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 diff --git a/src/LogExpert/Licenses/Nlog.license.txt b/Licenses/Nlog.license.txt similarity index 98% rename from src/LogExpert/Licenses/Nlog.license.txt rename to Licenses/Nlog.license.txt index bfb68fb1..5002772d 100644 --- a/src/LogExpert/Licenses/Nlog.license.txt +++ b/Licenses/Nlog.license.txt @@ -1,30 +1,30 @@ -Copyright (c) 2004-2017 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -* Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -* Neither the name of Jaroslaw Kowalski nor the names of its - contributors may be used to endorse or promote products derived from this - software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. +Copyright (c) 2004-2017 Jaroslaw Kowalski , Kim Christensen, Julian Verdurmen + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Jaroslaw Kowalski nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/LogExpert/Licenses/WinformsUI.Docking.license.txt b/Licenses/WinformsUI.Docking.license.txt similarity index 99% rename from src/LogExpert/Licenses/WinformsUI.Docking.license.txt rename to Licenses/WinformsUI.Docking.license.txt index 95e396c3..0d8a18ba 100644 --- a/src/LogExpert/Licenses/WinformsUI.Docking.license.txt +++ b/Licenses/WinformsUI.Docking.license.txt @@ -1,9 +1,9 @@ -The MIT License - -Copyright (c) 2007 Weifen Luo (email: weifenluo@yahoo.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +The MIT License + +Copyright (c) 2007 Weifen Luo (email: weifenluo@yahoo.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 602c4873..8821a046 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Summary of (most) features: * Portable (all options / settings saved in application startup directory) # Download -Follow the [Link](https://github.com/zarunbal/LogExpert/releases/latest) and download the latest package. Just extract it where you want and execute the application or download the Setup and install it +Follow the [Link](https://github.com/LogExperts/LogExpert/releases/latest) and download the latest package. Just extract it where you want and execute the application or download the Setup and install it Or Install via chocolatey @@ -62,7 +62,7 @@ Please checkout the wiki for FAQ / HELP / Informations / Examples - dont use AutoScaleMode for single GUI controls like Buttons etc. - dont use AutoScaleDimensions for single GUI controls like Buttons etc. -https://github.com/zarunbal/LogExpert/wiki +https://github.com/LogExperts/LogExpert/wiki # Discord Server https://discord.gg/SjxkuckRe9 @@ -71,8 +71,8 @@ https://discord.gg/SjxkuckRe9 ### Contributors This project exists thanks to all the people who contribute. - - + + Made with [contrib.rocks](https://contrib.rocks). diff --git a/build/Build.cs b/build/Build.cs index 43dc4947..0e700887 100644 --- a/build/Build.cs +++ b/build/Build.cs @@ -245,9 +245,9 @@ protected override void OnBuildInitialized() { Log.Information($"AssemblyVersion {VersionString}\r\nAssemblyFileVersion {VersionFileString}\r\nAssemblyInformationalVersion {VersionInformationString}"); - AbsolutePath assemblyVersion = SourceDirectory / "Solution Items" / "AssemblyVersion.cs"; + AbsolutePath assemblyInfo = SourceDirectory / "Solution Items" / "AssemblyInfo.cs"; - string text = assemblyVersion.ReadAllText(); + string text = assemblyInfo.ReadAllText(); Regex configurationRegex = AssemblyConfiguration(); Regex assemblyVersionRegex = AssemblyVersion(); Regex assemblyFileVersionRegex = AssemblyFileVersion(); @@ -258,11 +258,11 @@ protected override void OnBuildInitialized() text = assemblyFileVersionRegex.Replace(text, (match) => ReplaceVersionMatch(match, VersionFileString)); text = assemblyInformationalVersionRegex.Replace(text, (match) => ReplaceVersionMatch(match, VersionInformationString)); - Log.Verbose("Content of AssemblyVersion file"); + Log.Verbose("Content of AssemblyInfo.cs file"); Log.Verbose(text); Log.Verbose("End of Content"); - assemblyVersion.WriteAllText(text); + assemblyInfo.WriteAllText(text); SourceDirectory.GlobFiles("**sftp-plugin/*.cs").ForEach(file => { @@ -443,7 +443,7 @@ protected override void OnBuildInitialized() AppveyorArtifacts.ForEach((artifact) => { - Process proc = new Process(); + var proc = new Process(); proc.StartInfo = new ProcessStartInfo("appveyor", $"PushArtifact \"{artifact}\""); if (!proc.Start()) { @@ -464,7 +464,7 @@ protected override void OnBuildInitialized() { AbsolutePath logExpertApplicationData = SpecialFolder(SpecialFolders.ApplicationData) / "LogExpert"; - DirectoryInfo info = new DirectoryInfo(logExpertApplicationData); + var info = new DirectoryInfo(logExpertApplicationData); info.GetDirectories().ForEach(a => a.Delete(true)); logExpertApplicationData.DeleteDirectory(); }); @@ -474,7 +474,7 @@ protected override void OnBuildInitialized() { AbsolutePath logExpertDocuments = SpecialFolder(SpecialFolders.UserProfile) / "Documents" / "LogExpert"; - DirectoryInfo info = new DirectoryInfo(logExpertDocuments); + var info = new DirectoryInfo(logExpertDocuments); info.GetDirectories().ForEach(a => a.Delete(true)); logExpertDocuments.DeleteDirectory(); }); diff --git a/build/_build.csproj b/build/_build.csproj index d11d75f7..d5eadde9 100644 --- a/build/_build.csproj +++ b/build/_build.csproj @@ -3,7 +3,6 @@ Exe net8.0 - false False CS0649;CS0169 @@ -12,14 +11,14 @@ - - + + all runtime; build; native; contentfiles; analyzers - + diff --git a/chocolatey/logexpert.portable.nuspec.template b/chocolatey/logexpert.portable.nuspec.template index b6f32b7f..de0df86d 100644 --- a/chocolatey/logexpert.portable.nuspec.template +++ b/chocolatey/logexpert.portable.nuspec.template @@ -4,17 +4,14 @@ logexpert ##version## LogExpert - Zarunbal Previous:Hagen Raab - Zarunbal - https://cdn.rawgit.com/zarunbal/LogExpert/v##version##/LICENSE - https://github.com/zarunbal/LogExpert/tree/master/chocolatey - https://github.com/zarunbal/LogExpert - https://github.com/zarunbal/LogExpert/issues - https://github.com/zarunbal/LogExpert/releases/tag/v##version## + Zarunbal, Hagen Raab, Hirogen, RandallFlagg and others + Zarunbal, Hirogen + https://raw.githubusercontent.com/LogExperts/LogExpert/v##version##/LICENSE + https://github.com/LogExperts/LogExpert/tree/master/chocolatey + https://github.com/LogExperts/LogExpert + https://github.com/LogExperts/LogExpert/issues + https://github.com/LogExperts/LogExpert/releases/tag/v##version## false - - - LogExpert is a Windows tail program (a GUI replacement for the Unix tail command). Summary of (most) features: @@ -40,6 +37,9 @@ Summary of (most) features: LogExpert is log file viewing for the Pros. Original work Copyright (c) 2011 Hagen Raab, Modified work Copyright (c) 2017 Zarunbal LogExpert windows tail logging viewer troubleshooting + + + diff --git a/global.json b/global.json index b6b5c9f5..4c686a52 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "9.0.101" + "version": "9.0.301" } -} +} \ No newline at end of file diff --git a/lib/3rdparty.txt b/lib/3rdparty.txt index be26adc5..140f0a8a 100644 --- a/lib/3rdparty.txt +++ b/lib/3rdparty.txt @@ -8,7 +8,7 @@ Released under "MIT X11 license" DockPanel Suite: ---------------- -http://sourceforge.net/projects/dockpanelsuite/ +https://github.com/dockpanelsuite/dockpanelsuite Copyright (c) 2007 Weifen Luo (email: weifenluo@yahoo.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. diff --git a/src/.editorconfig b/src/.editorconfig new file mode 100644 index 00000000..0792babf --- /dev/null +++ b/src/.editorconfig @@ -0,0 +1,4877 @@ +# Remove the line below if you want to inherit .editorconfig settings from higher directories +root = true + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +indent_style = space +tab_width = 4 +charset = utf-8 + +# New line preferences +end_of_line = crlf +insert_final_newline = false + +#### .NET Code Actions #### + +# Type members +dotnet_hide_advanced_members = false +dotnet_member_insertion_location = with_other_members_of_the_same_kind +dotnet_property_generation_behavior = prefer_auto_properties + +# Symbol search +dotnet_search_reference_assemblies = true + +#### .NET Coding Conventions #### + +# Organize usings +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false +dotnet_style_qualification_for_field = false +dotnet_style_qualification_for_method = false +dotnet_style_qualification_for_property = false + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:warning +dotnet_style_predefined_type_for_member_access = true:warning + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:warning +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:warning +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:warning + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members + +# Expression-level preferences +dotnet_prefer_system_hash_code = true +dotnet_style_coalesce_expression = true:warning +dotnet_style_collection_initializer = true:warning +dotnet_style_explicit_tuple_names = true:warning +dotnet_style_namespace_match_folder = true:warning +dotnet_style_null_propagation = true:warning +dotnet_style_object_initializer = true:warning +dotnet_style_operator_placement_when_wrapping = beginning_of_line:warning +dotnet_style_prefer_auto_properties = true:warning +dotnet_style_prefer_collection_expression = when_types_loosely_match +dotnet_style_prefer_compound_assignment = true:warning +dotnet_style_prefer_conditional_expression_over_assignment = true:warning +dotnet_style_prefer_conditional_expression_over_return = true:warning +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed +dotnet_style_prefer_inferred_anonymous_type_member_names = true +dotnet_style_prefer_inferred_tuple_names = true +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:warning +dotnet_style_prefer_simplified_boolean_expressions = true:warning +dotnet_style_prefer_simplified_interpolation = true:warning + +# Field preferences +dotnet_style_readonly_field = true:warning + +# Parameter preferences +dotnet_code_quality_unused_parameters = all:warning + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +# New line preferences +dotnet_style_allow_multiple_blank_lines_experimental = false:warning +dotnet_style_allow_statement_immediately_after_block_experimental = false:warning + +#### C# Coding Conventions #### + +# var preferences +csharp_style_var_elsewhere = true:suggestion +csharp_style_var_for_built_in_types = true:warning +csharp_style_var_when_type_is_apparent = true:warning + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:suggestion +csharp_style_expression_bodied_constructors = false:warning +csharp_style_expression_bodied_indexers = true:suggestion +csharp_style_expression_bodied_lambdas = true:suggestion +csharp_style_expression_bodied_local_functions = true:suggestion +csharp_style_expression_bodied_methods = true:suggestion +csharp_style_expression_bodied_operators = true:suggestion +csharp_style_expression_bodied_properties = true:suggestion + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:warning +csharp_style_pattern_matching_over_is_with_cast_check = true:warning +csharp_style_prefer_extended_property_pattern = true:warning +csharp_style_prefer_not_pattern = true:warning +csharp_style_prefer_pattern_matching = true:warning +csharp_style_prefer_switch_expression = true:warning + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:warning +csharp_style_prefer_parameter_null_checking = true:suggestion + +# Modifier preferences +csharp_prefer_static_anonymous_function = true +csharp_prefer_static_local_function = true:warning +csharp_style_prefer_readonly_struct = true +csharp_style_prefer_readonly_struct_member = true +csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async + +# Code-block preferences +csharp_prefer_braces = true:warning +csharp_prefer_system_threading_lock = true:suggestion +csharp_prefer_simple_using_statement = true:warning +csharp_style_namespace_declarations = file_scoped:warning +csharp_style_prefer_method_group_conversion = true:warning +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_prefer_top_level_statements = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:warning +csharp_style_deconstructed_variable_declaration = true:warning +csharp_style_implicit_object_creation_when_type_is_apparent = true:warning +csharp_style_inlined_variable_declaration = true:warning +csharp_style_prefer_local_over_anonymous_function = true:warning +csharp_style_prefer_index_operator = true:warning +csharp_style_prefer_null_check_over_type_check = true:warning +csharp_style_prefer_range_operator = true:warning +csharp_style_prefer_utf8_string_literals = true +csharp_style_prefer_tuple_swap = true:warning +csharp_style_throw_expression = true:warning +csharp_style_unused_value_assignment_preference = discard_variable:warning +csharp_style_unused_value_expression_statement_preference = discard_variable:warning + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:warning + +# New line preferences +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = true:warning +csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = true +csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = false:warning +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false:warning +csharp_style_allow_embedded_statements_on_same_line_experimental = false:warning + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = true +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = false + +#### Naming styles #### + +# Naming rules + +dotnet_naming_rule.interface_should_be_begins_with_i.severity = warning +dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface +dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i + +dotnet_naming_rule.types_should_be_pascal_case.severity = warning +dotnet_naming_rule.types_should_be_pascal_case.symbols = types +dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = warning +dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case + +dotnet_naming_rule.no_single_letter_names.severity = error +dotnet_naming_rule.no_single_letter_names.symbols = parameters_and_variables +dotnet_naming_rule.no_single_letter_names.style = descriptive_names + +# Symbol specifications + +dotnet_naming_symbols.parameters_and_variables.applicable_kinds = parameter, local + +dotnet_naming_symbols.interface.applicable_kinds = interface +dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interface.required_modifiers = + +dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum +dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +# Naming styles + +dotnet_naming_style.descriptive_names.capitalization = camel_case +dotnet_naming_style.descriptive_names.minimum_word_length = 2 + +dotnet_naming_style.pascal_case.required_prefix = +dotnet_naming_style.pascal_case.required_suffix = +dotnet_naming_style.pascal_case.word_separator = +dotnet_naming_style.pascal_case.capitalization = pascal_case + +dotnet_naming_style.begins_with_i.required_prefix = I +dotnet_naming_style.begins_with_i.required_suffix = +dotnet_naming_style.begins_with_i.word_separator = +dotnet_naming_style.begins_with_i.capitalization = pascal_case + +#### The Nullable Knights #### + +dotnet_diagnostic.CS8625.severity = none +dotnet_diagnostic.CS8603.severity = none +dotnet_diagnostic.CS8618.severity = none +dotnet_diagnostic.CS8600.severity = none +dotnet_diagnostic.CS8602.severity = none +dotnet_diagnostic.CS8604.severity = none +dotnet_diagnostic.CS8622.severity = none +dotnet_diagnostic.CS8601.severity = none +dotnet_diagnostic.CS8605.severity = none +dotnet_diagnostic.CS0649.severity = none +dotnet_diagnostic.CS0169.severity = none +dotnet_diagnostic.CS1591.severity = none + +#### Analyzers Rules #### + +## Microsoft.CodeAnalysis.CSharp.CodeStyle + +# IDE0001: Simplify name +dotnet_diagnostic.IDE0001.severity = warning + +# IDE0002: Simplify member access +dotnet_diagnostic.IDE0002.severity = warning + +# IDE0003: Remove this or Me qualification +dotnet_diagnostic.IDE0003.severity = warning + +# IDE0004: Remove unnecessary cast +dotnet_diagnostic.IDE0004.severity = warning + +# IDE0005: Remove unnecessary import +dotnet_diagnostic.IDE0005.severity = none + +# IDE0005_gen: Remove unnecessary import (NotConfigurable) +#dotnet_diagnostic.IDE0005_gen.severity = silent + +# IDE0007: Use implicit type +dotnet_diagnostic.IDE0007.severity = warning + +# IDE0008: Use explicit type instead of 'var' +dotnet_diagnostic.IDE0008.severity = warning + +# IDE0009: Add this or Me qualification +dotnet_diagnostic.IDE0009.severity = warning + +# IDE0010: Add missing cases to switch statement +dotnet_diagnostic.IDE0010.severity = warning + +# IDE0011: Add braces +dotnet_diagnostic.IDE0011.severity = warning + +# IDE0016: Use throw expression +dotnet_diagnostic.IDE0016.severity = warning + +# IDE0017: Use object initializers +dotnet_diagnostic.IDE0017.severity = warning + +# IDE0018: Inline variable declaration +dotnet_diagnostic.IDE0018.severity = warning + +# IDE0019: Use pattern matching to avoid 'as' followed by a 'null' check +dotnet_diagnostic.IDE0019.severity = warning + +# IDE0020: Use pattern matching to avoid 'is' check followed by a cast (with variable) +dotnet_diagnostic.IDE0020.severity = warning + +# IDE0021: Use expression body for constructors +dotnet_diagnostic.IDE0021.severity = suggestion + +# IDE0022: Use expression body for methods +dotnet_diagnostic.IDE0022.severity = none + +# IDE0023: Use expression body for conversion operators +dotnet_diagnostic.IDE0023.severity = suggestion + +# IDE0024: Use expression body for operators +dotnet_diagnostic.IDE0024.severity = suggestion + +# IDE0025: Use expression body for properties +dotnet_diagnostic.IDE0025.severity = suggestion + +# IDE0026: Use expression body for indexers +dotnet_diagnostic.IDE0026.severity = suggestion + +# IDE0027: Use expression body for accessors +dotnet_diagnostic.IDE0027.severity = suggestion + +# IDE0028: Use collection initializers +dotnet_diagnostic.IDE0028.severity = warning + +# IDE0029: Use coalesce expression (non-nullable types) +dotnet_diagnostic.IDE0029.severity = warning + +# IDE0030: Use coalesce expression (nullable types) +dotnet_diagnostic.IDE0030.severity = warning + +# IDE0031: Use null propagation +dotnet_diagnostic.IDE0031.severity = warning + +# IDE0032: Use auto property +dotnet_diagnostic.IDE0032.severity = warning + +# IDE0033: Use explicitly provided tuple name +dotnet_diagnostic.IDE0033.severity = warning + +# IDE0034: Simplify default expression +dotnet_diagnostic.IDE0034.severity = warning + +# IDE0035: Remove unreachable code +dotnet_diagnostic.IDE0035.severity = warning + +# IDE0036: Order modifiers +dotnet_diagnostic.IDE0036.severity = warning + +# IDE0037: Use inferred member name +dotnet_diagnostic.IDE0037.severity = warning + +# IDE0038: Use pattern matching to avoid 'is' check followed by a cast (without variable) +dotnet_diagnostic.IDE0038.severity = warning + +# IDE0039: Use local function instead of lambda +dotnet_diagnostic.IDE0039.severity = warning + +# IDE0040: Add accessibility modifiers +dotnet_diagnostic.IDE0040.severity = warning + +# IDE0041: Use 'is null' check +dotnet_diagnostic.IDE0041.severity = warning + +# IDE0042: Deconstruct variable declaration +dotnet_diagnostic.IDE0042.severity = warning + +# IDE0043: Invalid format string +dotnet_diagnostic.IDE0043.severity = warning + +# IDE0044: Add readonly modifier +dotnet_diagnostic.IDE0044.severity = warning + +# IDE0045: Use conditional expression for assignment +dotnet_diagnostic.IDE0045.severity = warning + +# IDE0046: Use conditional expression for return +dotnet_diagnostic.IDE0046.severity = suggestion + +# IDE0047: Remove unnecessary parentheses +dotnet_diagnostic.IDE0047.severity = warning + +# IDE0048: Add parentheses for clarity +dotnet_diagnostic.IDE0048.severity = warning + +# IDE0049: Use language keywords instead of framework type names for type references +dotnet_diagnostic.IDE0049.severity = warning + +# IDE0050: Convert anonymous type to tuple +dotnet_diagnostic.IDE0050.severity = warning + +# IDE0051: Remove unused private member +dotnet_diagnostic.IDE0051.severity = warning + +# IDE0052: Remove unused private member +dotnet_diagnostic.IDE0052.severity = warning + +# IDE0053: Use expression body for lambdas +dotnet_diagnostic.IDE0053.severity = suggestion + +# IDE0054: Use compound assignment +dotnet_diagnostic.IDE0054.severity = warning + +# IDE0055: Fix formatting +dotnet_diagnostic.IDE0055.severity = none + +# IDE0056: Use index operator +dotnet_diagnostic.IDE0056.severity = warning + +# IDE0057: Use range operator +dotnet_diagnostic.IDE0057.severity = warning + +# IDE0058: Remove unnecessary expression value +dotnet_diagnostic.IDE0058.severity = warning + +# IDE0059: Remove unnecessary value assignment +dotnet_diagnostic.IDE0059.severity = warning + +# IDE0060: Remove unused parameter +dotnet_diagnostic.IDE0060.severity = warning + +# IDE0061: Use expression body for local functions +dotnet_diagnostic.IDE0061.severity = suggestion + +# IDE0062: Make local function static +dotnet_diagnostic.IDE0062.severity = warning + +# IDE0063: Use simple using statement +dotnet_diagnostic.IDE0063.severity = warning + +# IDE0064: Make struct fields writable +dotnet_diagnostic.IDE0064.severity = warning + +# IDE0065: using directive placement +dotnet_diagnostic.IDE0065.severity = warning + +# IDE0066: Use switch expression +dotnet_diagnostic.IDE0066.severity = warning + +# IDE0070: Use 'System.HashCode' +dotnet_diagnostic.IDE0070.severity = warning + +# IDE0071: Simplify interpolation +dotnet_diagnostic.IDE0071.severity = warning + +# IDE0072: Add missing cases to switch expression +dotnet_diagnostic.IDE0072.severity = warning + +# IDE0073: Require file header +dotnet_diagnostic.IDE0073.severity = warning + +# IDE0074: Use coalesce compound assignment +dotnet_diagnostic.IDE0074.severity = warning + +# IDE0075: Simplify conditional expression +dotnet_diagnostic.IDE0075.severity = warning + +# IDE0076: Remove invalid global 'SuppressMessageAttribute' +dotnet_diagnostic.IDE0076.severity = warning + +# IDE0077: Avoid legacy format target in global 'SuppressMessageAttribute' +dotnet_diagnostic.IDE0077.severity = warning + +# IDE0078: Use pattern matching +dotnet_diagnostic.IDE0078.severity = warning + +# IDE0079: Remove unnecessary suppression +dotnet_diagnostic.IDE0079.severity = warning + +# IDE0080: Remove unnecessary suppression operator +dotnet_diagnostic.IDE0080.severity = warning + +# IDE0081: Remove 'ByVal' +dotnet_diagnostic.IDE0081.severity = warning + +# IDE0082: Convert 'typeof' to 'nameof' +dotnet_diagnostic.IDE0082.severity = warning + +# IDE0083: Use pattern matching ('not' operator) +dotnet_diagnostic.IDE0083.severity = warning + +# IDE0084: Use pattern matching ('IsNot' operator) +dotnet_diagnostic.IDE0084.severity = warning + +# IDE0090: Simplify new expression +dotnet_diagnostic.IDE0090.severity = warning + +# IDE0100: Remove unnecessary equality operator +dotnet_diagnostic.IDE0100.severity = warning + +# IDE0110: Remove unnecessary discard +dotnet_diagnostic.IDE0110.severity = warning + +# IDE0120: Simplify LINQ expression +dotnet_diagnostic.IDE0120.severity = warning + +# IDE0130: Namespace does not match folder structure +dotnet_diagnostic.IDE0130.severity = warning + +# IDE0140: Simplify object creation +dotnet_diagnostic.IDE0140.severity = warning + +# IDE0150: Prefer 'null' check over type check +dotnet_diagnostic.IDE0150.severity = warning + +# IDE0160: Convert to block scoped namespace +dotnet_diagnostic.IDE0160.severity = none + +# IDE0161: Convert to file-scoped namespace +dotnet_diagnostic.IDE0161.severity = warning + +# IDE0170: Property pattern can be simplified +dotnet_diagnostic.IDE0170.severity = warning + +# IDE0180: Use tuple to swap values +dotnet_diagnostic.IDE0180.severity = warning + +# IDE0190: Null check can be simplified +dotnet_diagnostic.IDE0190.severity = warning + +# IDE0200: Remove unnecessary lambda expression +dotnet_diagnostic.IDE0200.severity = warning + +# IDE1005: Use conditional delegate call +dotnet_diagnostic.IDE1005.severity = warning + +# IDE1006: Naming Styles +dotnet_diagnostic.IDE1006.severity = warning + +# IDE2000: Avoid multiple blank lines +dotnet_diagnostic.IDE2000.severity = warning + +# IDE2001: Embedded statements must be on their own line +dotnet_diagnostic.IDE2001.severity = warning + +# IDE2002: Consecutive braces must not have blank line between them +dotnet_diagnostic.IDE2002.severity = warning + +# IDE2003: Blank line required between block and subsequent statement +dotnet_diagnostic.IDE2003.severity = warning + +# IDE2004: Blank line not allowed after constructor initializer colon +dotnet_diagnostic.IDE2004.severity = warning + +# RemoveUnnecessaryImportsFixable: Remove unnecessary imports fixable (NotConfigurable) +#dotnet_diagnostic.RemoveUnnecessaryImportsFixable.severity = silent + +## Microsoft.CodeAnalysis.CSharp.NetAnalyzers + +# CA1000: Do not declare static members on generic types +dotnet_diagnostic.CA1000.severity = warning +dotnet_code_quality.CA1000.api_surface = all + +# CA1001: Types that own disposable fields should be disposable +dotnet_diagnostic.CA1001.severity = warning +dotnet_code_quality.CA1001.excluded_symbol_names = +dotnet_code_quality.CA1001.excluded_type_names_with_derived_types = + +# CA1002: Do not expose generic lists +dotnet_diagnostic.CA1002.severity = suggestion +dotnet_code_quality.CA1002.api_surface = public + +# CA1003: Use generic event handler instances +dotnet_diagnostic.CA1003.severity = warning +dotnet_code_quality.CA1003.api_surface = all + +# CA1005: Avoid excessive parameters on generic types +dotnet_diagnostic.CA1005.severity = suggestion +dotnet_code_quality.CA1005.api_surface = all + +# CA1008: Enums should have zero value +dotnet_diagnostic.CA1008.severity = warning +dotnet_code_quality.CA1008.api_surface = all + +# CA1010: Generic interface should also be implemented +dotnet_diagnostic.CA1010.severity = warning +dotnet_code_quality.CA1010.api_surface = all +dotnet_code_quality.CA1010.additional_required_generic_interfaces = + +# CA1012: Abstract types should not have public constructors +dotnet_diagnostic.CA1012.severity = warning +dotnet_code_quality.CA1012.api_surface = all + +# CA1014: Mark assemblies with CLSCompliant +dotnet_diagnostic.CA1014.severity = warning + +# CA1016: Mark assemblies with assembly version +dotnet_diagnostic.CA1016.severity = warning + +# CA1017: Mark assemblies with ComVisible +dotnet_diagnostic.CA1017.severity = warning + +# CA1018: Mark attributes with AttributeUsageAttribute +dotnet_diagnostic.CA1018.severity = warning + +# CA1019: Define accessors for attribute arguments +dotnet_diagnostic.CA1019.severity = warning + +# CA1021: Avoid out parameters +dotnet_diagnostic.CA1021.severity = suggestion +dotnet_code_quality.CA1021.api_surface = all + +# CA1024: Use properties where appropriate +dotnet_diagnostic.CA1024.severity = suggestion +dotnet_code_quality.CA1024.api_surface = all + +# CA1027: Mark enums with FlagsAttribute +dotnet_diagnostic.CA1027.severity = suggestion +dotnet_code_quality.CA1027.api_surface = all + +# CA1028: Enum Storage should be Int32 +dotnet_diagnostic.CA1028.severity = warning +dotnet_code_quality.CA1028.api_surface = all + +# CA1030: Use events where appropriate +dotnet_diagnostic.CA1030.severity = suggestion +dotnet_code_quality.CA1030.api_surface = all + +# CA1031: Do not catch general exception types +dotnet_diagnostic.CA1031.severity = warning +dotnet_code_quality.CA1031.disallowed_symbol_names = + +# CA1032: Implement standard exception constructors +dotnet_diagnostic.CA1032.severity = warning + +# CA1033: Interface methods should be callable by child types +dotnet_diagnostic.CA1033.severity = warning + +# CA1034: Nested types should not be visible +dotnet_diagnostic.CA1034.severity = warning + +# CA1036: Override methods on comparable types +dotnet_diagnostic.CA1036.severity = warning +dotnet_code_quality.CA1036.api_surface = all + +# CA1040: Avoid empty interfaces +dotnet_diagnostic.CA1040.severity = suggestion +dotnet_code_quality.CA1040.api_surface = all + +# CA1041: Provide ObsoleteAttribute message +dotnet_diagnostic.CA1041.severity = warning +dotnet_code_quality.CA1041.api_surface = all + +# CA1043: Use Integral Or String Argument For Indexers +dotnet_diagnostic.CA1043.severity = warning +dotnet_code_quality.CA1043.api_surface = all + +# CA1044: Properties should not be write only +dotnet_diagnostic.CA1044.severity = warning +dotnet_code_quality.CA1044.api_surface = all + +# CA1045: Do not pass types by reference +dotnet_diagnostic.CA1045.severity = suggestion +dotnet_code_quality.CA1045.api_surface = all + +# CA1046: Do not overload equality operator on reference types +dotnet_diagnostic.CA1046.severity = warning +dotnet_code_quality.CA1046.api_surface = all + +# CA1047: Do not declare protected member in sealed type +dotnet_diagnostic.CA1047.severity = warning +dotnet_code_quality.CA1047.api_surface = all + +# CA1050: Declare types in namespaces +dotnet_diagnostic.CA1050.severity = warning + +# CA1051: Do not declare visible instance fields +dotnet_diagnostic.CA1051.severity = warning +dotnet_code_quality.CA1051.api_surface = all +dotnet_code_quality.CA1051.exclude_structs = false + +# CA1052: Static holder types should be Static or NotInheritable +dotnet_diagnostic.CA1052.severity = warning +dotnet_code_quality.CA1052.api_surface = all + +# CA1053: Static holder types should not have default constructors +dotnet_diagnostic.CA1053.severity = warning +dotnet_code_quality.CA1053.api_surface = all + +# CA1054: URI-like parameters should not be strings +dotnet_diagnostic.CA1054.severity = warning +dotnet_code_quality.CA1054.api_surface = all + +# CA1055: URI-like return values should not be strings +dotnet_diagnostic.CA1055.severity = warning +dotnet_code_quality.CA1055.api_surface = all + +# CA1056: URI-like properties should not be strings +dotnet_diagnostic.CA1056.severity = warning +dotnet_code_quality.CA1056.api_surface = all + +# CA1058: Types should not extend certain base types +dotnet_diagnostic.CA1058.severity = warning +dotnet_code_quality.CA1058.api_surface = all + +# CA1060: Move pinvokes to native methods class +dotnet_diagnostic.CA1060.severity = warning + +# CA1061: Do not hide base class methods +dotnet_diagnostic.CA1061.severity = warning + +# CA1062: Validate arguments of public methods +dotnet_diagnostic.CA1062.severity = warning +dotnet_code_quality.CA1062.excluded_symbol_names = +dotnet_code_quality.CA1062.excluded_type_names_with_derived_types = +dotnet_code_quality.CA1062.exclude_extension_method_this_parameter = false +dotnet_code_quality.CA1062.null_check_validation_methods = + +# CA1063: Implement IDisposable Correctly +dotnet_diagnostic.CA1063.severity = warning +dotnet_code_quality.CA1063.api_surface = all + +# CA1064: Exceptions should be public +dotnet_diagnostic.CA1064.severity = warning + +# CA1065: Do not raise exceptions in unexpected locations +dotnet_diagnostic.CA1065.severity = warning + +# CA1066: Implement IEquatable when overriding Object.Equals +dotnet_diagnostic.CA1066.severity = warning + +# CA1067: Override Object.Equals(object) when implementing IEquatable +dotnet_diagnostic.CA1067.severity = warning + +# CA1068: CancellationToken parameters must come last +dotnet_diagnostic.CA1068.severity = warning +dotnet_code_quality.CA1068.api_surface = all +dotnet_code_quality.CA1068.excluded_symbol_names = +dotnet_code_quality.CA1068.excluded_type_names_with_derived_types = + +# CA1069: Enums values should not be duplicated +dotnet_diagnostic.CA1069.severity = warning + +# CA1070: Do not declare event fields as virtual +dotnet_diagnostic.CA1070.severity = warning +dotnet_code_quality.CA1070.api_surface = all + +# CA1200: Avoid using cref tags with a prefix +dotnet_diagnostic.CA1200.severity = warning + +# CA1303: Do not pass literals as localized parameters +dotnet_diagnostic.CA1303.severity = warning +dotnet_code_quality.CA1303.excluded_symbol_names = +dotnet_code_quality.CA1303.excluded_type_names_with_derived_types = +dotnet_code_quality.CA1303.use_naming_heuristic = true + +# CA1304: Specify CultureInfo +dotnet_diagnostic.CA1304.severity = warning +dotnet_code_quality.CA1304.excluded_symbol_names = +dotnet_code_quality.CA1304.excluded_type_names_with_derived_types = + +# CA1305: Specify IFormatProvider +dotnet_diagnostic.CA1305.severity = warning + +# CA1307: Specify StringComparison for clarity +dotnet_diagnostic.CA1307.severity = warning + +# CA1308: Normalize strings to uppercase +dotnet_diagnostic.CA1308.severity = warning + +# CA1309: Use ordinal string comparison +dotnet_diagnostic.CA1309.severity = warning + +# CA1310: Specify StringComparison for correctness +dotnet_diagnostic.CA1310.severity = warning + +# CA1401: P/Invokes should not be visible +dotnet_diagnostic.CA1401.severity = warning + +# CA1416: Validate platform compatibility +dotnet_diagnostic.CA1416.severity = warning +dotnet_code_quality.CA1416.enable_platform_analyzer_on_pre_net5_target = true + +# CA1417: Do not use 'OutAttribute' on string parameters for P/Invokes +dotnet_diagnostic.CA1417.severity = warning + +# CA1418: Use valid platform string +dotnet_diagnostic.CA1418.severity = warning + +# CA1419: Provide a parameterless constructor that is as visible as the containing type for concrete types derived from 'System.Runtime.InteropServices.SafeHandle' +dotnet_diagnostic.CA1419.severity = warning + +# CA1501: Avoid excessive inheritance +dotnet_diagnostic.CA1501.severity = suggestion +dotnet_code_quality.CA1501.additional_inheritance_excluded_symbol_names = + +# CA1502: Avoid excessive complexity +dotnet_diagnostic.CA1502.severity = suggestion + +# CA1505: Avoid unmaintainable code +dotnet_diagnostic.CA1505.severity = suggestion + +# CA1506: Avoid excessive class coupling +dotnet_diagnostic.CA1506.severity = suggestion + +# CA1507: Use nameof to express symbol names +dotnet_diagnostic.CA1507.severity = warning + +# CA1508: Avoid dead conditional code +dotnet_diagnostic.CA1508.severity = warning +dotnet_code_quality.CA1508.excluded_symbol_names = +dotnet_code_quality.CA1508.excluded_type_names_with_derived_types = + +# CA1509: Invalid entry in code metrics rule specification file +dotnet_diagnostic.CA1509.severity = warning + +# CA1510: Use ArgumentNullException throw helper +dotnet_diagnostic.CA1510.severity = warning + +# CA1511: Use ArgumentException throw helper +dotnet_diagnostic.CA1511.severity = warning + +# CA1512: Use ArgumentOutOfRangeException throw helper +dotnet_diagnostic.CA1512.severity = warning + +# CA1513: Use ObjectDisposedException throw helper +dotnet_diagnostic.CA1513.severity = warning + +# CA1514: Avoid redundant length argument +dotnet_diagnostic.CA1514.severity = warning + +# CA1515: Consider making public types internal +dotnet_diagnostic.CA1515.severity = none + +# CA1700: Do not name enum values 'Reserved' +dotnet_diagnostic.CA1700.severity = warning +dotnet_code_quality.CA1700.api_surface = all + +# CA1707: Identifiers should not contain underscores +dotnet_diagnostic.CA1707.severity = none +# dotnet_code_quality.CA1707.api_surface = all + +# CA1708: Identifiers should differ by more than case +dotnet_diagnostic.CA1708.severity = warning +dotnet_code_quality.CA1708.api_surface = all + +# CA1710: Identifiers should have correct suffix +dotnet_diagnostic.CA1710.severity = warning +dotnet_code_quality.CA1710.api_surface = all +dotnet_code_quality.CA1710.exclude_indirect_base_types = false +dotnet_code_quality.CA1710.additional_required_suffixes = T:System.Collections.Generic.IReadOnlyList`1->List|T:System.Collections.Generic.IList`1->List|T:System.Collections.Generic.IReadOnlySet`1->Set|T:System.Collections.Generic.ISet`1->Set|T:System.Collections.Generic.IReadOnlyCollection`1->Collection + +# CA1711: Identifiers should not have incorrect suffix +dotnet_diagnostic.CA1711.severity = warning +dotnet_code_quality.CA1711.api_surface = all +dotnet_code_quality.CA1711.allowed_suffixes = + +# CA1712: Do not prefix enum values with type name +dotnet_diagnostic.CA1712.severity = warning +dotnet_code_quality.CA1712.enum_values_prefix_trigger = AnyEnumValue + +# CA1713: Events should not have 'Before' or 'After' prefix +dotnet_diagnostic.CA1713.severity = warning + +# CA1714: Flags enums should have plural names +dotnet_diagnostic.CA1714.severity = warning +dotnet_code_quality.CA1714.api_surface = all + +# CA1715: Identifiers should have correct prefix +dotnet_diagnostic.CA1715.severity = warning +dotnet_code_quality.CA1715.api_surface = all +dotnet_code_quality.CA1715.exclude_single_letter_type_parameters = false + +# CA1716: Identifiers should not match keywords +dotnet_diagnostic.CA1716.severity = warning +dotnet_code_quality.CA1716.api_surface = all +dotnet_code_quality.CA1716.analyzed_symbol_kinds = Namespace, NamedType, Method, Property, Event, Parameter + +# CA1717: Only FlagsAttribute enums should have plural names +dotnet_diagnostic.CA1717.severity = warning +dotnet_code_quality.CA1717.api_surface = all + +# CA1720: Identifier contains type name +dotnet_diagnostic.CA1720.severity = warning +dotnet_code_quality.CA1720.api_surface = all + +# CA1721: Property names should not match get methods +dotnet_diagnostic.CA1721.severity = warning +dotnet_code_quality.CA1721.api_surface = all + +# CA1724: Type names should not match namespaces +dotnet_diagnostic.CA1724.severity = warning + +# CA1725: Parameter names should match base declaration +dotnet_diagnostic.CA1725.severity = warning +dotnet_code_quality.CA1725.api_surface = all + +# CA1727: Use PascalCase for named placeholders +dotnet_diagnostic.CA1727.severity = warning + +# CA1801: Review unused parameters +dotnet_diagnostic.CA1801.severity = warning +dotnet_code_quality.CA1801.api_surface = all + +# CA1802: Use literals where appropriate +dotnet_diagnostic.CA1802.severity = warning +dotnet_code_quality.CA1802.api_surface = all +dotnet_code_quality.CA1802.required_modifiers = none + +# CA1805: Do not initialize unnecessarily +dotnet_diagnostic.CA1805.severity = warning + +# CA1806: Do not ignore method results +dotnet_diagnostic.CA1806.severity = warning +dotnet_code_quality.CA1806.additional_use_results_methods = + +# CA1810: Initialize reference type static fields inline +dotnet_diagnostic.CA1810.severity = warning + +# CA1812: Avoid uninstantiated internal classes +dotnet_diagnostic.CA1812.severity = None + +# CA1813: Avoid unsealed attributes +dotnet_diagnostic.CA1813.severity = suggestion + +# CA1814: Prefer jagged arrays over multidimensional +dotnet_diagnostic.CA1814.severity = suggestion + +# CA1815: Override equals and operator equals on value types +dotnet_diagnostic.CA1815.severity = warning +dotnet_code_quality.CA1815.api_surface = all + +# CA1816: Dispose methods should call SuppressFinalize +dotnet_diagnostic.CA1816.severity = warning + +# CA1819: Properties should not return arrays +dotnet_diagnostic.CA1819.severity = suggestion +dotnet_code_quality.CA1819.api_surface = all + +# CA1820: Test for empty strings using string length +dotnet_diagnostic.CA1820.severity = warning + +# CA1821: Remove empty Finalizers +dotnet_diagnostic.CA1821.severity = warning + +# CA1822: Mark members as static +dotnet_diagnostic.CA1822.severity = warning +dotnet_code_quality.CA1822.api_surface = all + +# CA1823: Avoid unused private fields +dotnet_diagnostic.CA1823.severity = warning + +# CA1824: Mark assemblies with NeutralResourcesLanguageAttribute +dotnet_diagnostic.CA1824.severity = warning + +# CA1825: Avoid zero-length array allocations +dotnet_diagnostic.CA1825.severity = warning + +# CA1826: Do not use Enumerable methods on indexable collections +dotnet_diagnostic.CA1826.severity = warning +dotnet_code_quality.CA1826.exclude_ordefault_methods = false + +# CA1827: Do not use Count() or LongCount() when Any() can be used +dotnet_diagnostic.CA1827.severity = warning + +# CA1828: Do not use CountAsync() or LongCountAsync() when AnyAsync() can be used +dotnet_diagnostic.CA1828.severity = warning + +# CA1829: Use Length/Count property instead of Count() when available +dotnet_diagnostic.CA1829.severity = warning + +# CA1830: Prefer strongly-typed Append and Insert method overloads on StringBuilder +dotnet_diagnostic.CA1830.severity = warning + +# CA1831: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +dotnet_diagnostic.CA1831.severity = warning + +# CA1832: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +dotnet_diagnostic.CA1832.severity = warning + +# CA1833: Use AsSpan or AsMemory instead of Range-based indexers when appropriate +dotnet_diagnostic.CA1833.severity = warning + +# CA1834: Consider using 'StringBuilder.Append(char)' when applicable +dotnet_diagnostic.CA1834.severity = warning + +# CA1835: Prefer the 'Memory'-based overloads for 'ReadAsync' and 'WriteAsync' +dotnet_diagnostic.CA1835.severity = warning + +# CA1836: Prefer IsEmpty over Count +dotnet_diagnostic.CA1836.severity = warning + +# CA1837: Use 'Environment.ProcessId' +dotnet_diagnostic.CA1837.severity = warning + +# CA1838: Avoid 'StringBuilder' parameters for P/Invokes +dotnet_diagnostic.CA1838.severity = warning + +# CA1839: Use 'Environment.ProcessPath' +dotnet_diagnostic.CA1839.severity = warning + +# CA1840: Use 'Environment.CurrentManagedThreadId' +dotnet_diagnostic.CA1840.severity = warning + +# CA1841: Prefer Dictionary.Contains methods +dotnet_diagnostic.CA1841.severity = warning + +# CA1842: Do not use 'WhenAll' with a single task +dotnet_diagnostic.CA1842.severity = warning + +# CA1843: Do not use 'WaitAll' with a single task +dotnet_diagnostic.CA1843.severity = warning + +# CA1844: Provide memory-based overrides of async methods when subclassing 'Stream' +dotnet_diagnostic.CA1844.severity = warning + +# CA1845: Use span-based 'string.Concat' +dotnet_diagnostic.CA1845.severity = warning + +# CA1846: Prefer 'AsSpan' over 'Substring' +dotnet_diagnostic.CA1846.severity = warning + +# CA1847: Use char literal for a single character lookup +dotnet_diagnostic.CA1847.severity = warning + +# CA1848: Use the LoggerMessage delegates +dotnet_diagnostic.CA1848.severity = warning + +# CA1849: Call async methods when in an async method +dotnet_diagnostic.CA1849.severity = warning + +# CA1850: Prefer static 'HashData' method over 'ComputeHash' +dotnet_diagnostic.CA1850.severity = warning + +# CA2000: Dispose objects before losing scope +dotnet_diagnostic.CA2000.severity = None +dotnet_code_quality.CA2000.excluded_symbol_names = +dotnet_code_quality.CA2000.excluded_type_names_with_derived_types = +dotnet_code_quality.CA2000.dispose_analysis_kind = NonExceptionPaths +dotnet_code_quality.CA2000.dispose_ownership_transfer_at_constructor = false +dotnet_code_quality.CA2000.dispose_ownership_transfer_at_method_call = false + +# CA2002: Do not lock on objects with weak identity +dotnet_diagnostic.CA2002.severity = warning + +# CA2007: Consider calling ConfigureAwait on the awaited task +dotnet_diagnostic.CA2007.severity = warning +dotnet_code_quality.CA2007.exclude_async_void_methods = false +dotnet_code_quality.CA2007.output_kind = ConsoleApplication, DynamicallyLinkedLibrary, NetModule, WindowsApplication, WindowsRuntimeApplication, WindowsRuntimeMetadata + +# CA2008: Do not create tasks without passing a TaskScheduler +dotnet_diagnostic.CA2008.severity = warning + +# CA2009: Do not call ToImmutableCollection on an ImmutableCollection value +dotnet_diagnostic.CA2009.severity = warning + +# CA2011: Avoid infinite recursion +dotnet_diagnostic.CA2011.severity = warning + +# CA2012: Use ValueTasks correctly +dotnet_diagnostic.CA2012.severity = warning + +# CA2013: Do not use ReferenceEquals with value types +dotnet_diagnostic.CA2013.severity = warning + +# CA2014: Do not use stackalloc in loops +dotnet_diagnostic.CA2014.severity = warning + +# CA2015: Do not define finalizers for types derived from MemoryManager +dotnet_diagnostic.CA2015.severity = warning + +# CA2016: Forward the 'CancellationToken' parameter to methods that take one +dotnet_diagnostic.CA2016.severity = warning + +# CA2017: Parameter count mismatch +dotnet_diagnostic.CA2017.severity = warning + +# CA2018: 'Buffer.BlockCopy' expects the number of bytes to be copied for the 'count' argument +dotnet_diagnostic.CA2018.severity = warning + +# CA2100: Review SQL queries for security vulnerabilities +dotnet_diagnostic.CA2100.severity = warning +dotnet_code_quality.CAXXXX.excluded_symbol_names = +dotnet_code_quality.CAXXXX.excluded_type_names_with_derived_types = + +# CA2101: Specify marshaling for P/Invoke string arguments +dotnet_diagnostic.CA2101.severity = warning + +# CA2109: Review visible event handlers +dotnet_diagnostic.CA2109.severity = warning + +# CA2119: Seal methods that satisfy private interfaces +dotnet_diagnostic.CA2119.severity = warning + +# CA2153: Do Not Catch Corrupted State Exceptions +dotnet_diagnostic.CA2153.severity = warning + +# CA2200: Rethrow to preserve stack details +dotnet_diagnostic.CA2200.severity = warning + +# CA2201: Do not raise reserved exception types +dotnet_diagnostic.CA2201.severity = warning + +# CA2207: Initialize value type static fields inline +dotnet_diagnostic.CA2207.severity = warning + +# CA2208: Instantiate argument exceptions correctly +dotnet_diagnostic.CA2208.severity = warning +dotnet_code_quality.CA2208.api_surface = all + +# CA2211: Non-constant fields should not be visible +dotnet_diagnostic.CA2211.severity = warning + +# CA2213: Disposable fields should be disposed +dotnet_diagnostic.CA2213.severity = None + +# CA2214: Do not call overridable methods in constructors +dotnet_diagnostic.CA2214.severity = warning + +# CA2215: Dispose methods should call base class dispose +dotnet_diagnostic.CA2215.severity = warning + +# CA2216: Disposable types should declare finalizer +dotnet_diagnostic.CA2216.severity = warning + +# CA2217: Do not mark enums with FlagsAttribute +dotnet_diagnostic.CA2217.severity = warning +dotnet_code_quality.CA2217.api_surface = all + +# CA2218: Override GetHashCode on overriding Equals +dotnet_diagnostic.CA2218.severity = warning + +# CA2219: Do not raise exceptions in finally clauses +dotnet_diagnostic.CA2219.severity = warning + +# CA2224: Override Equals on overloading operator equals +dotnet_diagnostic.CA2224.severity = warning + +# CA2225: Operator overloads have named alternates +dotnet_diagnostic.CA2225.severity = warning +dotnet_code_quality.CA2225.api_surface = all + +# CA2226: Operators should have symmetrical overloads +dotnet_diagnostic.CA2226.severity = warning +dotnet_code_quality.CA2226.api_surface = all + +# CA2227: Collection properties should be read only +dotnet_diagnostic.CA2227.severity = suggestion + +# CA2229: Implement serialization constructors +dotnet_diagnostic.CA2229.severity = warning + +# CA2231: Overload operator equals on overriding value type Equals +dotnet_diagnostic.CA2231.severity = warning +dotnet_code_quality.CA2231.api_surface = all + +# CA2234: Pass system uri objects instead of strings +dotnet_diagnostic.CA2234.severity = warning +dotnet_code_quality.CA2234.api_surface = all + +# CA2235: Mark all non-serializable fields +dotnet_diagnostic.CA2235.severity = warning + +# CA2237: Mark ISerializable types with serializable +dotnet_diagnostic.CA2237.severity = warning + +# CA2241: Provide correct arguments to formatting methods +dotnet_diagnostic.CA2241.severity = warning +dotnet_code_quality.CA2241.additional_string_formatting_methods = +dotnet_code_quality.CA2241.try_determine_additional_string_formatting_methods_automatically = true + +# CA2242: Test for NaN correctly +dotnet_diagnostic.CA2242.severity = warning + +# CA2243: Attribute string literals should parse correctly +dotnet_diagnostic.CA2243.severity = warning + +# CA2244: Do not duplicate indexed element initializations +dotnet_diagnostic.CA2244.severity = warning + +# CA2245: Do not assign a property to itself +dotnet_diagnostic.CA2245.severity = warning + +# CA2246: Assigning symbol and its member in the same statement +dotnet_diagnostic.CA2246.severity = warning + +# CA2247: Argument passed to TaskCompletionSource constructor should be TaskCreationOptions enum instead of TaskContinuationOptions enum +dotnet_diagnostic.CA2247.severity = warning + +# CA2248: Provide correct 'enum' argument to 'Enum.HasFlag' +dotnet_diagnostic.CA2248.severity = warning + +# CA2249: Consider using 'string.Contains' instead of 'string.IndexOf' +dotnet_diagnostic.CA2249.severity = warning + +# CA2250: Use 'ThrowIfCancellationRequested' +dotnet_diagnostic.CA2250.severity = warning + +# CA2251: Use 'string.Equals' +dotnet_diagnostic.CA2251.severity = warning + +# CA2252: This API requires opting into preview features +dotnet_diagnostic.CA2252.severity = warning + +# CA2253: Named placeholders should not be numeric values +dotnet_diagnostic.CA2253.severity = warning + +# CA2254: Template should be a static expression +dotnet_diagnostic.CA2254.severity = warning + +# CA2255: The 'ModuleInitializer' attribute should not be used in libraries +dotnet_diagnostic.CA2255.severity = warning + +# CA2256: All members declared in parent interfaces must have an implementation in a DynamicInterfaceCastableImplementation-attributed interface +dotnet_diagnostic.CA2256.severity = warning + +# CA2257: Members defined on an interface with the 'DynamicInterfaceCastableImplementationAttribute' should be 'static' +dotnet_diagnostic.CA2257.severity = warning + +# CA2258: Providing a 'DynamicInterfaceCastableImplementation' interface in Visual Basic is unsupported +dotnet_diagnostic.CA2258.severity = warning + +# CA2300: Do not use insecure deserializer BinaryFormatter +dotnet_diagnostic.CA2300.severity = warning + +# CA2301: Do not call BinaryFormatter.Deserialize without first setting BinaryFormatter.Binder +dotnet_diagnostic.CA2301.severity = warning +dotnet_code_quality.CA2301.excluded_symbol_names = +dotnet_code_quality.CA2301.excluded_type_names_with_derived_types = + +# CA2302: Ensure BinaryFormatter.Binder is set before calling BinaryFormatter.Deserialize +dotnet_diagnostic.CA2302.severity = warning +dotnet_code_quality.CA2302.excluded_symbol_names = +dotnet_code_quality.CA2302.excluded_type_names_with_derived_types = + +# CA2305: Do not use insecure deserializer LosFormatter +dotnet_diagnostic.CA2305.severity = warning + +# CA2310: Do not use insecure deserializer NetDataContractSerializer +dotnet_diagnostic.CA2310.severity = warning + +# CA2311: Do not deserialize without first setting NetDataContractSerializer.Binder +dotnet_diagnostic.CA2311.severity = warning +dotnet_code_quality.CA2311.excluded_symbol_names = +dotnet_code_quality.CA2311.excluded_type_names_with_derived_types = + +# CA2312: Ensure NetDataContractSerializer.Binder is set before deserializing +dotnet_diagnostic.CA2312.severity = warning +dotnet_code_quality.CA2312.excluded_symbol_names = +dotnet_code_quality.CA2312.excluded_type_names_with_derived_types = + +# CA2315: Do not use insecure deserializer ObjectStateFormatter +dotnet_diagnostic.CA2315.severity = warning + +# CA2321: Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver +dotnet_diagnostic.CA2321.severity = warning +dotnet_code_quality.CA2321.excluded_symbol_names = +dotnet_code_quality.CA2321.excluded_type_names_with_derived_types = + +# CA2322: Ensure JavaScriptSerializer is not initialized with SimpleTypeResolver before deserializing +dotnet_diagnostic.CA2322.severity = warning +dotnet_code_quality.CA2322.excluded_symbol_names = +dotnet_code_quality.CA2322.excluded_type_names_with_derived_types = + +# CA2326: Do not use TypeNameHandling values other than None +dotnet_diagnostic.CA2326.severity = warning + +# CA2327: Do not use insecure JsonSerializerSettings +dotnet_diagnostic.CA2327.severity = warning +dotnet_code_quality.CA2327.excluded_symbol_names = +dotnet_code_quality.CA2327.excluded_type_names_with_derived_types = + +# CA2328: Ensure that JsonSerializerSettings are secure +dotnet_diagnostic.CA2328.severity = warning +dotnet_code_quality.CA2328.excluded_symbol_names = +dotnet_code_quality.CA2328.excluded_type_names_with_derived_types = + +# CA2329: Do not deserialize with JsonSerializer using an insecure configuration +dotnet_diagnostic.CA2329.severity = warning +dotnet_code_quality.CA2329.excluded_symbol_names = +dotnet_code_quality.CA2329.excluded_type_names_with_derived_types = + +# CA2330: Ensure that JsonSerializer has a secure configuration when deserializing +dotnet_diagnostic.CA2330.severity = warning +dotnet_code_quality.CA2330.excluded_symbol_names = +dotnet_code_quality.CA2330.excluded_type_names_with_derived_types = + +# CA2350: Do not use DataTable.ReadXml() with untrusted data +dotnet_diagnostic.CA2350.severity = warning + +# CA2351: Do not use DataSet.ReadXml() with untrusted data +dotnet_diagnostic.CA2351.severity = warning + +# CA2352: Unsafe DataSet or DataTable in serializable type can be vulnerable to remote code execution attacks +dotnet_diagnostic.CA2352.severity = warning + +# CA2353: Unsafe DataSet or DataTable in serializable type +dotnet_diagnostic.CA2353.severity = warning + +# CA2354: Unsafe DataSet or DataTable in deserialized object graph can be vulnerable to remote code execution attacks +dotnet_diagnostic.CA2354.severity = warning + +# CA2355: Unsafe DataSet or DataTable type found in deserializable object graph +dotnet_diagnostic.CA2355.severity = warning + +# CA2356: Unsafe DataSet or DataTable type in web deserializable object graph +dotnet_diagnostic.CA2356.severity = warning + +# CA2361: Ensure auto-generated class containing DataSet.ReadXml() is not used with untrusted data +dotnet_diagnostic.CA2361.severity = warning + +# CA2362: Unsafe DataSet or DataTable in auto-generated serializable type can be vulnerable to remote code execution attacks +dotnet_diagnostic.CA2362.severity = warning + +# CA3001: Review code for SQL injection vulnerabilities +dotnet_diagnostic.CA3001.severity = warning +dotnet_code_quality.CA3001.excluded_symbol_names = +dotnet_code_quality.CA3001.excluded_type_names_with_derived_types = + +# CA3002: Review code for XSS vulnerabilities +dotnet_diagnostic.CA3002.severity = warning +dotnet_code_quality.CA3002.excluded_symbol_names = +dotnet_code_quality.CA3002.excluded_type_names_with_derived_types = + +# CA3003: Review code for file path injection vulnerabilities +dotnet_diagnostic.CA3003.severity = warning +dotnet_code_quality.CA3003.excluded_symbol_names = +dotnet_code_quality.CA3003.excluded_type_names_with_derived_types = + +# CA3004: Review code for information disclosure vulnerabilities +dotnet_diagnostic.CA3004.severity = warning +dotnet_code_quality.CA3004.excluded_symbol_names = +dotnet_code_quality.CA3004.excluded_type_names_with_derived_types = + +# CA3005: Review code for LDAP injection vulnerabilities +dotnet_diagnostic.CA3005.severity = warning +dotnet_code_quality.CA3005.excluded_symbol_names = +dotnet_code_quality.CA3005.excluded_type_names_with_derived_types = + +# CA3006: Review code for process command injection vulnerabilities +dotnet_diagnostic.CA3006.severity = warning +dotnet_code_quality.CA3006.excluded_symbol_names = +dotnet_code_quality.CA3006.excluded_type_names_with_derived_types = + +# CA3007: Review code for open redirect vulnerabilities +dotnet_diagnostic.CA3007.severity = warning +dotnet_code_quality.CA3007.excluded_symbol_names = +dotnet_code_quality.CA3007.excluded_type_names_with_derived_types = + +# CA3008: Review code for XPath injection vulnerabilities +dotnet_diagnostic.CA3008.severity = warning +dotnet_code_quality.CA3008.excluded_symbol_names = +dotnet_code_quality.CA3008.excluded_type_names_with_derived_types = + +# CA3009: Review code for XML injection vulnerabilities +dotnet_diagnostic.CA3009.severity = warning +dotnet_code_quality.CA3009.excluded_symbol_names = +dotnet_code_quality.CA3009.excluded_type_names_with_derived_types = + +# CA3010: Review code for XAML injection vulnerabilities +dotnet_diagnostic.CA3010.severity = warning +dotnet_code_quality.CA3010.excluded_symbol_names = +dotnet_code_quality.CA3010.excluded_type_names_with_derived_types = + +# CA3011: Review code for DLL injection vulnerabilities +dotnet_diagnostic.CA3011.severity = warning +dotnet_code_quality.CA3011.excluded_symbol_names = +dotnet_code_quality.CA3011.excluded_type_names_with_derived_types = + +# CA3012: Review code for regex injection vulnerabilities +dotnet_diagnostic.CA3012.severity = warning +dotnet_code_quality.CA3012.excluded_symbol_names = +dotnet_code_quality.CA3012.excluded_type_names_with_derived_types = + +# CA3061: Do Not Add Schema By URL +dotnet_diagnostic.CA3061.severity = warning + +# CA3075: Insecure DTD processing in XML +dotnet_diagnostic.CA3075.severity = warning + +# CA3076: Insecure XSLT script processing. +dotnet_diagnostic.CA3076.severity = warning + +# CA3077: Insecure Processing in API Design, XmlDocument and XmlTextReader +dotnet_diagnostic.CA3077.severity = warning + +# CA3147: Mark Verb Handlers With Validate Antiforgery Token +dotnet_diagnostic.CA3147.severity = warning + +# CA5350: Do Not Use Weak Cryptographic Algorithms +dotnet_diagnostic.CA5350.severity = warning + +# CA5351: Do Not Use Broken Cryptographic Algorithms +dotnet_diagnostic.CA5351.severity = warning + +# CA5358: Review cipher mode usage with cryptography experts +dotnet_diagnostic.CA5358.severity = warning + +# CA5359: Do Not Disable Certificate Validation +dotnet_diagnostic.CA5359.severity = warning + +# CA5360: Do Not Call Dangerous Methods In Deserialization +dotnet_diagnostic.CA5360.severity = warning + +# CA5361: Do Not Disable SChannel Use of Strong Crypto +dotnet_diagnostic.CA5361.severity = warning +dotnet_code_quality.CA5361.excluded_symbol_names = +dotnet_code_quality.CA5361.excluded_type_names_with_derived_types = + +# CA5362: Potential reference cycle in deserialized object graph +dotnet_diagnostic.CA5362.severity = warning + +# CA5363: Do Not Disable Request Validation +dotnet_diagnostic.CA5363.severity = warning + +# CA5364: Do Not Use Deprecated Security Protocols +dotnet_diagnostic.CA5364.severity = warning + +# CA5365: Do Not Disable HTTP Header Checking +dotnet_diagnostic.CA5365.severity = warning + +# CA5366: Use XmlReader for 'DataSet.ReadXml()' +dotnet_diagnostic.CA5366.severity = warning + +# CA5367: Do Not Serialize Types With Pointer Fields +dotnet_diagnostic.CA5367.severity = warning + +# CA5368: Set ViewStateUserKey For Classes Derived From Page +dotnet_diagnostic.CA5368.severity = warning + +# CA5369: Use XmlReader for 'XmlSerializer.Deserialize()' +dotnet_diagnostic.CA5369.severity = warning + +# CA5370: Use XmlReader for XmlValidatingReader constructor +dotnet_diagnostic.CA5370.severity = warning + +# CA5371: Use XmlReader for 'XmlSchema.Read()' +dotnet_diagnostic.CA5371.severity = warning + +# CA5372: Use XmlReader for XPathDocument constructor +dotnet_diagnostic.CA5372.severity = warning + +# CA5373: Do not use obsolete key derivation function +dotnet_diagnostic.CA5373.severity = warning + +# CA5374: Do Not Use XslTransform +dotnet_diagnostic.CA5374.severity = warning + +# CA5375: Do Not Use Account Shared Access Signature +dotnet_diagnostic.CA5375.severity = warning + +# CA5376: Use SharedAccessProtocol HttpsOnly +dotnet_diagnostic.CA5376.severity = warning +dotnet_code_quality.CA5376.excluded_symbol_names = +dotnet_code_quality.CA5376.excluded_type_names_with_derived_types = + +# CA5377: Use Container Level Access Policy +dotnet_diagnostic.CA5377.severity = warning +dotnet_code_quality.CA5377.excluded_symbol_names = +dotnet_code_quality.CA5377.excluded_type_names_with_derived_types = + +# CA5378: Do not disable ServicePointManagerSecurityProtocols +dotnet_diagnostic.CA5378.severity = warning +dotnet_code_quality.CA5378.excluded_symbol_names = +dotnet_code_quality.CA5378.excluded_type_names_with_derived_types = + +# CA5379: Ensure Key Derivation Function algorithm is sufficiently strong +dotnet_diagnostic.CA5379.severity = warning + +# CA5380: Do Not Add Certificates To Root Store +dotnet_diagnostic.CA5380.severity = warning +dotnet_code_quality.CA5380.excluded_symbol_names = +dotnet_code_quality.CA5380.excluded_type_names_with_derived_types = + +# CA5381: Ensure Certificates Are Not Added To Root Store +dotnet_diagnostic.CA5381.severity = warning +dotnet_code_quality.CA5381.excluded_symbol_names = +dotnet_code_quality.CA5381.excluded_type_names_with_derived_types = + +# CA5382: Use Secure Cookies In ASP.Net Core +dotnet_diagnostic.CA5382.severity = warning +dotnet_code_quality.CA5382.excluded_symbol_names = +dotnet_code_quality.CA5382.excluded_type_names_with_derived_types = + +# CA5383: Ensure Use Secure Cookies In ASP.Net Core +dotnet_diagnostic.CA5383.severity = warning +dotnet_code_quality.CA5383.excluded_symbol_names = +dotnet_code_quality.CA5383.excluded_type_names_with_derived_types = + +# CA5384: Do Not Use Digital Signature Algorithm (DSA) +dotnet_diagnostic.CA5384.severity = warning +dotnet_code_quality.CA5384.excluded_symbol_names = +dotnet_code_quality.CA5384.excluded_type_names_with_derived_types = + +# CA5385: Use Rivest–Shamir–Adleman (RSA) Algorithm With Sufficient Key Size +dotnet_diagnostic.CA5385.severity = warning + +# CA5386: Avoid hardcoding SecurityProtocolType value +dotnet_diagnostic.CA5386.severity = warning + +# CA5387: Do Not Use Weak Key Derivation Function With Insufficient Iteration Count +dotnet_diagnostic.CA5387.severity = warning +dotnet_code_quality.CA5387.excluded_symbol_names = +dotnet_code_quality.CA5387.excluded_type_names_with_derived_types = + +# CA5388: Ensure Sufficient Iteration Count When Using Weak Key Derivation Function +dotnet_diagnostic.CA5388.severity = warning +dotnet_code_quality.CA5388.excluded_symbol_names = +dotnet_code_quality.CA5388.excluded_type_names_with_derived_types = + +# CA5389: Do Not Add Archive Item's Path To The Target File System Path +dotnet_diagnostic.CA5389.severity = warning +dotnet_code_quality.CA5389.excluded_symbol_names = +dotnet_code_quality.CA5389.excluded_type_names_with_derived_types = + +# CA5390: Do not hard-code encryption key +dotnet_diagnostic.CA5390.severity = warning +dotnet_code_quality.CA5390.excluded_symbol_names = +dotnet_code_quality.CA5390.excluded_type_names_with_derived_types = + +# CA5391: Use antiforgery tokens in ASP.NET Core MVC controllers +dotnet_diagnostic.CA5391.severity = warning +dotnet_code_quality.CA5391.exclude_aspnet_core_mvc_controllerbase = false + +# CA5392: Use DefaultDllImportSearchPaths attribute for P/Invokes +dotnet_diagnostic.CA5392.severity = warning + +# CA5393: Do not use unsafe DllImportSearchPath value +dotnet_diagnostic.CA5393.severity = warning +dotnet_code_quality.CA5393.unsafe_DllImportSearchPath_bits = 770 + +# CA5394: Do not use insecure randomness +dotnet_diagnostic.CA5394.severity = warning + +# CA5395: Miss HttpVerb attribute for action methods +dotnet_diagnostic.CA5395.severity = warning + +# CA5396: Set HttpOnly to true for HttpCookie +dotnet_diagnostic.CA5396.severity = warning + +# CA5397: Do not use deprecated SslProtocols values +dotnet_diagnostic.CA5397.severity = warning + +# CA5398: Avoid hardcoded SslProtocols values +dotnet_diagnostic.CA5398.severity = warning + +# CA5399: HttpClients should enable certificate revocation list checks +dotnet_diagnostic.CA5399.severity = warning +dotnet_code_quality.CA5399.excluded_symbol_names = +dotnet_code_quality.CA5399.excluded_type_names_with_derived_types = + +# CA5400: Ensure HttpClient certificate revocation list check is not disabled +dotnet_diagnostic.CA5400.severity = warning +dotnet_code_quality.CA5400.excluded_symbol_names = +dotnet_code_quality.CA5400.excluded_type_names_with_derived_types = + +# CA5401: Do not use CreateEncryptor with non-default IV +dotnet_diagnostic.CA5401.severity = warning + +# CA5402: Use CreateEncryptor with the default IV +dotnet_diagnostic.CA5402.severity = warning + +# CA5403: Do not hard-code certificate +dotnet_diagnostic.CA5403.severity = warning + +# CA5404: Do not disable token validation checks +dotnet_diagnostic.CA5404.severity = warning + +# CA5405: Do not always skip token validation in delegates +dotnet_diagnostic.CA5405.severity = warning + +# IL3000: Avoid using accessing Assembly file path when publishing as a single-file +dotnet_diagnostic.IL3000.severity = warning + +# IL3001: Avoid using accessing Assembly file path when publishing as a single-file +dotnet_diagnostic.IL3001.severity = warning + +# IL3002: Avoid calling members annotated with 'RequiresAssemblyFilesAttribute' when publishing as a single file +dotnet_diagnostic.IL3002.severity = warning + +## Roslynator.CSharp.Analyzers + +roslynator_accessibility_modifiers = explicit +roslynator_accessor_braces_style = single_line_when_expression_is_on_single_line +roslynator_array_creation_type_style = implicit +roslynator_arrow_token_new_line = after +roslynator_binary_operator_new_line = before +roslynator_blank_line_between_closing_brace_and_switch_section = true +roslynator_blank_line_between_single_line_accessors = false +roslynator_blank_line_between_using_directives = separate_groups +roslynator_block_braces_style = multi_line +roslynator_body_style = expression +roslynator_conditional_operator_condition_parentheses_style = omit_when_condition_is_single_token +roslynator_conditional_operator_new_line = before +roslynator_configure_await = true +roslynator_doc_comment_summary_style = multi_line +roslynator_empty_string_style = field +roslynator_enum_flag_value_style = decimal_number +roslynator_enum_has_flag_style = method +roslynator_equals_token_new_line = after +roslynator_infinite_loop_style = while +roslynator_max_line_length = 256 +roslynator_new_line_at_end_of_file = true +roslynator_new_line_before_while_in_do_statement = false +roslynator_null_conditional_operator_new_line = after +roslynator_null_check_style = pattern_matching +roslynator_object_creation_parentheses_style = include +roslynator_object_creation_type_style = implicit_when_type_is_obvious +roslynator_prefix_field_identifier_with_underscore = false +roslynator_suppress_unity_script_methods = true +roslynator_use_anonymous_function_or_method_group = method_group +roslynator_use_block_body_when_declaration_spans_over_multiple_lines = true +roslynator_use_block_body_when_expression_spans_over_multiple_lines = true +roslynator_use_var_instead_of_implicit_object_creation = true + +roslynator_refactoring.add_all_properties_to_initializer.enabled = true +roslynator_refactoring.add_argument_name.enabled = true +roslynator_refactoring.add_braces.enabled = true +roslynator_refactoring.add_braces_to_if_else.enabled = true +roslynator_refactoring.add_braces_to_switch_section.enabled = true +roslynator_refactoring.add_braces_to_switch_sections.enabled = true +roslynator_refactoring.add_default_value_to_parameter.enabled = true +roslynator_refactoring.add_empty_line_between_declarations.enabled = true +roslynator_refactoring.add_exception_element_to_documentation_comment.enabled = true +roslynator_refactoring.add_generic_parameter_to_declaration.enabled = true +roslynator_refactoring.add_member_to_interface.enabled = true +roslynator_refactoring.add_missing_cases_to_switch.enabled = true +roslynator_refactoring.add_parameter_to_interface_member.enabled = true +roslynator_refactoring.add_tag_to_documentation_comment.enabled = true +roslynator_refactoring.add_using_directive.enabled = true +roslynator_refactoring.add_using_static_directive.enabled = true +roslynator_refactoring.call_extension_method_as_instance_method.enabled = true +roslynator_refactoring.call_indexof_instead_of_contains.enabled = true +roslynator_refactoring.comment_out_member_declaration.enabled = true +roslynator_refactoring.comment_out_statement.enabled = true +roslynator_refactoring.convert_auto_property_to_full_property.enabled = true +roslynator_refactoring.convert_auto_property_to_full_property_without_backing_field.enabled = true +roslynator_refactoring.convert_block_body_to_expression_body.enabled = true +roslynator_refactoring.convert_comment_to_documentation_comment.enabled = true +roslynator_refactoring.convert_conditional_expression_to_if_else.enabled = true +roslynator_refactoring.convert_do_to_while.enabled = true +roslynator_refactoring.convert_expression_body_to_block_body.enabled = true +roslynator_refactoring.convert_for_to_foreach.enabled = true +roslynator_refactoring.convert_for_to_while.enabled = true +roslynator_refactoring.convert_foreach_to_for.enabled = true +roslynator_refactoring.convert_foreach_to_for_and_reverse_loop.enabled = true +roslynator_refactoring.convert_hasflag_call_to_bitwise_operation.enabled = true +roslynator_refactoring.convert_hexadecimal_literal_to_decimal_literal.enabled = true +roslynator_refactoring.convert_if_to_conditional_expression.enabled = true +roslynator_refactoring.convert_if_to_switch.enabled = true +roslynator_refactoring.convert_interpolated_string_to_concatenation.enabled = true +roslynator_refactoring.convert_interpolated_string_to_string_format.enabled = true +roslynator_refactoring.convert_interpolated_string_to_string_literal.enabled = true +roslynator_refactoring.convert_lambda_block_body_to_expression_body.enabled = true +roslynator_refactoring.convert_lambda_expression_body_to_block_body.enabled = true +roslynator_refactoring.convert_method_group_to_lambda.enabled = true +roslynator_refactoring.convert_regular_string_literal_to_verbatim_string_literal.enabled = true +roslynator_refactoring.convert_return_statement_to_if.enabled = true +roslynator_refactoring.convert_statements_to_if_else.enabled = true +roslynator_refactoring.convert_string_format_to_interpolated_string.enabled = true +roslynator_refactoring.convert_switch_expression_to_switch_statement.enabled = true +roslynator_refactoring.convert_switch_to_if.enabled = true +roslynator_refactoring.convert_verbatim_string_literal_to_regular_string_literal.enabled = true +roslynator_refactoring.convert_verbatim_string_literal_to_regular_string_literals.enabled = true +roslynator_refactoring.convert_while_to_do.enabled = true +roslynator_refactoring.convert_while_to_for.enabled = true +roslynator_refactoring.copy_argument.enabled = true +roslynator_refactoring.copy_documentation_comment_from_base_member.enabled = true +roslynator_refactoring.copy_member_declaration.enabled = true +roslynator_refactoring.copy_parameter.enabled = true +roslynator_refactoring.copy_statement.enabled = true +roslynator_refactoring.copy_switch_section.enabled = true +roslynator_refactoring.deconstruct_foreach_variable.enabled = true +roslynator_refactoring.expand_coalesce_expression.enabled = true +roslynator_refactoring.expand_compound_assignment.enabled = true +roslynator_refactoring.expand_event_declaration.enabled = true +roslynator_refactoring.expand_initializer.enabled = true +roslynator_refactoring.expand_positional_constructor.enabled = true +roslynator_refactoring.extract_event_handler_method.enabled = true +roslynator_refactoring.extract_expression_from_condition.enabled = true +roslynator_refactoring.extract_type_declaration_to_new_file.enabled = true +roslynator_refactoring.generate_base_constructors.enabled = true +roslynator_refactoring.generate_combined_enum_member.enabled = true +roslynator_refactoring.generate_enum_member.enabled = true +roslynator_refactoring.generate_enum_values.enabled = true +roslynator_refactoring.generate_event_invoking_method.enabled = true +roslynator_refactoring.generate_property_for_debuggerdisplay_attribute.enabled = true +roslynator_refactoring.change_accessibility.enabled = true +roslynator_refactoring.change_method_return_type_to_void.enabled = true +roslynator_refactoring.change_type_according_to_expression.enabled = true +roslynator_refactoring.check_expression_for_null.enabled = true +roslynator_refactoring.check_parameter_for_null.enabled = true +roslynator_refactoring.implement_custom_enumerator.enabled = true +roslynator_refactoring.implement_iequatable.enabled = true +roslynator_refactoring.initialize_field_from_constructor.enabled = true +roslynator_refactoring.initialize_local_variable_with_default_value.enabled = true +roslynator_refactoring.inline_alias_expression.enabled = true +roslynator_refactoring.inline_constant.enabled = true +roslynator_refactoring.inline_constant_value.enabled = true +roslynator_refactoring.inline_method.enabled = true +roslynator_refactoring.inline_property.enabled = true +roslynator_refactoring.inline_using_static.enabled = true +roslynator_refactoring.insert_string_interpolation.enabled = true +roslynator_refactoring.introduce_and_initialize_field.enabled = true +roslynator_refactoring.introduce_and_initialize_property.enabled = true +roslynator_refactoring.introduce_constructor.enabled = true +roslynator_refactoring.introduce_field_to_lock_on.enabled = true +roslynator_refactoring.introduce_local_variable.enabled = true +roslynator_refactoring.invert_binary_expression.enabled = true +roslynator_refactoring.invert_boolean_literal.enabled = true +roslynator_refactoring.invert_conditional_expression.enabled = true +roslynator_refactoring.invert_if.enabled = true +roslynator_refactoring.invert_if_else.enabled = true +roslynator_refactoring.invert_is_expression.enabled = true +roslynator_refactoring.invert_linq_method_call.enabled = true +roslynator_refactoring.invert_operator.enabled = true +roslynator_refactoring.invert_prefix_or_postfix_unary_expression.enabled = true +roslynator_refactoring.join_string_expressions.enabled = true +roslynator_refactoring.make_member_abstract.enabled = true +roslynator_refactoring.make_member_virtual.enabled = true +roslynator_refactoring.merge_attributes.enabled = true +roslynator_refactoring.merge_if_statements.enabled = true +roslynator_refactoring.merge_if_with_parent_if.enabled = true +roslynator_refactoring.merge_local_declarations.enabled = true +roslynator_refactoring.merge_switch_sections.enabled = true +roslynator_refactoring.move_unsafe_context_to_containing_declaration.enabled = true +roslynator_refactoring.notify_when_property_changes.enabled = true +roslynator_refactoring.parenthesize_expression.enabled = true +roslynator_refactoring.promote_local_variable_to_parameter.enabled = true +roslynator_refactoring.remove_all_comments.enabled = true +roslynator_refactoring.remove_all_comments_except_documentation_comments.enabled = true +roslynator_refactoring.remove_all_documentation_comments.enabled = true +roslynator_refactoring.remove_all_member_declarations.enabled = true +roslynator_refactoring.remove_all_preprocessor_directives.enabled = true +roslynator_refactoring.remove_all_region_directives.enabled = true +roslynator_refactoring.remove_all_statements.enabled = true +roslynator_refactoring.remove_all_switch_sections.enabled = true +roslynator_refactoring.remove_argument_name.enabled = true +roslynator_refactoring.remove_async_await.enabled = true +roslynator_refactoring.remove_braces.enabled = true +roslynator_refactoring.remove_braces_from_if_else.enabled = true +roslynator_refactoring.remove_braces_from_switch_section.enabled = true +roslynator_refactoring.remove_braces_from_switch_sections.enabled = true +roslynator_refactoring.remove_comment.enabled = true +roslynator_refactoring.remove_condition_from_last_else.enabled = true +roslynator_refactoring.remove_containing_statement.enabled = true +roslynator_refactoring.remove_empty_lines.enabled = true +roslynator_refactoring.remove_enum_member_value.enabled = true +roslynator_refactoring.remove_instantiation_of_local_variable.enabled = true +roslynator_refactoring.remove_interpolation.enabled = true +roslynator_refactoring.remove_member_declaration.enabled = true +roslynator_refactoring.remove_member_declarations_above_or_below.enabled = true +roslynator_refactoring.remove_parentheses.enabled = true +roslynator_refactoring.remove_preprocessor_directive.enabled = true +roslynator_refactoring.remove_property_initializer.enabled = true +roslynator_refactoring.remove_region.enabled = true +roslynator_refactoring.remove_statement.enabled = true +roslynator_refactoring.remove_unnecessary_assignment.enabled = true +roslynator_refactoring.rename_identifier_according_to_type_name.enabled = true +roslynator_refactoring.rename_method_according_to_type_name.enabled = true +roslynator_refactoring.rename_parameter_according_to_type_name.enabled = true +roslynator_refactoring.rename_property_according_to_type_name.enabled = true +roslynator_refactoring.replace_as_expression_with_explicit_cast.enabled = true +roslynator_refactoring.replace_conditional_expression_with_true_or_false_branch.enabled = true +roslynator_refactoring.replace_equality_operator_with_string_equals.enabled = true +roslynator_refactoring.replace_equality_operator_with_string_isnullorempty.enabled = true +roslynator_refactoring.replace_equality_operator_with_string_isnullorwhitespace.enabled = true +roslynator_refactoring.replace_explicit_cast_with_as_expression.enabled = true +roslynator_refactoring.replace_interpolated_string_with_interpolation_expression.enabled = true +roslynator_refactoring.replace_method_with_property.enabled = true +roslynator_refactoring.replace_null_literal_with_default_expression.enabled = true +roslynator_refactoring.replace_prefix_operator_with_postfix_operator.enabled = true +roslynator_refactoring.replace_property_with_method.enabled = true +roslynator_refactoring.reverse_for_statement.enabled = true +roslynator_refactoring.simplify_if.enabled = true +roslynator_refactoring.sort_case_labels.enabled = true +roslynator_refactoring.sort_member_declarations.enabled = true +roslynator_refactoring.split_attributes.enabled = true +roslynator_refactoring.split_if.enabled = true +roslynator_refactoring.split_if_else.enabled = true +roslynator_refactoring.split_local_declaration_and_assignment.enabled = true +roslynator_refactoring.split_switch_labels.enabled = true +roslynator_refactoring.split_variable_declaration.enabled = true +roslynator_refactoring.swap_binary_operands.enabled = true +roslynator_refactoring.swap_member_declarations.enabled = true +roslynator_refactoring.sync_property_name_and_backing_field_name.enabled = true +roslynator_refactoring.uncomment_multiline_comment.enabled = true +roslynator_refactoring.uncomment_singleline_comment.enabled = true +roslynator_refactoring.use_coalesce_expression_instead_of_if.enabled = true +roslynator_refactoring.use_constant_instead_of_readonly_field.enabled = true +roslynator_refactoring.use_element_access_instead_of_linq_method.enabled = true +roslynator_refactoring.use_enumerator_explicitly.enabled = true +roslynator_refactoring.use_explicit_type.enabled = true +roslynator_refactoring.use_implicit_type.enabled = true +roslynator_refactoring.use_index_initializer.enabled = true +roslynator_refactoring.use_lambda_instead_of_anonymous_method.enabled = true +roslynator_refactoring.use_list_instead_of_yield.enabled = true +roslynator_refactoring.use_object_initializer.enabled = true +roslynator_refactoring.use_readonly_field_instead_of_constant.enabled = true +roslynator_refactoring.use_string_empty_instead_of_empty_string_literal.enabled = true +roslynator_refactoring.use_stringbuilder_instead_of_concatenation.enabled = true +roslynator_refactoring.wrap_arguments.enabled = true +roslynator_refactoring.wrap_binary_expression.enabled = true +roslynator_refactoring.wrap_call_chain.enabled = true +roslynator_refactoring.wrap_conditional_expression.enabled = true +roslynator_refactoring.wrap_constraint_clauses.enabled = true +roslynator_refactoring.wrap_initializer_expressions.enabled = true +roslynator_refactoring.wrap_lines_in_preprocessor_directive.enabled = true +roslynator_refactoring.wrap_lines_in_region.enabled = true +roslynator_refactoring.wrap_lines_in_try_catch.enabled = true +roslynator_refactoring.wrap_parameters.enabled = true +roslynator_refactoring.wrap_statements_in_condition.enabled = true +roslynator_refactoring.wrap_statements_in_using_statement.enabled = true + +roslynator_compiler_diagnostic_fix.cs0019.enabled = true +roslynator_compiler_diagnostic_fix.cs0021.enabled = true +roslynator_compiler_diagnostic_fix.cs0023.enabled = true +roslynator_compiler_diagnostic_fix.cs0029.enabled = true +roslynator_compiler_diagnostic_fix.cs0030.enabled = true +roslynator_compiler_diagnostic_fix.cs0037.enabled = true +roslynator_compiler_diagnostic_fix.cs0069.enabled = true +roslynator_compiler_diagnostic_fix.cs0077.enabled = true +roslynator_compiler_diagnostic_fix.cs0080.enabled = true +roslynator_compiler_diagnostic_fix.cs0101.enabled = true +roslynator_compiler_diagnostic_fix.cs0102.enabled = true +roslynator_compiler_diagnostic_fix.cs0103.enabled = true +roslynator_compiler_diagnostic_fix.cs0106.enabled = true +roslynator_compiler_diagnostic_fix.cs0107.enabled = true +roslynator_compiler_diagnostic_fix.cs0108.enabled = true +roslynator_compiler_diagnostic_fix.cs0109.enabled = true +roslynator_compiler_diagnostic_fix.cs0112.enabled = true +roslynator_compiler_diagnostic_fix.cs0114.enabled = true +roslynator_compiler_diagnostic_fix.cs0115.enabled = true +roslynator_compiler_diagnostic_fix.cs0119.enabled = true +roslynator_compiler_diagnostic_fix.cs0120.enabled = true +roslynator_compiler_diagnostic_fix.cs0123.enabled = true +roslynator_compiler_diagnostic_fix.cs0126.enabled = true +roslynator_compiler_diagnostic_fix.cs0127.enabled = true +roslynator_compiler_diagnostic_fix.cs0128.enabled = true +roslynator_compiler_diagnostic_fix.cs0131.enabled = true +roslynator_compiler_diagnostic_fix.cs0132.enabled = true +roslynator_compiler_diagnostic_fix.cs0133.enabled = true +roslynator_compiler_diagnostic_fix.cs0136.enabled = true +roslynator_compiler_diagnostic_fix.cs0139.enabled = true +roslynator_compiler_diagnostic_fix.cs0152.enabled = true +roslynator_compiler_diagnostic_fix.cs0161.enabled = true +roslynator_compiler_diagnostic_fix.cs0162.enabled = true +roslynator_compiler_diagnostic_fix.cs0163.enabled = true +roslynator_compiler_diagnostic_fix.cs0164.enabled = true +roslynator_compiler_diagnostic_fix.cs0165.enabled = true +roslynator_compiler_diagnostic_fix.cs0168.enabled = true +roslynator_compiler_diagnostic_fix.cs0173.enabled = true +roslynator_compiler_diagnostic_fix.cs0177.enabled = true +roslynator_compiler_diagnostic_fix.cs0191.enabled = true +roslynator_compiler_diagnostic_fix.cs0192.enabled = true +roslynator_compiler_diagnostic_fix.cs0201.enabled = true +roslynator_compiler_diagnostic_fix.cs0214.enabled = true +roslynator_compiler_diagnostic_fix.cs0216.enabled = true +roslynator_compiler_diagnostic_fix.cs0219.enabled = true +roslynator_compiler_diagnostic_fix.cs0221.enabled = true +roslynator_compiler_diagnostic_fix.cs0225.enabled = true +roslynator_compiler_diagnostic_fix.cs0238.enabled = true +roslynator_compiler_diagnostic_fix.cs0246.enabled = true +roslynator_compiler_diagnostic_fix.cs0260.enabled = true +roslynator_compiler_diagnostic_fix.cs0262.enabled = true +roslynator_compiler_diagnostic_fix.cs0266.enabled = true +roslynator_compiler_diagnostic_fix.cs0267.enabled = true +roslynator_compiler_diagnostic_fix.cs0272.enabled = true +roslynator_compiler_diagnostic_fix.cs0275.enabled = true +roslynator_compiler_diagnostic_fix.cs0305.enabled = true +roslynator_compiler_diagnostic_fix.cs0401.enabled = true +roslynator_compiler_diagnostic_fix.cs0403.enabled = true +roslynator_compiler_diagnostic_fix.cs0405.enabled = true +roslynator_compiler_diagnostic_fix.cs0407.enabled = true +roslynator_compiler_diagnostic_fix.cs0409.enabled = true +roslynator_compiler_diagnostic_fix.cs0428.enabled = true +roslynator_compiler_diagnostic_fix.cs0441.enabled = true +roslynator_compiler_diagnostic_fix.cs0442.enabled = true +roslynator_compiler_diagnostic_fix.cs0449.enabled = true +roslynator_compiler_diagnostic_fix.cs0450.enabled = true +roslynator_compiler_diagnostic_fix.cs0451.enabled = true +roslynator_compiler_diagnostic_fix.cs0472.enabled = true +roslynator_compiler_diagnostic_fix.cs0500.enabled = true +roslynator_compiler_diagnostic_fix.cs0501.enabled = true +roslynator_compiler_diagnostic_fix.cs0507.enabled = true +roslynator_compiler_diagnostic_fix.cs0508.enabled = true +roslynator_compiler_diagnostic_fix.cs0513.enabled = true +roslynator_compiler_diagnostic_fix.cs0515.enabled = true +roslynator_compiler_diagnostic_fix.cs0524.enabled = true +roslynator_compiler_diagnostic_fix.cs0525.enabled = true +roslynator_compiler_diagnostic_fix.cs0527.enabled = true +roslynator_compiler_diagnostic_fix.cs0531.enabled = true +roslynator_compiler_diagnostic_fix.cs0539.enabled = true +roslynator_compiler_diagnostic_fix.cs0541.enabled = true +roslynator_compiler_diagnostic_fix.cs0549.enabled = true +roslynator_compiler_diagnostic_fix.cs0558.enabled = true +roslynator_compiler_diagnostic_fix.cs0567.enabled = true +roslynator_compiler_diagnostic_fix.cs0568.enabled = true +roslynator_compiler_diagnostic_fix.cs0573.enabled = true +roslynator_compiler_diagnostic_fix.cs0574.enabled = true +roslynator_compiler_diagnostic_fix.cs0575.enabled = true +roslynator_compiler_diagnostic_fix.cs0579.enabled = true +roslynator_compiler_diagnostic_fix.cs0592.enabled = true +roslynator_compiler_diagnostic_fix.cs0621.enabled = true +roslynator_compiler_diagnostic_fix.cs0628.enabled = true +roslynator_compiler_diagnostic_fix.cs0659.enabled = true +roslynator_compiler_diagnostic_fix.cs0660.enabled = true +roslynator_compiler_diagnostic_fix.cs0661.enabled = true +roslynator_compiler_diagnostic_fix.cs0678.enabled = true +roslynator_compiler_diagnostic_fix.cs0693.enabled = true +roslynator_compiler_diagnostic_fix.cs0708.enabled = true +roslynator_compiler_diagnostic_fix.cs0710.enabled = true +roslynator_compiler_diagnostic_fix.cs0713.enabled = true +roslynator_compiler_diagnostic_fix.cs0714.enabled = true +roslynator_compiler_diagnostic_fix.cs0718.enabled = true +roslynator_compiler_diagnostic_fix.cs0750.enabled = true +roslynator_compiler_diagnostic_fix.cs0751.enabled = true +roslynator_compiler_diagnostic_fix.cs0753.enabled = true +roslynator_compiler_diagnostic_fix.cs0756.enabled = true +roslynator_compiler_diagnostic_fix.cs0759.enabled = true +roslynator_compiler_diagnostic_fix.cs0766.enabled = true +roslynator_compiler_diagnostic_fix.cs0815.enabled = true +roslynator_compiler_diagnostic_fix.cs0819.enabled = true +roslynator_compiler_diagnostic_fix.cs0822.enabled = true +roslynator_compiler_diagnostic_fix.cs1002.enabled = true +roslynator_compiler_diagnostic_fix.cs1003.enabled = true +roslynator_compiler_diagnostic_fix.cs1004.enabled = true +roslynator_compiler_diagnostic_fix.cs1012.enabled = true +roslynator_compiler_diagnostic_fix.cs1023.enabled = true +roslynator_compiler_diagnostic_fix.cs1031.enabled = true +roslynator_compiler_diagnostic_fix.cs1057.enabled = true +roslynator_compiler_diagnostic_fix.cs1061.enabled = true +roslynator_compiler_diagnostic_fix.cs1100.enabled = true +roslynator_compiler_diagnostic_fix.cs1105.enabled = true +roslynator_compiler_diagnostic_fix.cs1106.enabled = true +roslynator_compiler_diagnostic_fix.cs1503.enabled = true +roslynator_compiler_diagnostic_fix.cs1522.enabled = true +roslynator_compiler_diagnostic_fix.cs1526.enabled = true +roslynator_compiler_diagnostic_fix.cs1527.enabled = true +roslynator_compiler_diagnostic_fix.cs1591.enabled = true +roslynator_compiler_diagnostic_fix.cs1597.enabled = true +roslynator_compiler_diagnostic_fix.cs1609.enabled = true +roslynator_compiler_diagnostic_fix.cs1615.enabled = true +roslynator_compiler_diagnostic_fix.cs1620.enabled = true +roslynator_compiler_diagnostic_fix.cs1621.enabled = true +roslynator_compiler_diagnostic_fix.cs1622.enabled = true +roslynator_compiler_diagnostic_fix.cs1623.enabled = true +roslynator_compiler_diagnostic_fix.cs1624.enabled = true +roslynator_compiler_diagnostic_fix.cs1643.enabled = true +roslynator_compiler_diagnostic_fix.cs1674.enabled = true +roslynator_compiler_diagnostic_fix.cs1689.enabled = true +roslynator_compiler_diagnostic_fix.cs1715.enabled = true +roslynator_compiler_diagnostic_fix.cs1717.enabled = true +roslynator_compiler_diagnostic_fix.cs1722.enabled = true +roslynator_compiler_diagnostic_fix.cs1737.enabled = true +roslynator_compiler_diagnostic_fix.cs1741.enabled = true +roslynator_compiler_diagnostic_fix.cs1743.enabled = true +roslynator_compiler_diagnostic_fix.cs1750.enabled = true +roslynator_compiler_diagnostic_fix.cs1751.enabled = true +roslynator_compiler_diagnostic_fix.cs1955.enabled = true +roslynator_compiler_diagnostic_fix.cs1983.enabled = true +roslynator_compiler_diagnostic_fix.cs1988.enabled = true +roslynator_compiler_diagnostic_fix.cs1994.enabled = true +roslynator_compiler_diagnostic_fix.cs1997.enabled = true +roslynator_compiler_diagnostic_fix.cs3000.enabled = true +roslynator_compiler_diagnostic_fix.cs3001.enabled = true +roslynator_compiler_diagnostic_fix.cs3002.enabled = true +roslynator_compiler_diagnostic_fix.cs3003.enabled = true +roslynator_compiler_diagnostic_fix.cs3005.enabled = true +roslynator_compiler_diagnostic_fix.cs3006.enabled = true +roslynator_compiler_diagnostic_fix.cs3007.enabled = true +roslynator_compiler_diagnostic_fix.cs3008.enabled = true +roslynator_compiler_diagnostic_fix.cs3009.enabled = true +roslynator_compiler_diagnostic_fix.cs3016.enabled = true +roslynator_compiler_diagnostic_fix.cs3024.enabled = true +roslynator_compiler_diagnostic_fix.cs3027.enabled = true +roslynator_compiler_diagnostic_fix.cs7036.enabled = true +roslynator_compiler_diagnostic_fix.cs8050.enabled = true +roslynator_compiler_diagnostic_fix.cs8070.enabled = true +roslynator_compiler_diagnostic_fix.cs8112.enabled = true +roslynator_compiler_diagnostic_fix.cs8139.enabled = true +roslynator_compiler_diagnostic_fix.cs8340.enabled = true +roslynator_compiler_diagnostic_fix.cs8403.enabled = true +roslynator_compiler_diagnostic_fix.cs8602.enabled = true +roslynator_compiler_diagnostic_fix.cs8604.enabled = true +roslynator_compiler_diagnostic_fix.cs8618.enabled = true +roslynator_compiler_diagnostic_fix.cs8625.enabled = true +roslynator_compiler_diagnostic_fix.cs8632.enabled = true + +# RCS0001: Add empty line after embedded statement. +dotnet_diagnostic.RCS0001.severity = warning + +# RCS0002: Add empty line after #region. +dotnet_diagnostic.RCS0002.severity = warning + +# RCS0003: Add empty line after using directive list. +dotnet_diagnostic.RCS0003.severity = warning + +# RCS0004: Add empty line before closing brace of 'do' statement. +dotnet_diagnostic.RCS0004.severity = none + +# RCS0005: Add empty line before #endregion. +dotnet_diagnostic.RCS0005.severity = warning + +# RCS0006: Add empty line before using directive list. +dotnet_diagnostic.RCS0006.severity = warning + +# RCS0007: Add empty line between accessors. +dotnet_diagnostic.RCS0007.severity = warning + +# RCS0008: Add empty line between block and statement. +dotnet_diagnostic.RCS0008.severity = warning + +# RCS0009: Add empty line between declaration and documentation comment. +dotnet_diagnostic.RCS0009.severity = warning + +# RCS0010: Add empty line between declarations. +dotnet_diagnostic.RCS0010.severity = warning + +# RCS0011: Add empty line between single-line accessors (or vice versa). +dotnet_diagnostic.RCS0011.severity = warning + +# RCS0012: Add empty line between single-line declarations. +dotnet_diagnostic.RCS0012.severity = warning + +# RCS0013: Add empty line between single-line declarations of different kind. +dotnet_diagnostic.RCS0013.severity = warning + +# RCS0014: Add empty line between switch sections. +dotnet_diagnostic.RCS0014.severity = warning + +# RCS0015: Add empty line between using directives with different root namespace (or vice versa). +dotnet_diagnostic.RCS0015.severity = warning + +# RCS0016: Add newline after attribute list. +dotnet_diagnostic.RCS0016.severity = warning + +# RCS0020: Add newline after opening brace of accessor. +dotnet_diagnostic.RCS0020.severity = warning + +# RCS0021: Add newline after opening brace of block. +dotnet_diagnostic.RCS0021.severity = warning + +# RCS0022: Add newline after opening brace of empty block. +dotnet_diagnostic.RCS0022.severity = warning + +# RCS0023: Add newline after opening brace of type declaration. +dotnet_diagnostic.RCS0023.severity = warning + +# RCS0024: Add newline after switch label. +dotnet_diagnostic.RCS0024.severity = warning + +# RCS0025: Add newline before accessor of full property. +dotnet_diagnostic.RCS0025.severity = warning + +# RCS0027: Add newline before binary operator instead of after it (or vice versa). +dotnet_diagnostic.RCS0027.severity = warning + +# RCS0028: Add newline before conditional operator instead of after it (or vice versa). +dotnet_diagnostic.RCS0028.severity = warning + +# RCS0029: Add newline before constructor initializer. +dotnet_diagnostic.RCS0029.severity = none + +# RCS0030: Add newline before embedded statement. +dotnet_diagnostic.RCS0030.severity = warning + +# RCS0031: Add newline before enum member. +dotnet_diagnostic.RCS0031.severity = warning + +# RCS0032: Add newline before expression-body arrow instead of after it (or vice versa). +dotnet_diagnostic.RCS0032.severity = warning + +# RCS0033: Add newline before statement. +dotnet_diagnostic.RCS0033.severity = warning + +# RCS0034: Add newline before type parameter constraint. +dotnet_diagnostic.RCS0034.severity = warning + +# RCS0036: Remove empty line between single-line declarations of same kind. +dotnet_diagnostic.RCS0036.severity = none + +# RCS0038: Remove empty line between using directives with same root namespace. +dotnet_diagnostic.RCS0038.severity = warning + +# RCS0039: Remove newline before base list. +dotnet_diagnostic.RCS0039.severity = warning + +# RCS0041: Remove newline between 'if' keyword and 'else' keyword. +dotnet_diagnostic.RCS0041.severity = warning + +# RCS0042: Remove newlines from accessor list of auto-property. +dotnet_diagnostic.RCS0042.severity = warning + +# RCS0043: Remove newlines from accessor with single-line expression. +dotnet_diagnostic.RCS0043.severity = none + +# RCS0044: Use carriage return + linefeed as newline. +dotnet_diagnostic.RCS0044.severity = warning + +# RCS0045: Use linefeed as newline. +dotnet_diagnostic.RCS0045.severity = none + +# RCS0046: Use spaces instead of tab. +dotnet_diagnostic.RCS0046.severity = none + +# RCS0047: [deprecated] Wrap and indent each node in list +dotnet_diagnostic.RCS0047.severity = none + +# RCS0048: Remove newlines from initializer with single-line expression. +dotnet_diagnostic.RCS0048.severity = none + +# RCS0049: Add empty line after top comment. +dotnet_diagnostic.RCS0049.severity = warning + +# RCS0050: Add empty line before top declaration. +dotnet_diagnostic.RCS0050.severity = warning + +# RCS0051: Add newline between closing brace and 'while' keyword (or vice versa). +dotnet_diagnostic.RCS0051.severity = warning + +# RCS0052: Add newline before equals sign instead of after it (or vice versa). +dotnet_diagnostic.RCS0052.severity = warning + +# RCS0053: Fix formatting of a list. +dotnet_diagnostic.RCS0053.severity = warning + +# RCS0054: Fix formatting of a call chain. +dotnet_diagnostic.RCS0054.severity = warning + +# RCS0055: Fix formatting of a binary expression chain. +dotnet_diagnostic.RCS0055.severity = warning + +# RCS0056: A line is too long. +dotnet_diagnostic.RCS0056.severity = suggestion + +# RCS0057: Normalize whitespace at the beginning of a file. +dotnet_diagnostic.RCS0057.severity = warning + +# RCS0058: Normalize whitespace at the end of a file. +dotnet_diagnostic.RCS0058.severity = warning + +# RCS0059: Place new line after/before null-conditional operator. +dotnet_diagnostic.RCS0059.severity = warning + +# RCS1001: Add braces (when expression spans over multiple lines). +dotnet_diagnostic.RCS1001.severity = warning + +# RCS1002: Remove braces. +dotnet_diagnostic.RCS1002.severity = none + +# RCS1002FadeOut: Remove braces. (NotConfigurable) +#dotnet_diagnostic.RCS1002FadeOut.severity = silent + +# RCS1003: Add braces to if-else (when expression spans over multiple lines). +dotnet_diagnostic.RCS1003.severity = warning + +# RCS1004: Remove braces from if-else. +dotnet_diagnostic.RCS1004.severity = none + +# RCS1004FadeOut: Remove braces from if-else. (NotConfigurable) +#dotnet_diagnostic.RCS1004FadeOut.severity = silent + +# RCS1005: Simplify nested using statement. +dotnet_diagnostic.RCS1005.severity = warning + +# RCS1005FadeOut: Simplify nested using statement. (NotConfigurable) +#dotnet_diagnostic.RCS1005FadeOut.severity = silent + +# RCS1006: Merge 'else' with nested 'if'. +dotnet_diagnostic.RCS1006.severity = warning + +# RCS1006FadeOut: Merge 'else' with nested 'if'. (NotConfigurable) +#dotnet_diagnostic.RCS1006FadeOut.severity = silent + +# RCS1007: Add braces. +dotnet_diagnostic.RCS1007.severity = warning + +# RCS1008: Use explicit type instead of 'var' (when the type is not obvious). +dotnet_diagnostic.RCS1008.severity = none + +# RCS1009: Use explicit type instead of 'var' (foreach variable). +dotnet_diagnostic.RCS1009.severity = none + +# RCS1010: Use 'var' instead of explicit type (when the type is obvious). +dotnet_diagnostic.RCS1010.severity = warning + +# RCS1012: Use explicit type instead of 'var' (when the type is obvious). +dotnet_diagnostic.RCS1012.severity = none + +# RCS1013: Use predefined type. +dotnet_diagnostic.RCS1013.severity = warning + +# RCS1014: Use explicitly typed array (or vice versa). +dotnet_diagnostic.RCS1014.severity = warning + +# RCS1015: Use nameof operator. +dotnet_diagnostic.RCS1015.severity = warning + +# RCS1015FadeOut: Use nameof operator. (NotConfigurable) +#dotnet_diagnostic.RCS1015FadeOut.severity = silent + +# RCS1016: Use expression-bodied member. +dotnet_diagnostic.RCS1016.severity = suggestion + +# RCS1016FadeOut: Convert block body to expression-body (or vice versa). (NotConfigurable) +#dotnet_diagnostic.RCS1016FadeOut.severity = silent + +# RCS1018: Add accessibility modifiers. +dotnet_diagnostic.RCS1018.severity = warning + +# RCS1019: Order modifiers. +dotnet_diagnostic.RCS1019.severity = warning + +# RCS1020: Simplify Nullable to T?. +dotnet_diagnostic.RCS1020.severity = warning + +# RCS1021: Convert lambda expression body to expression-body. +dotnet_diagnostic.RCS1021.severity = warning + +# RCS1021FadeOut: Convert lambda expression body to expression-body. (NotConfigurable) +#dotnet_diagnostic.RCS1021FadeOut.severity = silent + +# RCS1031: Remove unnecessary braces. +dotnet_diagnostic.RCS1031.severity = none + +# RCS1031FadeOut: Remove unnecessary braces. (NotConfigurable) +#dotnet_diagnostic.RCS1031FadeOut.severity = silent + +# RCS1032: Remove redundant parentheses. +dotnet_diagnostic.RCS1032.severity = warning + +# RCS1032FadeOut: Remove redundant parentheses. (NotConfigurable) +#dotnet_diagnostic.RCS1032FadeOut.severity = silent + +# RCS1033: Remove redundant boolean literal. +dotnet_diagnostic.RCS1033.severity = warning + +# RCS1034: Remove redundant 'sealed' modifier. +dotnet_diagnostic.RCS1034.severity = warning + +# RCS1035: Remove redundant comma in initializer. +dotnet_diagnostic.RCS1035.severity = warning + +# RCS1036: Remove redundant empty line. +dotnet_diagnostic.RCS1036.severity = warning + +# RCS1037: Remove trailing white-space. +dotnet_diagnostic.RCS1037.severity = warning + +# RCS1038: Remove empty statement. +dotnet_diagnostic.RCS1038.severity = warning + +# RCS1039: Remove argument list from attribute. +dotnet_diagnostic.RCS1039.severity = warning + +# RCS1040: Remove empty 'else' clause. +dotnet_diagnostic.RCS1040.severity = warning + +# RCS1041: Remove empty initializer. +dotnet_diagnostic.RCS1041.severity = warning + +# RCS1042: Remove enum default underlying type. +dotnet_diagnostic.RCS1042.severity = warning + +# RCS1043: Remove 'partial' modifier from type with a single part. +dotnet_diagnostic.RCS1043.severity = warning + +# RCS1044: Remove original exception from throw statement. +dotnet_diagnostic.RCS1044.severity = warning + +# RCS1046: Asynchronous method name should end with 'Async'. +dotnet_diagnostic.RCS1046.severity = warning + +# RCS1047: Non-asynchronous method name should not end with 'Async'. +dotnet_diagnostic.RCS1047.severity = warning + +# RCS1047FadeOut: Non-asynchronous method name should not end with 'Async'. (NotConfigurable) +#dotnet_diagnostic.RCS1047FadeOut.severity = silent + +# RCS1048: Use lambda expression instead of anonymous method. +dotnet_diagnostic.RCS1048.severity = warning + +# RCS1048FadeOut: Use lambda expression instead of anonymous method. (NotConfigurable) +#dotnet_diagnostic.RCS1048FadeOut.severity = silent + +# RCS1049: Simplify boolean comparison. +dotnet_diagnostic.RCS1049.severity = warning + +# RCS1049FadeOut: Simplify boolean comparison. (NotConfigurable) +#dotnet_diagnostic.RCS1049FadeOut.severity = silent + +# RCS1050: Add argument list to object creation expression (or vice versa). +dotnet_diagnostic.RCS1050.severity = warning + +# RCS1051: Parenthesize condition of conditional expression. +dotnet_diagnostic.RCS1051.severity = warning + +# RCS1052: Declare each attribute separately. +dotnet_diagnostic.RCS1052.severity = warning + +# RCS1055: Avoid semicolon at the end of declaration. +dotnet_diagnostic.RCS1055.severity = warning + +# RCS1056: Avoid usage of using alias directive. +dotnet_diagnostic.RCS1056.severity = warning + +# RCS1058: Use compound assignment. +dotnet_diagnostic.RCS1058.severity = warning + +# RCS1058FadeOut: Use compound assignment. (NotConfigurable) +#dotnet_diagnostic.RCS1058FadeOut.severity = silent + +# RCS1059: Avoid locking on publicly accessible instance. +dotnet_diagnostic.RCS1059.severity = warning + +# RCS1060: Declare each type in separate file. +dotnet_diagnostic.RCS1060.severity = warning + +# RCS1061: Merge 'if' with nested 'if'. +dotnet_diagnostic.RCS1061.severity = warning + +# RCS1061FadeOut: Merge 'if' with nested 'if'. (NotConfigurable) +#dotnet_diagnostic.RCS1061FadeOut.severity = silent + +# RCS1063: Avoid usage of do statement to create an infinite loop. +dotnet_diagnostic.RCS1063.severity = warning + +# RCS1064: Avoid usage of for statement to create an infinite loop. +dotnet_diagnostic.RCS1064.severity = warning + +# RCS1065: Avoid usage of while statement to create an inifinite loop. +dotnet_diagnostic.RCS1065.severity = none + +# RCS1066: Remove empty 'finally' clause. +dotnet_diagnostic.RCS1066.severity = warning + +# RCS1066FadeOut: Remove empty 'finally' clause. (NotConfigurable) +#dotnet_diagnostic.RCS1066FadeOut.severity = silent + +# RCS1068: Simplify logical negation. +dotnet_diagnostic.RCS1068.severity = warning + +# RCS1069: Remove unnecessary case label. +dotnet_diagnostic.RCS1069.severity = warning + +# RCS1070: Remove redundant default switch section. +dotnet_diagnostic.RCS1070.severity = warning + +# RCS1071: Remove redundant base constructor call. +dotnet_diagnostic.RCS1071.severity = warning + +# RCS1072: Remove empty namespace declaration. +dotnet_diagnostic.RCS1072.severity = warning + +# RCS1073: Convert 'if' to 'return' statement. +dotnet_diagnostic.RCS1073.severity = warning + +# RCS1073FadeOut: Convert 'if' to 'return' statement. (NotConfigurable) +#dotnet_diagnostic.RCS1073FadeOut.severity = silent + +# RCS1074: Remove redundant constructor. +dotnet_diagnostic.RCS1074.severity = warning + +# RCS1075: Avoid empty catch clause that catches System.Exception. +dotnet_diagnostic.RCS1075.severity = warning + +# RCS1077: Optimize LINQ method call. +dotnet_diagnostic.RCS1077.severity = warning + +# RCS1078: Use "" instead of string.Empty. +dotnet_diagnostic.RCS1078.severity = warning + +# RCS1079: Throwing of new NotImplementedException. +dotnet_diagnostic.RCS1079.severity = warning + +# RCS1080: Use 'Count/Length' property instead of 'Any' method. +dotnet_diagnostic.RCS1080.severity = warning + +# RCS1081: Split variable declaration. +dotnet_diagnostic.RCS1081.severity = warning + +# RCS1084: Use coalesce expression instead of conditional expression. +dotnet_diagnostic.RCS1084.severity = warning + +# RCS1085: Use auto-implemented property. +dotnet_diagnostic.RCS1085.severity = warning + +# RCS1085FadeOut: Use auto-implemented property. (NotConfigurable) +#dotnet_diagnostic.RCS1085FadeOut.severity = silent + +# RCS1089: Use --/++ operator instead of assignment. +dotnet_diagnostic.RCS1089.severity = warning + +# RCS1089: Use --/++ operator instead of assignment. (NotConfigurable) +#dotnet_diagnostic.RCS1089FadeOut.severity = silent + +# RCS1090: Call 'ConfigureAwait(false)'. +dotnet_diagnostic.RCS1090.severity = warning + +# RCS1091: Remove empty region. +dotnet_diagnostic.RCS1091.severity = warning + +# RCS1091FadeOut: Remove empty region. (NotConfigurable) +#dotnet_diagnostic.RCS1091FadeOut.severity = silent + +# RCS1093: Remove file with no code. +dotnet_diagnostic.RCS1093.severity = warning + +# RCS1094: Declare using directive on top level. +dotnet_diagnostic.RCS1094.severity = warning + +# RCS1096: Convert 'HasFlag' call to bitwise operation (or vice versa). +dotnet_diagnostic.RCS1096.severity = warning + +# RCS1097: Remove redundant 'ToString' call. +dotnet_diagnostic.RCS1097.severity = warning + +# RCS1098: Constant values should be placed on right side of comparisons. +dotnet_diagnostic.RCS1098.severity = warning + +# RCS1099: Default label should be the last label in a switch section. +dotnet_diagnostic.RCS1099.severity = warning + +# RCS1100: [deprecated] Format documentation summary on a single line. +dotnet_diagnostic.RCS1100.severity = none + +# RCS1101: [deprecated] Format documentation summary on multiple lines. +dotnet_diagnostic.RCS1101.severity = none + +# RCS1102: Make class static. +dotnet_diagnostic.RCS1102.severity = warning + +# RCS1103: Convert 'if' to assignment. +dotnet_diagnostic.RCS1103.severity = warning + +# RCS1104: Simplify conditional expression. +dotnet_diagnostic.RCS1104.severity = warning + +# RCS1105: Unncessary interpolation. +dotnet_diagnostic.RCS1105.severity = warning + +# RCS1106: Remove empty destructor. +dotnet_diagnostic.RCS1106.severity = warning + +# RCS1107: Remove redundant 'ToCharArray' call. +dotnet_diagnostic.RCS1107.severity = warning + +# RCS1108: Add 'static' modifier to all partial class declarations. +dotnet_diagnostic.RCS1108.severity = warning + +# RCS1110: Declare type inside namespace. +dotnet_diagnostic.RCS1110.severity = warning + +# RCS1111: Add braces to switch section with multiple statements. +dotnet_diagnostic.RCS1111.severity = warning + +# RCS1112: Combine 'Enumerable.Where' method chain. +dotnet_diagnostic.RCS1112.severity = warning + +# RCS1112FadeOut: Combine 'Enumerable.Where' method chain. (NotConfigurable) +#dotnet_diagnostic.RCS1112FadeOut.severity = silent + +# RCS1113: Use 'string.IsNullOrEmpty' method. +dotnet_diagnostic.RCS1113.severity = warning + +# RCS1114: Remove redundant delegate creation. +dotnet_diagnostic.RCS1114.severity = warning + +# RCS1114FadeOut: Remove redundant delegate creation. (NotConfigurable) +#dotnet_diagnostic.RCS1114FadeOut.severity = silent + +# RCS1118: Mark local variable as const. +dotnet_diagnostic.RCS1118.severity = warning + +# RCS1123: Add parentheses when necessary. +dotnet_diagnostic.RCS1123.severity = warning + +# RCS1124: Inline local variable. +dotnet_diagnostic.RCS1124.severity = suggestion + +# RCS1124FadeOut: Inline local variable. (NotConfigurable) +#dotnet_diagnostic.RCS1124FadeOut.severity = silent + +# RCS1126: Add braces to if-else. +dotnet_diagnostic.RCS1126.severity = warning + +# RCS1128: Use coalesce expression. +dotnet_diagnostic.RCS1128.severity = warning + +# RCS1129: Remove redundant field initalization. +dotnet_diagnostic.RCS1129.severity = warning + +# RCS1130: Bitwise operation on enum without Flags attribute. +dotnet_diagnostic.RCS1130.severity = warning + +# RCS1132: Remove redundant overriding member. +dotnet_diagnostic.RCS1132.severity = warning + +# RCS1133: Remove redundant Dispose/Close call. +dotnet_diagnostic.RCS1133.severity = warning + +# RCS1134: Remove redundant statement. +dotnet_diagnostic.RCS1134.severity = warning + +# RCS1135: Declare enum member with zero value (when enum has FlagsAttribute). +dotnet_diagnostic.RCS1135.severity = warning + +# RCS1136: Merge switch sections with equivalent content. +dotnet_diagnostic.RCS1136.severity = warning + +# RCS1138: Add summary to documentation comment. +dotnet_diagnostic.RCS1138.severity = warning + +# RCS1139: Add summary element to documentation comment. +dotnet_diagnostic.RCS1139.severity = warning + +# RCS1140: Add exception to documentation comment. +dotnet_diagnostic.RCS1140.severity = warning + +# RCS1141: Add 'param' element to documentation comment. +dotnet_diagnostic.RCS1141.severity = warning + +# RCS1142: Add 'typeparam' element to documentation comment. +dotnet_diagnostic.RCS1142.severity = warning + +# RCS1143: Simplify coalesce expression. +dotnet_diagnostic.RCS1143.severity = warning + +# RCS1145: Remove redundant 'as' operator. +dotnet_diagnostic.RCS1145.severity = warning + +# RCS1146: Use conditional access. +dotnet_diagnostic.RCS1146.severity = warning + +# RCS1151: Remove redundant cast. +dotnet_diagnostic.RCS1151.severity = warning + +# RCS1154: Sort enum members. +dotnet_diagnostic.RCS1154.severity = warning + +# RCS1155: Use StringComparison when comparing strings. +dotnet_diagnostic.RCS1155.severity = warning + +# RCS1156: Use string.Length instead of comparison with empty string. +dotnet_diagnostic.RCS1156.severity = warning + +# RCS1157: Composite enum value contains undefined flag. +dotnet_diagnostic.RCS1157.severity = warning + +# RCS1158: Static member in generic type should use a type parameter. +dotnet_diagnostic.RCS1158.severity = warning + +# RCS1159: Use EventHandler. +dotnet_diagnostic.RCS1159.severity = warning + +# RCS1160: Abstract type should not have public constructors. +dotnet_diagnostic.RCS1160.severity = warning + +# RCS1161: Enum should declare explicit values. +dotnet_diagnostic.RCS1161.severity = warning + +# RCS1162: Avoid chain of assignments. +dotnet_diagnostic.RCS1162.severity = warning + +# RCS1163: Unused parameter. +dotnet_diagnostic.RCS1163.severity = warning + +# RCS1164: Unused type parameter. +dotnet_diagnostic.RCS1164.severity = warning + +# RCS1165: Unconstrained type parameter checked for null. +dotnet_diagnostic.RCS1165.severity = warning + +# RCS1166: Value type object is never equal to null. +dotnet_diagnostic.RCS1166.severity = warning + +# RCS1168: Parameter name differs from base name. +dotnet_diagnostic.RCS1168.severity = warning + +# RCS1169: Make field read-only. +dotnet_diagnostic.RCS1169.severity = warning + +# RCS1170: Use read-only auto-implemented property. +dotnet_diagnostic.RCS1170.severity = warning + +# RCS1171: Simplify lazy initialization. +dotnet_diagnostic.RCS1171.severity = suggestion + +# RCS1172: Use 'is' operator instead of 'as' operator. +dotnet_diagnostic.RCS1172.severity = warning + +# RCS1173: Use coalesce expression instead of 'if'. +dotnet_diagnostic.RCS1173.severity = warning + +# RCS1174: Remove redundant async/await. +dotnet_diagnostic.RCS1174.severity = warning + +# RCS1174FadeOut: Remove redundant async/await. (NotConfigurable) +#dotnet_diagnostic.RCS1174FadeOut.severity = silent + +# RCS1175: Unused this parameter. +dotnet_diagnostic.RCS1175.severity = warning + +# RCS1176: Use 'var' instead of explicit type (when the type is not obvious). +dotnet_diagnostic.RCS1176.severity = warning + +# RCS1177: Use 'var' instead of explicit type (in foreach). +dotnet_diagnostic.RCS1177.severity = warning + +# RCS1179: Unnecessary assignment. +dotnet_diagnostic.RCS1179.severity = warning + +# RCS1180: Inline lazy initialization. +dotnet_diagnostic.RCS1180.severity = suggestion + +# RCS1181: Convert comment to documentation comment. +dotnet_diagnostic.RCS1181.severity = warning + +# RCS1182: Remove redundant base interface. +dotnet_diagnostic.RCS1182.severity = warning + +# RCS1186: Use Regex instance instead of static method. +dotnet_diagnostic.RCS1186.severity = warning + +# RCS1187: Use constant instead of field. +dotnet_diagnostic.RCS1187.severity = warning + +# RCS1188: Remove redundant auto-property initialization. +dotnet_diagnostic.RCS1188.severity = warning + +# RCS1189: Add or remove region name. +dotnet_diagnostic.RCS1189.severity = warning + +# RCS1190: Join string expressions. +dotnet_diagnostic.RCS1190.severity = warning + +# RCS1191: Declare enum value as combination of names. +dotnet_diagnostic.RCS1191.severity = warning + +# RCS1192: Unnecessary usage of verbatim string literal. +dotnet_diagnostic.RCS1192.severity = warning + +# RCS1193: Overriding member should not change 'params' modifier. +dotnet_diagnostic.RCS1193.severity = warning + +# RCS1194: Implement exception constructors. +dotnet_diagnostic.RCS1194.severity = warning + +# RCS1195: Use ^ operator. +dotnet_diagnostic.RCS1195.severity = warning + +# RCS1196: Call extension method as instance method. +dotnet_diagnostic.RCS1196.severity = warning + +# RCS1197: Optimize StringBuilder.Append/AppendLine call. +dotnet_diagnostic.RCS1197.severity = warning + +# RCS1198: Avoid unnecessary boxing of value type. +dotnet_diagnostic.RCS1198.severity = warning + +# RCS1199: Unnecessary null check. +dotnet_diagnostic.RCS1199.severity = warning + +# RCS1200: Call 'Enumerable.ThenBy' instead of 'Enumerable.OrderBy'. +dotnet_diagnostic.RCS1200.severity = warning + +# RCS1201: Use method chaining. +dotnet_diagnostic.RCS1201.severity = warning + +# RCS1202: Avoid NullReferenceException. +dotnet_diagnostic.RCS1202.severity = warning + +# RCS1203: Use AttributeUsageAttribute. +dotnet_diagnostic.RCS1203.severity = warning + +# RCS1204: Use EventArgs.Empty. +dotnet_diagnostic.RCS1204.severity = warning + +# RCS1205: Order named arguments according to the order of parameters. +dotnet_diagnostic.RCS1205.severity = warning + +# RCS1206: Use conditional access instead of conditional expression. +dotnet_diagnostic.RCS1206.severity = warning + +# RCS1207: Convert anonymous function to method group. +dotnet_diagnostic.RCS1207.severity = warning + +# RCS1207FadeOut: Convert anonymous function to method group. (NotConfigurable) +#dotnet_diagnostic.RCS1207FadeOut.severity = silent + +# RCS1208: Reduce 'if' nesting. +dotnet_diagnostic.RCS1208.severity = warning + +# RCS1209: Order type parameter constraints. +dotnet_diagnostic.RCS1209.severity = warning + +# RCS1210: Return Task.FromResult instead of returning null. +dotnet_diagnostic.RCS1210.severity = warning + +# RCS1211: Remove unnecessary 'else'. +dotnet_diagnostic.RCS1211.severity = warning + +# RCS1212: Remove redundant assignment. +dotnet_diagnostic.RCS1212.severity = warning + +# RCS1212FadeOut: Remove redundant assignment. (NotConfigurable) +#dotnet_diagnostic.RCS1212FadeOut.severity = silent + +# RCS1213: Remove unused member declaration. +dotnet_diagnostic.RCS1213.severity = warning + +# RCS1214: Unnecessary interpolated string. +dotnet_diagnostic.RCS1214.severity = warning + +# RCS1214FadeOut: Unnecessary interpolated string. (NotConfigurable) +#dotnet_diagnostic.RCS1214FadeOut.severity = silent + +# RCS1215: Expression is always equal to true/false. +dotnet_diagnostic.RCS1215.severity = warning + +# RCS1216: Unnecessary unsafe context. +dotnet_diagnostic.RCS1216.severity = warning + +# RCS1217: Convert interpolated string to concatenation. +dotnet_diagnostic.RCS1217.severity = warning + +# RCS1217FadeOut: Convert interpolated string to concatenation. (NotConfigurable) +#dotnet_diagnostic.RCS1217FadeOut.severity = silent + +# RCS1218: Simplify code branching. +dotnet_diagnostic.RCS1218.severity = warning + +# RCS1220: Use pattern matching instead of combination of 'is' operator and cast operator. +dotnet_diagnostic.RCS1220.severity = warning + +# RCS1221: Use pattern matching instead of combination of 'as' operator and null check. +dotnet_diagnostic.RCS1221.severity = warning + +# RCS1222: Merge preprocessor directives. +dotnet_diagnostic.RCS1222.severity = warning + +# RCS1223: Mark publicly visible type with DebuggerDisplay attribute. +dotnet_diagnostic.RCS1223.severity = silent + +# RCS1224: Make method an extension method. +dotnet_diagnostic.RCS1224.severity = warning + +# RCS1225: Make class sealed. +dotnet_diagnostic.RCS1225.severity = warning + +# RCS1226: Add paragraph to documentation comment. +dotnet_diagnostic.RCS1226.severity = warning + +# RCS1227: Validate arguments correctly. +dotnet_diagnostic.RCS1227.severity = warning + +# RCS1228: Unused element in documentation comment. +dotnet_diagnostic.RCS1228.severity = warning + +# RCS1228FadeOut: Unused element in documentation comment. (NotConfigurable) +#dotnet_diagnostic.RCS1228FadeOut.severity = silent + +# RCS1229: Use async/await when necessary. +dotnet_diagnostic.RCS1229.severity = warning + +# RCS1230: Unnecessary explicit use of enumerator. +dotnet_diagnostic.RCS1230.severity = warning + +# RCS1231: Make parameter ref read-only. +dotnet_diagnostic.RCS1231.severity = suggestion + +# RCS1232: Order elements in documentation comment. +dotnet_diagnostic.RCS1232.severity = warning + +# RCS1233: Use short-circuiting operator. +dotnet_diagnostic.RCS1233.severity = warning + +# RCS1234: Duplicate enum value. +dotnet_diagnostic.RCS1234.severity = warning + +# RCS1235: Optimize method call. +dotnet_diagnostic.RCS1235.severity = warning + +# RCS1236: Use exception filter. +dotnet_diagnostic.RCS1236.severity = warning + +# RCS1237: Use bit shift operator. +dotnet_diagnostic.RCS1237.severity = suggestion + +# RCS1238: Avoid nested ?: operators. +dotnet_diagnostic.RCS1238.severity = suggestion + +# RCS1239: Use 'for' statement instead of 'while' statement. +dotnet_diagnostic.RCS1239.severity = warning + +# RCS1240: Operator is unnecessary. +dotnet_diagnostic.RCS1240.severity = warning + +# RCS1241: Implement non-generic counterpart. +dotnet_diagnostic.RCS1241.severity = warning + +# RCS1242: Do not pass non-read-only struct by read-only reference. +dotnet_diagnostic.RCS1242.severity = warning + +# RCS1243: Duplicate word in a comment. +dotnet_diagnostic.RCS1243.severity = warning + +# RCS1244: Simplify 'default' expression. +dotnet_diagnostic.RCS1244.severity = warning + +# RCS1246: Use element access. +dotnet_diagnostic.RCS1246.severity = warning + +# RCS1247: Fix documentation comment tag. +dotnet_diagnostic.RCS1247.severity = warning + +# RCS1248: Normalize null check. +dotnet_diagnostic.RCS1248.severity = warning + +# RCS1249: Unnecessary null-forgiving operator. +dotnet_diagnostic.RCS1249.severity = warning + +# RCS1250: Use implicit/explicit object creation. +dotnet_diagnostic.RCS1250.severity = warning + +# RCS1251: Remove unnecessary braces from record declaration. +dotnet_diagnostic.RCS1251.severity = warning + +# RCS1252: Normalize usage of infinite loop. +dotnet_diagnostic.RCS1252.severity = warning + +# RCS1253: Format documentation comment summary. +dotnet_diagnostic.RCS1253.severity = warning + +# RCS1254: Normalize format of enum flag value. +dotnet_diagnostic.RCS1254.severity = warning + +# ROS0001: Analyzer is obsolete. +dotnet_diagnostic.ROS0001.severity = warning + +# ROS0002: Analyzer option is obsolete. +dotnet_diagnostic.ROS0002.severity = warning + +# ROS0003: Analyzer requires config option to be specified. +dotnet_diagnostic.ROS0003.severity = warning + +## SonarAnalyzer.CSharp + +# S100: Methods and properties should be named in PascalCase +dotnet_diagnostic.S100.severity = warning + +# S1006: Method overrides should not change parameter defaults +dotnet_diagnostic.S1006.severity = warning + +# S101: Types should be named in PascalCase +dotnet_diagnostic.S101.severity = warning + +# S103: Lines should not be too long +dotnet_diagnostic.S103.severity = suggestion + +# S104: Files should not have too many lines of code +dotnet_diagnostic.S104.severity = suggestion + +# S1048: Destructors should not throw exceptions +dotnet_diagnostic.S1048.severity = warning + +# S105: Tabulation characters should not be used +dotnet_diagnostic.S105.severity = none + +# S106: Standard outputs should not be used directly to log anything +dotnet_diagnostic.S106.severity = warning + +# S1066: Collapsible "if" statements should be merged +dotnet_diagnostic.S1066.severity = warning + +# S1067: Expressions should not be too complex +dotnet_diagnostic.S1067.severity = suggestion + +# S107: Methods should not have too many parameters +dotnet_diagnostic.S107.severity = suggestion + +# S1075: URIs should not be hardcoded +dotnet_diagnostic.S1075.severity = warning + +# S108: Nested blocks of code should not be left empty +dotnet_diagnostic.S108.severity = warning + +# S109: Magic numbers should not be used +dotnet_diagnostic.S109.severity = warning + +# S110: Inheritance tree of classes should not be too deep +dotnet_diagnostic.S110.severity = suggestion + +# S1104: Fields should not have public accessibility +dotnet_diagnostic.S1104.severity = warning + +# S1109: A close curly brace should be located at the beginning of a line +dotnet_diagnostic.S1109.severity = warning + +# S1110: Redundant pairs of parentheses should be removed +dotnet_diagnostic.S1110.severity = warning + +# S1116: Empty statements should be removed +dotnet_diagnostic.S1116.severity = warning + +# S1117: Local variables should not shadow class fields +dotnet_diagnostic.S1117.severity = warning + +# S1118: Utility classes should not have public constructors +dotnet_diagnostic.S1118.severity = warning + +# S112: General exceptions should never be thrown +dotnet_diagnostic.S112.severity = warning + +# S1121: Assignments should not be made from within sub-expressions +dotnet_diagnostic.S1121.severity = warning + +# S1123: "Obsolete" attributes should include explanations +dotnet_diagnostic.S1123.severity = warning + +# S1125: Boolean literals should not be redundant +dotnet_diagnostic.S1125.severity = warning + +# S1128: Unused "using" should be removed +dotnet_diagnostic.S1128.severity = warning + +# S113: Files should contain an empty newline at the end +dotnet_diagnostic.S113.severity = warning + +# S1134: Track uses of "FIXME" tags +dotnet_diagnostic.S1134.severity = warning + +# S1135: Track uses of "TODO" tags +dotnet_diagnostic.S1135.severity = warning + +# S1144: Unused private types or members should be removed +dotnet_diagnostic.S1144.severity = warning + +# S1147: Exit methods should not be called +dotnet_diagnostic.S1147.severity = warning + +# S1151: "switch case" clauses should not have too many lines of code +dotnet_diagnostic.S1151.severity = suggestion + +# S1155: "Any()" should be used to test for emptiness +dotnet_diagnostic.S1155.severity = warning + +# S1163: Exceptions should not be thrown in finally blocks +dotnet_diagnostic.S1163.severity = warning + +# S1168: Empty arrays and collections should be returned instead of null +dotnet_diagnostic.S1168.severity = warning + +# S1172: Unused method parameters should be removed +dotnet_diagnostic.S1172.severity = warning + +# S1185: Overriding members should do more than simply call the same member in the base class +dotnet_diagnostic.S1185.severity = warning + +# S1186: Methods should not be empty +dotnet_diagnostic.S1186.severity = warning + +# S1192: String literals should not be duplicated +dotnet_diagnostic.S1192.severity = warning + +# S1199: Nested code blocks should not be used +dotnet_diagnostic.S1199.severity = warning + +# S1200: Classes should not be coupled to too many other classes (Single Responsibility Principle) +dotnet_diagnostic.S1200.severity = suggestion + +# S1206: "Equals(Object)" and "GetHashCode()" should be overridden in pairs +dotnet_diagnostic.S1206.severity = warning + +# S121: Control structures should use curly braces +dotnet_diagnostic.S121.severity = warning + +# S1210: "Equals" and the comparison operators should be overridden when implementing "IComparable" +dotnet_diagnostic.S1210.severity = warning + +# S1215: "GC.Collect" should not be called +dotnet_diagnostic.S1215.severity = warning + +# S122: Statements should be on separate lines +dotnet_diagnostic.S122.severity = warning + +# S1226: Method parameters, caught exceptions and foreach variables' initial values should not be ignored +dotnet_diagnostic.S1226.severity = warning + +# S1227: break statements should not be used except for switch cases +dotnet_diagnostic.S1227.severity = warning + +# S1244: Floating point numbers should not be tested for equality +dotnet_diagnostic.S1244.severity = warning + +# S125: Sections of code should not be commented out +dotnet_diagnostic.S125.severity = warning + +# S126: "if ... else if" constructs should end with "else" clauses +dotnet_diagnostic.S126.severity = warning + +# S1264: A "while" loop should be used instead of a "for" loop +dotnet_diagnostic.S1264.severity = warning + +# S127: "for" loop stop conditions should be invariant +dotnet_diagnostic.S127.severity = warning + +# S1301: "switch" statements should have at least 3 "case" clauses +dotnet_diagnostic.S1301.severity = warning + +# S1309: Track uses of in-source issue suppressions +dotnet_diagnostic.S1309.severity = warning + +# S131: "switch/Select" statements should contain a "default/Case Else" clauses +dotnet_diagnostic.S131.severity = warning + +# S1313: Using hardcoded IP addresses is security-sensitive +dotnet_diagnostic.S1313.severity = warning + +# S134: Control flow statements "if", "switch", "for", "foreach", "while", "do" and "try" should not be nested too deeply +dotnet_diagnostic.S134.severity = suggestion + +# S138: Functions should not have too many lines of code +dotnet_diagnostic.S138.severity = suggestion + +# S1449: Culture should be specified for "string" operations +dotnet_diagnostic.S1449.severity = warning + +# S1450: Private fields only used as local variables in methods should become local variables +dotnet_diagnostic.S1450.severity = warning + +# S1451: Track lack of copyright and license headers +dotnet_diagnostic.S1451.severity = none + +# S1479: "switch" statements should not have too many "case" clauses +dotnet_diagnostic.S1479.severity = suggestion + +# S1481: Unused local variables should be removed +dotnet_diagnostic.S1481.severity = warning + +# S1541: Methods and properties should not be too complex +dotnet_diagnostic.S1541.severity = suggestion + +# S1607: Tests should not be ignored +dotnet_diagnostic.S1607.severity = warning + +# S1643: Strings should not be concatenated using '+' in a loop +dotnet_diagnostic.S1643.severity = warning + +# S1656: Variables should not be self-assigned +dotnet_diagnostic.S1656.severity = warning + +# S1659: Multiple variables should not be declared on the same line +dotnet_diagnostic.S1659.severity = warning + +# S1694: An abstract class should have both abstract and concrete methods +dotnet_diagnostic.S1694.severity = warning + +# S1696: NullReferenceException should not be caught +dotnet_diagnostic.S1696.severity = warning + +# S1698: "==" should not be used when "Equals" is overridden +dotnet_diagnostic.S1698.severity = warning + +# S1699: Constructors should only call non-overridable methods +dotnet_diagnostic.S1699.severity = warning + +# S1751: Loops with at most one iteration should be refactored +dotnet_diagnostic.S1751.severity = warning + +# S1764: Identical expressions should not be used on both sides of a binary operator +dotnet_diagnostic.S1764.severity = warning + +# S1821: "switch" statements should not be nested +dotnet_diagnostic.S1821.severity = warning + +# S1848: Objects should not be created to be dropped immediately without being used +dotnet_diagnostic.S1848.severity = warning + +# S1854: Unused assignments should be removed +dotnet_diagnostic.S1854.severity = warning + +# S1858: "ToString()" calls should not be redundant +dotnet_diagnostic.S1858.severity = warning + +# S1862: Related "if/else if" statements should not have the same condition +dotnet_diagnostic.S1862.severity = warning + +# S1871: Two branches in a conditional structure should not have exactly the same implementation +dotnet_diagnostic.S1871.severity = warning + +# S1905: Redundant casts should not be used +dotnet_diagnostic.S1905.severity = warning + +# S1939: Inheritance list should not be redundant +dotnet_diagnostic.S1939.severity = warning + +# S1940: Boolean checks should not be inverted +dotnet_diagnostic.S1940.severity = warning + +# S1944: Inappropriate casts should not be made +dotnet_diagnostic.S1944.severity = warning + +# S1994: "for" loop increment clauses should modify the loops' counters +dotnet_diagnostic.S1994.severity = warning + +# S2053: Hashes should include an unpredictable salt +dotnet_diagnostic.S2053.severity = warning + +# S2068: Hard-coded credentials are security-sensitive +dotnet_diagnostic.S2068.severity = warning + +# S2077: Formatting SQL queries is security-sensitive +dotnet_diagnostic.S2077.severity = warning + +# S2092: Creating cookies without the "secure" flag is security-sensitive +dotnet_diagnostic.S2092.severity = warning + +# S2114: Collections should not be passed as arguments to their own methods +dotnet_diagnostic.S2114.severity = warning + +# S2115: A secure password should be used when connecting to a database +dotnet_diagnostic.S2115.severity = warning + +# S2123: Values should not be uselessly incremented +dotnet_diagnostic.S2123.severity = warning + +# S2148: Underscores should be used to make large numbers readable +dotnet_diagnostic.S2148.severity = warning + +# S2156: "sealed" classes should not have "protected" members +dotnet_diagnostic.S2156.severity = warning + +# S2178: Short-circuit logic should be used in boolean contexts +dotnet_diagnostic.S2178.severity = warning + +# S2183: Integral numbers should not be shifted by zero or more than their number of bits-1 +dotnet_diagnostic.S2183.severity = warning + +# S2184: Results of integer division should not be assigned to floating point variables +dotnet_diagnostic.S2184.severity = warning + +# S2187: TestCases should contain tests +dotnet_diagnostic.S2187.severity = warning + +# S2190: Recursion should not be infinite +dotnet_diagnostic.S2190.severity = warning + +# S2197: Modulus results should not be checked for direct equality +dotnet_diagnostic.S2197.severity = warning + +# S2201: Return values from functions without side effects should not be ignored +dotnet_diagnostic.S2201.severity = warning + +# S2219: Runtime type checking should be simplified +dotnet_diagnostic.S2219.severity = warning + +# S2221: "Exception" should not be caught when not required by called methods +dotnet_diagnostic.S2221.severity = warning + +# S2222: Locks should be released +dotnet_diagnostic.S2222.severity = warning + +# S2223: Non-constant static fields should not be visible +dotnet_diagnostic.S2223.severity = warning + +# S2225: "ToString()" method should not return null +dotnet_diagnostic.S2225.severity = warning + +# S2228: Console logging should not be used +dotnet_diagnostic.S2228.severity = warning + +# S2234: Parameters should be passed in the correct order +dotnet_diagnostic.S2234.severity = warning + +# S2245: Using pseudorandom number generators (PRNGs) is security-sensitive +dotnet_diagnostic.S2245.severity = warning + +# S2251: A "for" loop update clause should move the counter in the right direction +dotnet_diagnostic.S2251.severity = warning + +# S2252: For-loop conditions should be true at least once +dotnet_diagnostic.S2252.severity = warning + +# S2255: Writing cookies is security-sensitive +dotnet_diagnostic.S2255.severity = warning + +# S2257: Using non-standard cryptographic algorithms is security-sensitive +dotnet_diagnostic.S2257.severity = warning + +# S2259: Null pointers should not be dereferenced +dotnet_diagnostic.S2259.severity = warning + +# S2275: Composite format strings should not lead to unexpected behavior at runtime +dotnet_diagnostic.S2275.severity = warning + +# S2290: Field-like events should not be virtual +dotnet_diagnostic.S2290.severity = warning + +# S2291: Overflow checking should not be disabled for "Enumerable.Sum" +dotnet_diagnostic.S2291.severity = warning + +# S2292: Trivial properties should be auto-implemented +dotnet_diagnostic.S2292.severity = warning + +# S2302: "nameof" should be used +dotnet_diagnostic.S2302.severity = warning + +# S2306: "async" and "await" should not be used as identifiers +dotnet_diagnostic.S2306.severity = warning + +# S2325: Methods and properties that don't access instance data should be static +dotnet_diagnostic.S2325.severity = warning + +# S2326: Unused type parameters should be removed +dotnet_diagnostic.S2326.severity = warning + +# S2327: "try" statements with identical "catch" and/or "finally" blocks should be merged +dotnet_diagnostic.S2327.severity = warning + +# S2328: "GetHashCode" should not reference mutable fields +dotnet_diagnostic.S2328.severity = warning + +# S2330: Array covariance should not be used +dotnet_diagnostic.S2330.severity = warning + +# S2333: Redundant modifiers should not be used +dotnet_diagnostic.S2333.severity = warning + +# S2339: Public constant members should not be used +dotnet_diagnostic.S2339.severity = warning + +# S2342: Enumeration types should comply with a naming convention +dotnet_diagnostic.S2342.severity = warning + +# S2344: Enumeration type names should not have "Flags" or "Enum" suffixes +dotnet_diagnostic.S2344.severity = warning + +# S2345: Flags enumerations should explicitly initialize all their members +dotnet_diagnostic.S2345.severity = warning + +# S2346: Flags enumerations zero-value members should be named "None" +dotnet_diagnostic.S2346.severity = warning + +# S2357: Fields should be private +dotnet_diagnostic.S2357.severity = warning + +# S2360: Optional parameters should not be used +dotnet_diagnostic.S2360.severity = warning + +# S2365: Properties should not make collection or array copies +dotnet_diagnostic.S2365.severity = warning + +# S2368: Public methods should not have multidimensional array parameters +dotnet_diagnostic.S2368.severity = suggestion + +# S2372: Exceptions should not be thrown from property getters +dotnet_diagnostic.S2372.severity = warning + +# S2376: Write-only properties should not be used +dotnet_diagnostic.S2376.severity = warning + +# S2386: Mutable fields should not be "public static" +dotnet_diagnostic.S2386.severity = warning + +# S2387: Child class fields should not shadow parent class fields +dotnet_diagnostic.S2387.severity = warning + +# S2436: Types and methods should not have too many generic parameters +dotnet_diagnostic.S2436.severity = suggestion + +# S2437: Silly bit operations should not be performed +dotnet_diagnostic.S2437.severity = warning + +# S2479: Whitespace and control characters in string literals should be explicit +dotnet_diagnostic.S2479.severity = warning + +# S2486: Generic exceptions should not be ignored +dotnet_diagnostic.S2486.severity = warning + +# S2551: Shared resources should not be used for locking +dotnet_diagnostic.S2551.severity = warning + +# S2583: Conditionally executed code should be reachable +dotnet_diagnostic.S2583.severity = warning + +# S2589: Boolean expressions should not be gratuitous +dotnet_diagnostic.S2589.severity = warning + +# S2612: Setting loose file permissions is security-sensitive +dotnet_diagnostic.S2612.severity = warning + +# S2674: The length returned from a stream read should be checked +dotnet_diagnostic.S2674.severity = warning + +# S2681: Multiline blocks should be enclosed in curly braces +dotnet_diagnostic.S2681.severity = warning + +# S2688: "NaN" should not be used in comparisons +dotnet_diagnostic.S2688.severity = warning + +# S2692: "IndexOf" checks should not be for positive numbers +dotnet_diagnostic.S2692.severity = warning + +# S2696: Instance members should not write to "static" fields +dotnet_diagnostic.S2696.severity = warning + +# S2699: Tests should include assertions +dotnet_diagnostic.S2699.severity = warning + +# S2701: Literal boolean values should not be used in assertions +dotnet_diagnostic.S2701.severity = warning + +# S2737: "catch" clauses should do more than rethrow +dotnet_diagnostic.S2737.severity = warning + +# S2743: Static fields should not be used in generic types +dotnet_diagnostic.S2743.severity = warning + +# S2755: XML parsers should not be vulnerable to XXE attacks +dotnet_diagnostic.S2755.severity = warning + +# S2757: "=+" should not be used instead of "+=" +dotnet_diagnostic.S2757.severity = warning + +# S2760: Sequential tests should not check the same condition +dotnet_diagnostic.S2760.severity = warning + +# S2761: Doubled prefix operators "!!" and "~~" should not be used +dotnet_diagnostic.S2761.severity = warning + +# S2857: SQL keywords should be delimited by whitespace +dotnet_diagnostic.S2857.severity = warning + +# S2930: "IDisposables" should be disposed +dotnet_diagnostic.S2930.severity = warning + +# S2931: Classes with "IDisposable" members should implement "IDisposable" +dotnet_diagnostic.S2931.severity = warning + +# S2933: Fields that are only assigned in the constructor should be "readonly" +dotnet_diagnostic.S2933.severity = warning + +# S2934: Property assignments should not be made for "readonly" fields not constrained to reference types +dotnet_diagnostic.S2934.severity = warning + +# S2952: Classes should "Dispose" of members from the classes' own "Dispose" methods +dotnet_diagnostic.S2952.severity = warning + +# S2953: Methods named "Dispose" should implement "IDisposable.Dispose" +dotnet_diagnostic.S2953.severity = warning + +# S2955: Generic parameters not constrained to reference types should not be compared to "null" +dotnet_diagnostic.S2955.severity = warning + +# S2971: "IEnumerable" LINQs should be simplified +dotnet_diagnostic.S2971.severity = warning + +# S2995: "Object.ReferenceEquals" should not be used for value types +dotnet_diagnostic.S2995.severity = warning + +# S2996: "ThreadStatic" fields should not be initialized +dotnet_diagnostic.S2996.severity = warning + +# S2997: "IDisposables" created in a "using" statement should not be returned +dotnet_diagnostic.S2997.severity = warning + +# S3005: "ThreadStatic" should not be used on non-static fields +dotnet_diagnostic.S3005.severity = warning + +# S3010: Static fields should not be updated in constructors +dotnet_diagnostic.S3010.severity = warning + +# S3011: Reflection should not be used to increase accessibility of classes, methods, or fields +dotnet_diagnostic.S3011.severity = warning + +# S3052: Members should not be initialized to default values +dotnet_diagnostic.S3052.severity = warning + +# S3059: Types should not have members with visibility set higher than the type's visibility +dotnet_diagnostic.S3059.severity = warning + +# S3060: "is" should not be used with "this" +dotnet_diagnostic.S3060.severity = warning + +# S3168: "async" methods should not return "void" +dotnet_diagnostic.S3168.severity = warning + +# S3169: Multiple "OrderBy" calls should not be used +dotnet_diagnostic.S3169.severity = warning + +# S3172: Delegates should not be subtracted +dotnet_diagnostic.S3172.severity = warning + +# S3215: "interface" instances should not be cast to concrete types +dotnet_diagnostic.S3215.severity = warning + +# S3216: "ConfigureAwait(false)" should be used +dotnet_diagnostic.S3216.severity = warning + +# S3217: "Explicit" conversions of "foreach" loops should not be used +dotnet_diagnostic.S3217.severity = warning + +# S3218: Inner class members should not shadow outer class "static" or type members +dotnet_diagnostic.S3218.severity = warning + +# S3220: Method calls should not resolve ambiguously to overloads with "params" +dotnet_diagnostic.S3220.severity = warning + +# S3234: "GC.SuppressFinalize" should not be invoked for types without destructors +dotnet_diagnostic.S3234.severity = warning + +# S3235: Redundant parentheses should not be used +dotnet_diagnostic.S3235.severity = none + +# S3236: Caller information arguments should not be provided explicitly +dotnet_diagnostic.S3236.severity = warning + +# S3237: "value" parameters should be used +dotnet_diagnostic.S3237.severity = warning + +# S3240: The simplest possible condition syntax should be used +dotnet_diagnostic.S3240.severity = warning + +# S3241: Methods should not return values that are never used +dotnet_diagnostic.S3241.severity = warning + +# S3242: Method parameters should be declared with base types +dotnet_diagnostic.S3242.severity = warning + +# S3244: Anonymous delegates should not be used to unsubscribe from Events +dotnet_diagnostic.S3244.severity = warning + +# S3246: Generic type parameters should be co/contravariant when possible +dotnet_diagnostic.S3246.severity = warning + +# S3247: Duplicate casts should not be made +dotnet_diagnostic.S3247.severity = warning + +# S3249: Classes directly extending "object" should not call "base" in "GetHashCode" or "Equals" +dotnet_diagnostic.S3249.severity = warning + +# S3251: Implementations should be provided for "partial" methods +dotnet_diagnostic.S3251.severity = warning + +# S3253: Constructor and destructor declarations should not be redundant +dotnet_diagnostic.S3253.severity = warning + +# S3254: Default parameter values should not be passed as arguments +dotnet_diagnostic.S3254.severity = warning + +# S3256: "string.IsNullOrEmpty" should be used +dotnet_diagnostic.S3256.severity = warning + +# S3257: Declarations and initializations should be as concise as possible +dotnet_diagnostic.S3257.severity = warning + +# S3260: Non-derived "private" classes and records should be "sealed" +dotnet_diagnostic.S3260.severity = warning + +# S3261: Namespaces should not be empty +dotnet_diagnostic.S3261.severity = warning + +# S3262: "params" should be used on overrides +dotnet_diagnostic.S3262.severity = warning + +# S3263: Static fields should appear in the order they must be initialized +dotnet_diagnostic.S3263.severity = warning + +# S3264: Events should be invoked +dotnet_diagnostic.S3264.severity = warning + +# S3265: Non-flags enums should not be used in bitwise operations +dotnet_diagnostic.S3265.severity = warning + +# S3267: Loops should be simplified with "LINQ" expressions +dotnet_diagnostic.S3267.severity = warning + +# S3329: Cipher Block Chaining IV's should be unpredictable +dotnet_diagnostic.S3329.severity = warning + +# S3330: Creating cookies without the "HttpOnly" flag is security-sensitive +dotnet_diagnostic.S3330.severity = warning + +# S3343: Caller information parameters should come at the end of the parameter list +dotnet_diagnostic.S3343.severity = warning + +# S3346: Expressions used in "Debug.Assert" should not produce side effects +dotnet_diagnostic.S3346.severity = warning + +# S3353: Unchanged local variables should be "const" +dotnet_diagnostic.S3353.severity = warning + +# S3358: Ternary operators should not be nested +dotnet_diagnostic.S3358.severity = suggestion + +# S3366: "this" should not be exposed from constructors +dotnet_diagnostic.S3366.severity = warning + +# S3376: Attribute, EventArgs, and Exception type names should end with the type being extended +dotnet_diagnostic.S3376.severity = warning + +# S3397: "base.Equals" should not be used to check for reference equality in "Equals" if "base" is not "object" +dotnet_diagnostic.S3397.severity = warning + +# S3400: Methods should not return constants +dotnet_diagnostic.S3400.severity = warning + +# S3415: Assertion arguments should be passed in the correct order +dotnet_diagnostic.S3415.severity = warning + +# S3427: Method overloads with default parameter values should not overlap +dotnet_diagnostic.S3427.severity = warning + +# S3431: "[ExpectedException]" should not be used +dotnet_diagnostic.S3431.severity = warning + +# S3433: Test method signatures should be correct +dotnet_diagnostic.S3433.severity = warning + +# S3440: Variables should not be checked against the values they're about to be assigned +dotnet_diagnostic.S3440.severity = warning + +# S3441: Redundant property names should be omitted in anonymous classes +dotnet_diagnostic.S3441.severity = warning + +# S3442: "abstract" classes should not have "public" constructors +dotnet_diagnostic.S3442.severity = warning + +# S3443: Type should not be examined on "System.Type" instances +dotnet_diagnostic.S3443.severity = warning + +# S3444: Interfaces should not simply inherit from base interfaces with colliding members +dotnet_diagnostic.S3444.severity = warning + +# S3445: Exceptions should not be explicitly rethrown +dotnet_diagnostic.S3445.severity = warning + +# S3447: "[Optional]" should not be used on "ref" or "out" parameters +dotnet_diagnostic.S3447.severity = warning + +# S3449: Right operands of shift operators should be integers +dotnet_diagnostic.S3449.severity = warning + +# S3450: Parameters with "[DefaultParameterValue]" attributes should also be marked "[Optional]" +dotnet_diagnostic.S3450.severity = warning + +# S3451: "[DefaultValue]" should not be used when "[DefaultParameterValue]" is meant +dotnet_diagnostic.S3451.severity = warning + +# S3453: Classes should not have only "private" constructors +dotnet_diagnostic.S3453.severity = warning + +# S3456: "string.ToCharArray()" should not be called redundantly +dotnet_diagnostic.S3456.severity = warning + +# S3457: Composite format strings should be used correctly +dotnet_diagnostic.S3457.severity = warning + +# S3458: Empty "case" clauses that fall through to the "default" should be omitted +dotnet_diagnostic.S3458.severity = warning + +# S3459: Unassigned members should be removed +dotnet_diagnostic.S3459.severity = warning + +# S3464: Type inheritance should not be recursive +dotnet_diagnostic.S3464.severity = warning + +# S3466: Optional parameters should be passed to "base" calls +dotnet_diagnostic.S3466.severity = warning + +# S3532: Empty "default" clauses should be removed +dotnet_diagnostic.S3532.severity = warning + +# S3597: "ServiceContract" and "OperationContract" attributes should be used together +dotnet_diagnostic.S3597.severity = warning + +# S3598: One-way "OperationContract" methods should have "void" return type +dotnet_diagnostic.S3598.severity = warning + +# S3600: "params" should not be introduced on overrides +dotnet_diagnostic.S3600.severity = warning + +# S3603: Methods with "Pure" attribute should return a value +dotnet_diagnostic.S3603.severity = warning + +# S3604: Member initializer values should not be redundant +dotnet_diagnostic.S3604.severity = warning + +# S3610: Nullable type comparison should not be redundant +dotnet_diagnostic.S3610.severity = warning + +# S3626: Jump statements should not be redundant +dotnet_diagnostic.S3626.severity = warning + +# S3655: Empty nullable value should not be accessed +dotnet_diagnostic.S3655.severity = warning + +# S3717: Track use of "NotImplementedException" +dotnet_diagnostic.S3717.severity = warning + +# S3776: Cognitive Complexity of methods should not be too high +dotnet_diagnostic.S3776.severity = suggestion + +# S3869: "SafeHandle.DangerousGetHandle" should not be called +dotnet_diagnostic.S3869.severity = warning + +# S3871: Exception types should be "public" +dotnet_diagnostic.S3871.severity = warning + +# S3872: Parameter names should not duplicate the names of their methods +dotnet_diagnostic.S3872.severity = warning + +# S3874: "out" and "ref" parameters should not be used +dotnet_diagnostic.S3874.severity = suggestion + +# S3875: "operator==" should not be overloaded on reference types +dotnet_diagnostic.S3875.severity = warning + +# S3876: Strings or integral types should be used for indexers +dotnet_diagnostic.S3876.severity = warning + +# S3877: Exceptions should not be thrown from unexpected methods +dotnet_diagnostic.S3877.severity = warning + +# S3880: Finalizers should not be empty +dotnet_diagnostic.S3880.severity = warning + +# S3881: "IDisposable" should be implemented correctly +dotnet_diagnostic.S3881.severity = warning + +# S3884: "CoSetProxyBlanket" and "CoInitializeSecurity" should not be used +dotnet_diagnostic.S3884.severity = warning + +# S3885: "Assembly.Load" should be used +dotnet_diagnostic.S3885.severity = warning + +# S3887: Mutable, non-private fields should not be "readonly" +dotnet_diagnostic.S3887.severity = warning + +# S3889: Neither "Thread.Resume" nor "Thread.Suspend" should be used +dotnet_diagnostic.S3889.severity = warning + +# S3897: Classes that provide "Equals()" should implement "IEquatable" +dotnet_diagnostic.S3897.severity = warning + +# S3898: Value types should implement "IEquatable" +dotnet_diagnostic.S3898.severity = warning + +# S3900: Arguments of public methods should be validated against null +dotnet_diagnostic.S3900.severity = warning + +# S3902: "Assembly.GetExecutingAssembly" should not be called +dotnet_diagnostic.S3902.severity = warning + +# S3903: Types should be defined in named namespaces +dotnet_diagnostic.S3903.severity = warning + +# S3904: Assemblies should have version information +dotnet_diagnostic.S3904.severity = warning + +# S3906: Event Handlers should have the correct signature +dotnet_diagnostic.S3906.severity = warning + +# S3908: Generic event handlers should be used +dotnet_diagnostic.S3908.severity = warning + +# S3909: Collections should implement the generic interface +dotnet_diagnostic.S3909.severity = warning + +# S3923: All branches in a conditional structure should not have exactly the same implementation +dotnet_diagnostic.S3923.severity = warning + +# S3925: "ISerializable" should be implemented correctly +dotnet_diagnostic.S3925.severity = warning + +# S3926: Deserialization methods should be provided for "OptionalField" members +dotnet_diagnostic.S3926.severity = warning + +# S3927: Serialization event handlers should be implemented correctly +dotnet_diagnostic.S3927.severity = warning + +# S3928: Parameter names used into ArgumentException constructors should match an existing one +dotnet_diagnostic.S3928.severity = warning + +# S3937: Number patterns should be regular +dotnet_diagnostic.S3937.severity = warning + +# S3949: Calculations should not overflow +dotnet_diagnostic.S3949.severity = warning + +# S3956: "Generic.List" instances should not be part of public APIs +dotnet_diagnostic.S3956.severity = warning + +# S3962: "static readonly" constants should be "const" instead +dotnet_diagnostic.S3962.severity = warning + +# S3963: "static" fields should be initialized inline +dotnet_diagnostic.S3963.severity = warning + +# S3966: Objects should not be disposed more than once +dotnet_diagnostic.S3966.severity = warning + +# S3967: Multidimensional arrays should not be used +dotnet_diagnostic.S3967.severity = suggestion + +# S3971: "GC.SuppressFinalize" should not be called +dotnet_diagnostic.S3971.severity = warning + +# S3972: Conditionals should start on new lines +dotnet_diagnostic.S3972.severity = warning + +# S3973: A conditionally executed single line should be denoted by indentation +dotnet_diagnostic.S3973.severity = warning + +# S3981: Collection sizes and array length comparisons should make sense +dotnet_diagnostic.S3981.severity = warning + +# S3984: Exceptions should not be created without being thrown +dotnet_diagnostic.S3984.severity = warning + +# S3990: Assemblies should be marked as CLS compliant +dotnet_diagnostic.S3990.severity = warning + +# S3992: Assemblies should explicitly specify COM visibility +dotnet_diagnostic.S3992.severity = warning + +# S3993: Custom attributes should be marked with "System.AttributeUsageAttribute" +dotnet_diagnostic.S3993.severity = warning + +# S3994: URI Parameters should not be strings +dotnet_diagnostic.S3994.severity = warning + +# S3995: URI return values should not be strings +dotnet_diagnostic.S3995.severity = warning + +# S3996: URI properties should not be strings +dotnet_diagnostic.S3996.severity = warning + +# S3997: String URI overloads should call "System.Uri" overloads +dotnet_diagnostic.S3997.severity = warning + +# S3998: Threads should not lock on objects with weak identity +dotnet_diagnostic.S3998.severity = warning + +# S4000: Pointers to unmanaged memory should not be visible +dotnet_diagnostic.S4000.severity = warning + +# S4002: Disposable types should declare finalizers +dotnet_diagnostic.S4002.severity = warning + +# S4004: Collection properties should be readonly +dotnet_diagnostic.S4004.severity = suggestion + +# S4005: "System.Uri" arguments should be used instead of strings +dotnet_diagnostic.S4005.severity = warning + +# S4015: Inherited member visibility should not be decreased +dotnet_diagnostic.S4015.severity = warning + +# S4016: Enumeration members should not be named "Reserved" +dotnet_diagnostic.S4016.severity = warning + +# S4017: Method signatures should not contain nested generic types +dotnet_diagnostic.S4017.severity = suggestion + +# S4018: Generic methods should provide type parameters +dotnet_diagnostic.S4018.severity = warning + +# S4019: Base class methods should not be hidden +dotnet_diagnostic.S4019.severity = warning + +# S4022: Enumerations should have "Int32" storage +dotnet_diagnostic.S4022.severity = warning + +# S4023: Interfaces should not be empty +dotnet_diagnostic.S4023.severity = suggestion + +# S4025: Child class fields should not differ from parent class fields only by capitalization +dotnet_diagnostic.S4025.severity = warning + +# S4026: Assemblies should be marked with "NeutralResourcesLanguageAttribute" +dotnet_diagnostic.S4026.severity = warning + +# S4027: Exceptions should provide standard constructors +dotnet_diagnostic.S4027.severity = warning + +# S4035: Classes implementing "IEquatable" should be sealed +dotnet_diagnostic.S4035.severity = warning + +# S4036: Searching OS commands in PATH is security-sensitive +dotnet_diagnostic.S4036.severity = warning + +# S4039: Interface methods should be callable by derived types +dotnet_diagnostic.S4039.severity = warning + +# S4040: Strings should be normalized to uppercase +dotnet_diagnostic.S4040.severity = warning + +# S4041: Type names should not match namespaces +dotnet_diagnostic.S4041.severity = warning + +# S4047: Generics should be used when appropriate +dotnet_diagnostic.S4047.severity = warning + +# S4049: Properties should be preferred +dotnet_diagnostic.S4049.severity = suggestion + +# S4050: Operators should be overloaded consistently +dotnet_diagnostic.S4050.severity = warning + +# S4052: Types should not extend outdated base types +dotnet_diagnostic.S4052.severity = warning + +# S4055: Literals should not be passed as localized parameters +dotnet_diagnostic.S4055.severity = warning + +# S4056: Overloads with a "CultureInfo" or an "IFormatProvider" parameter should be used +dotnet_diagnostic.S4056.severity = warning + +# S4057: Locales should be set for data types +dotnet_diagnostic.S4057.severity = warning + +# S4058: Overloads with a "StringComparison" parameter should be used +dotnet_diagnostic.S4058.severity = warning + +# S4059: Property names should not match get methods +dotnet_diagnostic.S4059.severity = warning + +# S4060: Non-abstract attributes should be sealed +dotnet_diagnostic.S4060.severity = suggestion + +# S4061: "params" should be used instead of "varargs" +dotnet_diagnostic.S4061.severity = warning + +# S4069: Operator overloads should have named alternatives +dotnet_diagnostic.S4069.severity = warning + +# S4070: Non-flags enums should not be marked with "FlagsAttribute" +dotnet_diagnostic.S4070.severity = warning + +# S4136: Method overloads should be grouped together +dotnet_diagnostic.S4136.severity = warning + +# S4143: Collection elements should not be replaced unconditionally +dotnet_diagnostic.S4143.severity = warning + +# S4144: Methods should not have identical implementations +dotnet_diagnostic.S4144.severity = warning + +# S4158: Empty collections should not be accessed or iterated +dotnet_diagnostic.S4158.severity = warning + +# S4159: Classes should implement their "ExportAttribute" interfaces +dotnet_diagnostic.S4159.severity = warning + +# S4200: Native methods should be wrapped +dotnet_diagnostic.S4200.severity = warning + +# S4201: Null checks should not be used with "is" +dotnet_diagnostic.S4201.severity = warning + +# S4210: Windows Forms entry points should be marked with STAThread +dotnet_diagnostic.S4210.severity = warning + +# S4211: Members should not have conflicting transparency annotations +dotnet_diagnostic.S4211.severity = warning + +# S4212: Serialization constructors should be secured +dotnet_diagnostic.S4212.severity = warning + +# S4214: "P/Invoke" methods should not be visible +dotnet_diagnostic.S4214.severity = warning + +# S4220: Events should have proper arguments +dotnet_diagnostic.S4220.severity = warning + +# S4225: Extension methods should not extend "object" +dotnet_diagnostic.S4225.severity = warning + +# S4226: Extensions should be in separate namespaces +dotnet_diagnostic.S4226.severity = warning + +# S4260: "ConstructorArgument" parameters should exist in constructors +dotnet_diagnostic.S4260.severity = warning + +# S4261: Methods should be named according to their synchronicities +dotnet_diagnostic.S4261.severity = warning + +# S4275: Getters and setters should access the expected fields +dotnet_diagnostic.S4275.severity = warning + +# S4277: "Shared" parts should not be created with "new" +dotnet_diagnostic.S4277.severity = warning + +# S4423: Weak SSL/TLS protocols should not be used +dotnet_diagnostic.S4423.severity = warning + +# S4426: Cryptographic keys should be robust +dotnet_diagnostic.S4426.severity = warning + +# S4428: "PartCreationPolicyAttribute" should be used with "ExportAttribute" +dotnet_diagnostic.S4428.severity = warning + +# S4433: LDAP connections should be authenticated +dotnet_diagnostic.S4433.severity = warning + +# S4456: Parameter validation in yielding methods should be wrapped +dotnet_diagnostic.S4456.severity = warning + +# S4457: Parameter validation in "async"/"await" methods should be wrapped +dotnet_diagnostic.S4457.severity = warning + +# S4462: Calls to "async" methods should not be blocking +dotnet_diagnostic.S4462.severity = warning + +# S4487: Unread "private" fields should be removed +dotnet_diagnostic.S4487.severity = warning + +# S4502: Disabling CSRF protections is security-sensitive +dotnet_diagnostic.S4502.severity = warning + +# S4507: Delivering code in production with debug features activated is security-sensitive +dotnet_diagnostic.S4507.severity = warning + +# S4524: "default" clauses should be first or last +dotnet_diagnostic.S4524.severity = warning + +# S4564: ASP.NET HTTP request validation feature should not be disabled +dotnet_diagnostic.S4564.severity = warning + +# S4581: "new Guid()" should not be used +dotnet_diagnostic.S4581.severity = warning + +# S4583: Calls to delegate's method "BeginInvoke" should be paired with calls to "EndInvoke" +dotnet_diagnostic.S4583.severity = warning + +# S4586: Non-async "Task/Task" methods should not return null +dotnet_diagnostic.S4586.severity = warning + +# S4635: String offset-based methods should be preferred for finding substrings from offsets +dotnet_diagnostic.S4635.severity = warning + +# S4784: Using regular expressions is security-sensitive +dotnet_diagnostic.S4784.severity = warning + +# S4787: Encrypting data is security-sensitive +dotnet_diagnostic.S4787.severity = warning + +# S4790: Using weak hashing algorithms is security-sensitive +dotnet_diagnostic.S4790.severity = warning + +# S4792: Configuring loggers is security-sensitive +dotnet_diagnostic.S4792.severity = warning + +# S4818: Using Sockets is security-sensitive +dotnet_diagnostic.S4818.severity = warning + +# S4823: Using command line arguments is security-sensitive +dotnet_diagnostic.S4823.severity = warning + +# S4829: Reading the Standard Input is security-sensitive +dotnet_diagnostic.S4829.severity = warning + +# S4830: Server certificates should be verified during SSL/TLS connections +dotnet_diagnostic.S4830.severity = warning + +# S4834: Controlling permissions is security-sensitive +dotnet_diagnostic.S4834.severity = warning + +# S5034: "ValueTask" should be consumed correctly +dotnet_diagnostic.S5034.severity = warning + +# S5042: Expanding archive files is security-sensitive +dotnet_diagnostic.S5042.severity = warning + +# S5122: Having a permissive Cross-Origin Resource Sharing policy is security-sensitive +dotnet_diagnostic.S5122.severity = warning + +# S5332: Using clear-text protocols is security-sensitive +dotnet_diagnostic.S5332.severity = warning + +# S5443: Using publicly writable directories is security-sensitive +dotnet_diagnostic.S5443.severity = warning + +# S5445: Insecure temporary file creation methods should not be used +dotnet_diagnostic.S5445.severity = warning + +# S5542: Encryption algorithms should be used with secure mode and padding scheme +dotnet_diagnostic.S5542.severity = warning + +# S5547: Cipher algorithms should be robust +dotnet_diagnostic.S5547.severity = warning + +# S5659: JWT should be signed and verified with strong cipher algorithms +dotnet_diagnostic.S5659.severity = warning + +# S5693: Allowing requests with excessive content length is security-sensitive +dotnet_diagnostic.S5693.severity = warning + +# S5753: Disabling ASP.NET "Request Validation" feature is security-sensitive +dotnet_diagnostic.S5753.severity = warning + +# S5766: Deserializing objects without performing data validation is security-sensitive +dotnet_diagnostic.S5766.severity = warning + +# S5773: Types allowed to be deserialized should be restricted +dotnet_diagnostic.S5773.severity = warning + +# S6354: Use a testable date/time provider. +dotnet_diagnostic.S6354.severity = suggestion + +# S6419: Azure Functions should be stateless +dotnet_diagnostic.S6419.severity = warning + +# S6420: Client instances should not be recreated on each Azure Function invocation +dotnet_diagnostic.S6420.severity = warning + +# S6421: Azure Functions should use Structured Error Handling +dotnet_diagnostic.S6421.severity = warning + +# S6422: Calls to "async" methods should not be blocking in Azure Functions +dotnet_diagnostic.S6422.severity = warning + +# S6423: Azure Functions should log all failures +dotnet_diagnostic.S6423.severity = warning + +# S6424: Interfaces for durable entities should satisfy the restrictions +dotnet_diagnostic.S6424.severity = warning + +# S818: Literal suffixes should be upper case +dotnet_diagnostic.S818.severity = warning + +# S881: Increment (++) and decrement (--) operators should not be used in a method call or mixed with other operators in an expression +dotnet_diagnostic.S881.severity = warning + +# S907: "goto" statement should not be used +dotnet_diagnostic.S907.severity = warning + +# S927: parameter names should match base declaration and other partial definitions +dotnet_diagnostic.S927.severity = warning + +# S9999-cpd: Copy-paste token calculator (NotConfigurable) +#dotnet_diagnostic.S9999-cpd.severity = warning + +# S9999-log: Log generator (NotConfigurable) +#dotnet_diagnostic.S9999-log.severity = warning + +# S9999-metadata: File metadata generator (NotConfigurable) +#dotnet_diagnostic.S9999-metadata.severity = warning + +# S9999-metrics: Metrics calculator (NotConfigurable) +#dotnet_diagnostic.S9999-metrics.severity = warning + +# S9999-symbolRef: Symbol reference calculator (NotConfigurable) +#dotnet_diagnostic.S9999-symbolRef.severity = warning + +# S9999-token-type: Token type calculator (NotConfigurable) +#dotnet_diagnostic.S9999-token-type.severity = warning + +## StyleCop.Analyzers + +# SA0001: XML comment analysis disabled +dotnet_diagnostic.SA0001.severity = warning + +# SA0002: Invalid settings file +dotnet_diagnostic.SA0002.severity = warning + +# SA1000: Keywords should be spaced correctly +dotnet_diagnostic.SA1000.severity = warning + +# SA1001: Commas should be spaced correctly +dotnet_diagnostic.SA1001.severity = warning + +# SA1002: Semicolons should be spaced correctly +dotnet_diagnostic.SA1002.severity = warning + +# SA1003: Symbols should be spaced correctly +dotnet_diagnostic.SA1003.severity = warning + +# SA1004: Documentation lines should begin with single space +dotnet_diagnostic.SA1004.severity = warning + +# SA1005: Single line comments should begin with single space +dotnet_diagnostic.SA1005.severity = warning + +# SA1006: Preprocessor keywords should not be preceded by space +dotnet_diagnostic.SA1006.severity = warning + +# SA1007: Operator keyword should be followed by space +dotnet_diagnostic.SA1007.severity = warning + +# SA1008: Opening parenthesis should be spaced correctly +dotnet_diagnostic.SA1008.severity = warning + +# SA1009: Closing parenthesis should be spaced correctly +dotnet_diagnostic.SA1009.severity = warning + +# SA1010: Opening square brackets should be spaced correctly +dotnet_diagnostic.SA1010.severity = warning + +# SA1011: Closing square brackets should be spaced correctly +dotnet_diagnostic.SA1011.severity = warning + +# SA1012: Opening braces should be spaced correctly +dotnet_diagnostic.SA1012.severity = warning + +# SA1013: Closing braces should be spaced correctly +dotnet_diagnostic.SA1013.severity = warning + +# SA1014: Opening generic brackets should be spaced correctly +dotnet_diagnostic.SA1014.severity = warning + +# SA1015: Closing generic brackets should be spaced correctly +dotnet_diagnostic.SA1015.severity = warning + +# SA1016: Opening attribute brackets should be spaced correctly +dotnet_diagnostic.SA1016.severity = warning + +# SA1017: Closing attribute brackets should be spaced correctly +dotnet_diagnostic.SA1017.severity = warning + +# SA1018: Nullable type symbols should be spaced correctly +dotnet_diagnostic.SA1018.severity = warning + +# SA1019: Member access symbols should be spaced correctly +dotnet_diagnostic.SA1019.severity = warning + +# SA1020: Increment decrement symbols should be spaced correctly +dotnet_diagnostic.SA1020.severity = warning + +# SA1021: Negative signs should be spaced correctly +dotnet_diagnostic.SA1021.severity = warning + +# SA1022: Positive signs should be spaced correctly +dotnet_diagnostic.SA1022.severity = warning + +# SA1023: Dereference and access of symbols should be spaced correctly +dotnet_diagnostic.SA1023.severity = warning + +# SA1024: Colons Should Be Spaced Correctly +dotnet_diagnostic.SA1024.severity = warning + +# SA1025: Code should not contain multiple whitespace in a row +dotnet_diagnostic.SA1025.severity = warning + +# SA1026: Code should not contain space after new or stackalloc keyword in implicitly typed array allocation +dotnet_diagnostic.SA1026.severity = warning + +# SA1027: Use tabs correctly +dotnet_diagnostic.SA1027.severity = warning + +# SA1028: Code should not contain trailing whitespace +dotnet_diagnostic.SA1028.severity = warning + +# SA1100: Do not prefix calls with base unless local implementation exists +dotnet_diagnostic.SA1100.severity = warning + +# SA1101: Prefix local calls with this +dotnet_diagnostic.SA1101.severity = warning + +# SA1102: Query clause should follow previous clause +dotnet_diagnostic.SA1102.severity = warning + +# SA1103: Query clauses should be on separate lines or all on one line +dotnet_diagnostic.SA1103.severity = warning + +# SA1104: Query clause should begin on new line when previous clause spans multiple lines +dotnet_diagnostic.SA1104.severity = warning + +# SA1105: Query clauses spanning multiple lines should begin on own line +dotnet_diagnostic.SA1105.severity = warning + +# SA1106: Code should not contain empty statements +dotnet_diagnostic.SA1106.severity = warning + +# SA1107: Code should not contain multiple statements on one line +dotnet_diagnostic.SA1107.severity = warning + +# SA1108: Block statements should not contain embedded comments +dotnet_diagnostic.SA1108.severity = warning + +# SA1109: Block statements should not contain embedded regions (NotConfigurable) +#dotnet_diagnostic.SA1109.severity = none + +# SA1110: Opening parenthesis or bracket should be on declaration line +dotnet_diagnostic.SA1110.severity = none + +# SA1111: Closing parenthesis should be on line of last parameter +dotnet_diagnostic.SA1111.severity = none + +# SA1112: Closing parenthesis should be on line of opening parenthesis +dotnet_diagnostic.SA1112.severity = warning + +# SA1113: Comma should be on the same line as previous parameter +dotnet_diagnostic.SA1113.severity = warning + +# SA1114: Parameter list should follow declaration +dotnet_diagnostic.SA1114.severity = warning + +# SA1115: Parameter should follow comma +dotnet_diagnostic.SA1115.severity = warning + +# SA1116: Split parameters should start on line after declaration +dotnet_diagnostic.SA1116.severity = warning + +# SA1117: Parameters should be on same line or separate lines +dotnet_diagnostic.SA1117.severity = warning + +# SA1118: Parameter should not span multiple lines +dotnet_diagnostic.SA1118.severity = warning + +# SA1119: Statement should not use unnecessary parenthesis +dotnet_diagnostic.SA1119.severity = warning + +# SA1119_p: Statement should not use unnecessary parenthesis (NotConfigurable) +#dotnet_diagnostic.SA1119_p.severity = silent + +# SA1120: Comments should contain text +dotnet_diagnostic.SA1120.severity = warning + +# SA1121: Use built-in type alias +dotnet_diagnostic.SA1121.severity = warning + +# SA1122: Use string.Empty for empty strings +dotnet_diagnostic.SA1122.severity = warning + +# SA1123: Do not place regions within elements +dotnet_diagnostic.SA1123.severity = warning + +# SA1124: Do not use regions +dotnet_diagnostic.SA1124.severity = warning + +# SA1125: Use shorthand for nullable types +dotnet_diagnostic.SA1125.severity = warning + +# SA1126: Prefix calls correctly (NotConfigurable) +#dotnet_diagnostic.SA1126.severity = none + +# SA1127: Generic type constraints should be on their own line +dotnet_diagnostic.SA1127.severity = warning + +# SA1128: Put constructor initializers on their own line +dotnet_diagnostic.SA1128.severity = none + +# SA1129: Do not use default value type constructor +dotnet_diagnostic.SA1129.severity = warning + +# SA1130: Use lambda syntax +dotnet_diagnostic.SA1130.severity = warning + +# SA1131: Use readable conditions +dotnet_diagnostic.SA1131.severity = warning + +# SA1132: Do not combine fields +dotnet_diagnostic.SA1132.severity = warning + +# SA1133: Do not combine attributes +dotnet_diagnostic.SA1133.severity = warning + +# SA1134: Attributes should not share line +dotnet_diagnostic.SA1134.severity = warning + +# SA1135: Using directives should be qualified +dotnet_diagnostic.SA1135.severity = warning + +# SA1136: Enum values should be on separate lines +dotnet_diagnostic.SA1136.severity = warning + +# SA1137: Elements should have the same indentation +dotnet_diagnostic.SA1137.severity = warning + +# SA1139: Use literal suffix notation instead of casting +dotnet_diagnostic.SA1139.severity = warning + +# SA1141: Use tuple syntax +dotnet_diagnostic.SA1141.severity = warning + +# SA1142: Refer to tuple fields by name +dotnet_diagnostic.SA1142.severity = warning + +# SA1200: Using directives should be placed correctly +dotnet_diagnostic.SA1200.severity = warning + +# SA1201: Elements should appear in the correct order +dotnet_diagnostic.SA1201.severity = warning + +# SA1202: Elements should be ordered by access +dotnet_diagnostic.SA1202.severity = warning + +# SA1203: Constants should appear before fields +dotnet_diagnostic.SA1203.severity = warning + +# SA1204: Static elements should appear before instance elements +dotnet_diagnostic.SA1204.severity = warning + +# SA1205: Partial elements should declare access +dotnet_diagnostic.SA1205.severity = warning + +# SA1206: Declaration keywords should follow order +dotnet_diagnostic.SA1206.severity = warning + +# SA1207: Protected should come before internal +dotnet_diagnostic.SA1207.severity = warning + +# SA1208: System using directives should be placed before other using directives +dotnet_diagnostic.SA1208.severity = warning + +# SA1209: Using alias directives should be placed after other using directives +dotnet_diagnostic.SA1209.severity = warning + +# SA1210: Using directives should be ordered alphabetically by namespace +dotnet_diagnostic.SA1210.severity = warning + +# SA1211: Using alias directives should be ordered alphabetically by alias name +dotnet_diagnostic.SA1211.severity = warning + +# SA1212: Property accessors should follow order +dotnet_diagnostic.SA1212.severity = warning + +# SA1213: Event accessors should follow order +dotnet_diagnostic.SA1213.severity = warning + +# SA1214: Readonly fields should appear before non-readonly fields +dotnet_diagnostic.SA1214.severity = warning + +# SA1216: Using static directives should be placed at the correct location. +dotnet_diagnostic.SA1216.severity = warning + +# SA1217: Using static directives should be ordered alphabetically +dotnet_diagnostic.SA1217.severity = warning + +# SA1300: Element should begin with upper-case letter +dotnet_diagnostic.SA1300.severity = warning + +# SA1301: Element should begin with lower-case letter (NotConfigurable) +#dotnet_diagnostic.SA1301.severity = none + +# SA1302: Interface names should begin with I +dotnet_diagnostic.SA1302.severity = warning + +# SA1303: Const field names should begin with upper-case letter +dotnet_diagnostic.SA1303.severity = warning + +# SA1304: Non-private readonly fields should begin with upper-case letter +dotnet_diagnostic.SA1304.severity = warning + +# SA1305: Field names should not use Hungarian notation +dotnet_diagnostic.SA1305.severity = warning + +# SA1306: Field names should begin with lower-case letter +dotnet_diagnostic.SA1306.severity = warning + +# SA1307: Accessible fields should begin with upper-case letter +dotnet_diagnostic.SA1307.severity = warning + +# SA1308: Variable names should not be prefixed +dotnet_diagnostic.SA1308.severity = warning + +# SA1309: Field names should not begin with underscore +dotnet_diagnostic.SA1309.severity = warning + +# SA1310: Field names should not contain underscore +dotnet_diagnostic.SA1310.severity = warning + +# SA1311: Static readonly fields should begin with upper-case letter +dotnet_diagnostic.SA1311.severity = warning + +# SA1312: Variable names should begin with lower-case letter +dotnet_diagnostic.SA1312.severity = warning + +# SA1313: Parameter names should begin with lower-case letter +dotnet_diagnostic.SA1313.severity = warning + +# SA1314: Type parameter names should begin with T +dotnet_diagnostic.SA1314.severity = warning + +# SA1316: Tuple element names should use correct casing +dotnet_diagnostic.SA1316.severity = warning + +# SA1400: Access modifier should be declared +dotnet_diagnostic.SA1400.severity = warning + +# SA1401: Fields should be private +dotnet_diagnostic.SA1401.severity = warning + +# SA1402: File may only contain a single type +dotnet_diagnostic.SA1402.severity = warning + +# SA1403: File may only contain a single namespace +dotnet_diagnostic.SA1403.severity = warning + +# SA1404: Code analysis suppression should have justification +dotnet_diagnostic.SA1404.severity = warning + +# SA1405: Debug.Assert should provide message text +dotnet_diagnostic.SA1405.severity = warning + +# SA1406: Debug.Fail should provide message text +dotnet_diagnostic.SA1406.severity = warning + +# SA1407: Arithmetic expressions should declare precedence +dotnet_diagnostic.SA1407.severity = warning + +# SA1408: Conditional expressions should declare precedence +dotnet_diagnostic.SA1408.severity = warning + +# SA1409: Remove unnecessary code (NotConfigurable) +#dotnet_diagnostic.SA1409.severity = none + +# SA1410: Remove delegate parenthesis when possible +dotnet_diagnostic.SA1410.severity = none + +# SA1411: Attribute constructor should not use unnecessary parenthesis +dotnet_diagnostic.SA1411.severity = warning + +# SA1412: Store files as UTF-8 with byte order mark +dotnet_diagnostic.SA1412.severity = none + +# SA1413: Use trailing comma in multi-line initializers +dotnet_diagnostic.SA1413.severity = none + +# SA1414: Tuple types in signatures should have element names +dotnet_diagnostic.SA1414.severity = warning + +# SA1500: Braces for multi-line statements should not share line +dotnet_diagnostic.SA1500.severity = warning + +# SA1501: Statement should not be on a single line +dotnet_diagnostic.SA1501.severity = warning + +# SA1502: Element should not be on a single line +dotnet_diagnostic.SA1502.severity = warning + +# SA1503: Braces should not be omitted +dotnet_diagnostic.SA1503.severity = warning + +# SA1504: All accessors should be single-line or multi-line +dotnet_diagnostic.SA1504.severity = warning + +# SA1505: Opening braces should not be followed by blank line +dotnet_diagnostic.SA1505.severity = warning + +# SA1506: Element documentation headers should not be followed by blank line +dotnet_diagnostic.SA1506.severity = warning + +# SA1507: Code should not contain multiple blank lines in a row +dotnet_diagnostic.SA1507.severity = warning + +# SA1508: Closing braces should not be preceded by blank line +dotnet_diagnostic.SA1508.severity = warning + +# SA1509: Opening braces should not be preceded by blank line +dotnet_diagnostic.SA1509.severity = warning + +# SA1510: Chained statement blocks should not be preceded by blank line +dotnet_diagnostic.SA1510.severity = warning + +# SA1511: While-do footer should not be preceded by blank line +dotnet_diagnostic.SA1511.severity = warning + +# SA1512: Single-line comments should not be followed by blank line +dotnet_diagnostic.SA1512.severity = warning + +# SA1513: Closing brace should be followed by blank line +dotnet_diagnostic.SA1513.severity = warning + +# SA1514: Element documentation header should be preceded by blank line +dotnet_diagnostic.SA1514.severity = warning + +# SA1515: Single-line comment should be preceded by blank line +dotnet_diagnostic.SA1515.severity = warning + +# SA1516: Elements should be separated by blank line +dotnet_diagnostic.SA1516.severity = warning + +# SA1517: Code should not contain blank lines at start of file +dotnet_diagnostic.SA1517.severity = warning + +# SA1518: Use line endings correctly at end of file +dotnet_diagnostic.SA1518.severity = warning + +# SA1519: Braces should not be omitted from multi-line child statement +dotnet_diagnostic.SA1519.severity = warning + +# SA1520: Use braces consistently +dotnet_diagnostic.SA1520.severity = warning + +# SA1600: Elements should be documented +dotnet_diagnostic.SA1600.severity = warning + +# SA1601: Partial elements should be documented +dotnet_diagnostic.SA1601.severity = warning + +# SA1602: Enumeration items should be documented +dotnet_diagnostic.SA1602.severity = warning + +# SA1603: Documentation should contain valid XML (NotConfigurable) +#dotnet_diagnostic.SA1603.severity = none + +# SA1604: Element documentation should have summary +dotnet_diagnostic.SA1604.severity = warning + +# SA1605: Partial element documentation should have summary +dotnet_diagnostic.SA1605.severity = warning + +# SA1606: Element documentation should have summary text +dotnet_diagnostic.SA1606.severity = warning + +# SA1607: Partial element documentation should have summary text +dotnet_diagnostic.SA1607.severity = warning + +# SA1608: Element documentation should not have default summary +dotnet_diagnostic.SA1608.severity = warning + +# SA1609: Property documentation should have value +dotnet_diagnostic.SA1609.severity = warning + +# SA1610: Property documentation should have value text +dotnet_diagnostic.SA1610.severity = warning + +# SA1611: Element parameters should be documented +dotnet_diagnostic.SA1611.severity = warning + +# SA1612: Element parameter documentation should match element parameters +dotnet_diagnostic.SA1612.severity = warning + +# SA1613: Element parameter documentation should declare parameter name +dotnet_diagnostic.SA1613.severity = warning + +# SA1614: Element parameter documentation should have text +dotnet_diagnostic.SA1614.severity = warning + +# SA1615: Element return value should be documented +dotnet_diagnostic.SA1615.severity = warning + +# SA1616: Element return value documentation should have text +dotnet_diagnostic.SA1616.severity = warning + +# SA1617: Void return value should not be documented +dotnet_diagnostic.SA1617.severity = warning + +# SA1618: Generic type parameters should be documented +dotnet_diagnostic.SA1618.severity = warning + +# SA1619: Generic type parameters should be documented partial class +dotnet_diagnostic.SA1619.severity = warning + +# SA1620: Generic type parameter documentation should match type parameters +dotnet_diagnostic.SA1620.severity = warning + +# SA1621: Generic type parameter documentation should declare parameter name +dotnet_diagnostic.SA1621.severity = warning + +# SA1622: Generic type parameter documentation should have text +dotnet_diagnostic.SA1622.severity = warning + +# SA1623: Property summary documentation should match accessors +dotnet_diagnostic.SA1623.severity = warning + +# SA1624: Property summary documentation should omit accessor with restricted access +dotnet_diagnostic.SA1624.severity = warning + +# SA1625: Element documentation should not be copied and pasted +dotnet_diagnostic.SA1625.severity = warning + +# SA1626: Single-line comments should not use documentation style slashes +dotnet_diagnostic.SA1626.severity = warning + +# SA1627: Documentation text should not be empty +dotnet_diagnostic.SA1627.severity = warning + +# SA1628: Documentation text should begin with a capital letter (NotConfigurable) +#dotnet_diagnostic.SA1628.severity = none + +# SA1629: Documentation text should end with a period +dotnet_diagnostic.SA1629.severity = warning + +# SA1630: Documentation text should contain whitespace (NotConfigurable) +#dotnet_diagnostic.SA1630.severity = none + +# SA1631: Documentation should meet character percentage (NotConfigurable) +#dotnet_diagnostic.SA1631.severity = none + +# SA1632: Documentation text should meet minimum character length (NotConfigurable) +#dotnet_diagnostic.SA1632.severity = none + +# SA1633: File should have header +dotnet_diagnostic.SA1633.severity = none + +# SA1634: File header should show copyright +dotnet_diagnostic.SA1634.severity = warning + +# SA1635: File header should have copyright text +dotnet_diagnostic.SA1635.severity = warning + +# SA1636: File header copyright text should match +dotnet_diagnostic.SA1636.severity = warning + +# SA1637: File header should contain file name +dotnet_diagnostic.SA1637.severity = warning + +# SA1638: File header file name documentation should match file name +dotnet_diagnostic.SA1638.severity = warning + +# SA1639: File header should have summary +dotnet_diagnostic.SA1639.severity = none + +# SA1640: File header should have valid company text +dotnet_diagnostic.SA1640.severity = warning + +# SA1641: File header company name text should match +dotnet_diagnostic.SA1641.severity = warning + +# SA1642: Constructor summary documentation should begin with standard text +dotnet_diagnostic.SA1642.severity = warning + +# SA1643: Destructor summary documentation should begin with standard text +dotnet_diagnostic.SA1643.severity = warning + +# SA1644: Documentation headers should not contain blank lines (NotConfigurable) +#dotnet_diagnostic.SA1644.severity = none + +# SA1645: Included documentation file does not exist (NotConfigurable) +#dotnet_diagnostic.SA1645.severity = none + +# SA1646: Included documentation XPath does not exist (NotConfigurable) +#dotnet_diagnostic.SA1646.severity = none + +# SA1647: Include node does not contain valid file and path (NotConfigurable) +#dotnet_diagnostic.SA1647.severity = none + +# SA1648: inheritdoc should be used with inheriting class +dotnet_diagnostic.SA1648.severity = warning + +# SA1649: File name should match first type name +dotnet_diagnostic.SA1649.severity = warning + +# SA1650: Element documentation should be spelled correctly (NotConfigurable) +#dotnet_diagnostic.SA1650.severity = none + +# SA1651: Do not use placeholder elements +dotnet_diagnostic.SA1651.severity = warning + +# SX1101: Do not prefix local calls with 'this.' +dotnet_diagnostic.SX1101.severity = none + +# SX1309: Field names should begin with underscore +dotnet_diagnostic.SX1309.severity = none + +# SX1309S: Static field names should begin with underscore +dotnet_diagnostic.SX1309S.severity = none + +## ClrHeapAllocationAnalyzer + +# HAA0101: Array allocation for params parameter +dotnet_diagnostic.HAA0101.severity = suggestion + +# HAA0102: Non-overridden virtual method call on value type +dotnet_diagnostic.HAA0102.severity = suggestion + +# HAA0201: Implicit string concatenation allocation +dotnet_diagnostic.HAA0201.severity = suggestion + +# HAA0202: Value type to reference type conversion allocation for string concatenation +dotnet_diagnostic.HAA0202.severity = suggestion + +# HAA0301: Closure Allocation Source +dotnet_diagnostic.HAA0301.severity = suggestion + +# HAA0302: Display class allocation to capture closure +dotnet_diagnostic.HAA0302.severity = suggestion + +# HAA0303: Lambda or anonymous method in a generic method allocates a delegate instance +dotnet_diagnostic.HAA0303.severity = suggestion + +# HAA0401: Possible allocation of reference type enumerator +dotnet_diagnostic.HAA0401.severity = suggestion + +# HAA0501: Explicit new array type allocation +dotnet_diagnostic.HAA0501.severity = suggestion + +# HAA0502: Explicit new reference type allocation +dotnet_diagnostic.HAA0502.severity = suggestion + +# HAA0503: Explicit new anonymous object allocation +dotnet_diagnostic.HAA0503.severity = suggestion + +# HAA0504: Implicit new array creation allocation +dotnet_diagnostic.HAA0504.severity = suggestion + +# HAA0505: Initializer reference type allocation +dotnet_diagnostic.HAA0505.severity = suggestion + +# HAA0506: Let clause induced allocation +dotnet_diagnostic.HAA0506.severity = suggestion + +# HAA0601: Value type to reference type conversion causing boxing allocation +dotnet_diagnostic.HAA0601.severity = suggestion + +# HAA0602: Delegate on struct instance caused a boxing allocation +dotnet_diagnostic.HAA0602.severity = suggestion + +# HAA0603: Delegate allocation from a method group +dotnet_diagnostic.HAA0603.severity = suggestion + +# HAA0604: Delegate allocation from a method group +dotnet_diagnostic.HAA0604.severity = suggestion + +## xunit.analyzers + +# xUnit1000: Test classes must be public +dotnet_diagnostic.xUnit1000.severity = warning + +# xUnit1001: Fact methods cannot have parameters +dotnet_diagnostic.xUnit1001.severity = warning + +# xUnit1002: Test methods cannot have multiple Fact or Theory attributes +dotnet_diagnostic.xUnit1002.severity = warning + +# xUnit1003: Theory methods must have test data +dotnet_diagnostic.xUnit1003.severity = warning + +# xUnit1004: Test methods should not be skipped +dotnet_diagnostic.xUnit1004.severity = warning + +# xUnit1005: Fact methods should not have test data +dotnet_diagnostic.xUnit1005.severity = warning + +# xUnit1006: Theory methods should have parameters +dotnet_diagnostic.xUnit1006.severity = warning + +# xUnit1007: ClassData must point at a valid class +dotnet_diagnostic.xUnit1007.severity = warning + +# xUnit1008: Test data attribute should only be used on a Theory +dotnet_diagnostic.xUnit1008.severity = warning + +# xUnit1009: InlineData values must match the number of method parameters +dotnet_diagnostic.xUnit1009.severity = warning + +# xUnit1010: The value is not convertible to the method parameter type +dotnet_diagnostic.xUnit1010.severity = warning + +# xUnit1011: There is no matching method parameter +dotnet_diagnostic.xUnit1011.severity = warning + +# xUnit1012: Null should not be used for value type parameters +dotnet_diagnostic.xUnit1012.severity = warning + +# xUnit1013: Public method should be marked as test +dotnet_diagnostic.xUnit1013.severity = warning + +# xUnit1014: MemberData should use nameof operator for member name +dotnet_diagnostic.xUnit1014.severity = warning + +# xUnit1015: MemberData must reference an existing member +dotnet_diagnostic.xUnit1015.severity = warning + +# xUnit1016: MemberData must reference a public member +dotnet_diagnostic.xUnit1016.severity = warning + +# xUnit1017: MemberData must reference a static member +dotnet_diagnostic.xUnit1017.severity = warning + +# xUnit1018: MemberData must reference a valid member kind +dotnet_diagnostic.xUnit1018.severity = warning + +# xUnit1019: MemberData must reference a member providing a valid data type +dotnet_diagnostic.xUnit1019.severity = warning + +# xUnit1020: MemberData must reference a property with a getter +dotnet_diagnostic.xUnit1020.severity = warning + +# xUnit1021: MemberData should not have parameters if the referenced member is not a method +dotnet_diagnostic.xUnit1021.severity = warning + +# xUnit1022: Theory methods cannot have a parameter array +dotnet_diagnostic.xUnit1022.severity = warning + +# xUnit1023: Theory methods cannot have default parameter values +dotnet_diagnostic.xUnit1023.severity = warning + +# xUnit1024: Test methods cannot have overloads +dotnet_diagnostic.xUnit1024.severity = warning + +# xUnit1025: InlineData should be unique within the Theory it belongs to +dotnet_diagnostic.xUnit1025.severity = warning + +# xUnit1026: Theory methods should use all of their parameters +dotnet_diagnostic.xUnit1026.severity = warning + +# xUnit1027: Collection definition classes must be public +dotnet_diagnostic.xUnit1027.severity = error + +# xUnit1033: Test classes decorated with 'Xunit.IClassFixture' or 'Xunit.ICollectionFixture' should add a constructor argument of type TFixture +dotnet_diagnostic.xUnit1033.severity = warning + +# xUnit2000: Constants and literals should be the expected argument +dotnet_diagnostic.xUnit2000.severity = warning + +# xUnit2001: Do not use invalid equality check +dotnet_diagnostic.xUnit2001.severity = warning + +# xUnit2002: Do not use null check on value type +dotnet_diagnostic.xUnit2002.severity = warning + +# xUnit2003: Do not use equality check to test for null value +dotnet_diagnostic.xUnit2003.severity = warning + +# xUnit2004: Do not use equality check to test for boolean conditions +dotnet_diagnostic.xUnit2004.severity = warning + +# xUnit2005: Do not use identity check on value type +dotnet_diagnostic.xUnit2005.severity = warning + +# xUnit2006: Do not use invalid string equality check +dotnet_diagnostic.xUnit2006.severity = warning + +# xUnit2007: Do not use typeof expression to check the type +dotnet_diagnostic.xUnit2007.severity = warning + +# xUnit2008: Do not use boolean check to match on regular expressions +dotnet_diagnostic.xUnit2008.severity = warning + +# xUnit2009: Do not use boolean check to check for substrings +dotnet_diagnostic.xUnit2009.severity = warning + +# xUnit2010: Do not use boolean check to check for string equality +dotnet_diagnostic.xUnit2010.severity = warning + +# xUnit2011: Do not use empty collection check +dotnet_diagnostic.xUnit2011.severity = warning + +# xUnit2012: Do not use Enumerable.Any() to check if a value exists in a collection +dotnet_diagnostic.xUnit2012.severity = warning + +# xUnit2013: Do not use equality check to check for collection size. +dotnet_diagnostic.xUnit2013.severity = warning + +# xUnit2014: Do not use throws check to check for asynchronously thrown exception +dotnet_diagnostic.xUnit2014.severity = warning + +# xUnit2015: Do not use typeof expression to check the exception type +dotnet_diagnostic.xUnit2015.severity = warning + +# xUnit2016: Keep precision in the allowed range when asserting equality of doubles or decimals. +dotnet_diagnostic.xUnit2016.severity = warning + +# xUnit2017: Do not use Contains() to check if a value exists in a collection +dotnet_diagnostic.xUnit2017.severity = warning + +# xUnit2018: Do not compare an object's exact type to an abstract class or interface +dotnet_diagnostic.xUnit2018.severity = warning + +# xUnit2019: Do not use obsolete throws check to check for asynchronously thrown exception +dotnet_diagnostic.xUnit2019.severity = none + +# xUnit3000: Test case classes must derive directly or indirectly from Xunit.LongLivedMarshalByRefObject +dotnet_diagnostic.xUnit3000.severity = warning + +# xUnit3001: Classes that implement Xunit.Abstractions.IXunitSerializable must have a public parameterless constructor +dotnet_diagnostic.xUnit3001.severity = warning + diff --git a/src/AutoColumnizer/AutoColumnizer.cs b/src/AutoColumnizer/AutoColumnizer.cs index 4e327fc7..bed59327 100644 --- a/src/AutoColumnizer/AutoColumnizer.cs +++ b/src/AutoColumnizer/AutoColumnizer.cs @@ -1,66 +1,64 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; +using LogExpert; -namespace LogExpert -{ - public class AutoColumnizer : ILogLineColumnizer - { - #region ILogLineColumnizer implementation +using System; + +namespace AutoColumnizer; - public string Text => GetName(); +public class AutoColumnizer : ILogLineColumnizer +{ + #region ILogLineColumnizer implementation - public bool IsTimeshiftImplemented() - { - return true; - } + public string Text => GetName(); - public string GetName() - { - return "Auto Columnizer"; - } + public bool IsTimeshiftImplemented() + { + return true; + } - public string GetDescription() - { - return "Automatically find the right columnizer for any file"; - } + public string GetName() + { + return "Auto Columnizer"; + } + public string GetDescription() + { + return "Automatically find the right columnizer for any file"; + } - public int GetColumnCount() - { - throw new NotImplementedException(); - } - public string[] GetColumnNames() - { - throw new NotImplementedException(); - } + public int GetColumnCount() + { + throw new NotImplementedException(); + } - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) - { - throw new NotImplementedException(); - } + public string[] GetColumnNames() + { + throw new NotImplementedException(); + } - public void SetTimeOffset(int msecOffset) - { - throw new NotImplementedException(); - } + public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + { + throw new NotImplementedException(); + } - public int GetTimeOffset() - { - throw new NotImplementedException(); - } + public void SetTimeOffset(int msecOffset) + { + throw new NotImplementedException(); + } - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) - { - throw new NotImplementedException(); - } + public int GetTimeOffset() + { + throw new NotImplementedException(); + } - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - } + public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + { + throw new NotImplementedException(); + } - #endregion ILogLineColumnizer implementation + public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { } + + #endregion ILogLineColumnizer implementation } \ No newline at end of file diff --git a/src/AutoColumnizer/AutoColumnizer.csproj b/src/AutoColumnizer/AutoColumnizer.csproj index 1bed4e34..3f5dd983 100644 --- a/src/AutoColumnizer/AutoColumnizer.csproj +++ b/src/AutoColumnizer/AutoColumnizer.csproj @@ -1,33 +1,10 @@  - net8.0-windows - Library - false + net8.0 + AutoColumnizer - true - ..\Solution Items\Key.snk - false - false $(SolutionDir)..\bin\$(Configuration)\plugins - - False - - - True - - - - - Properties\AssemblyVersion.cs - - - - - - Key.snk - - diff --git a/src/AutoColumnizer/Properties/AssemblyInfo.cs b/src/AutoColumnizer/Properties/AssemblyInfo.cs deleted file mode 100644 index 59b88e6a..00000000 --- a/src/AutoColumnizer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("b57259a3-4ed7-4f8b-a252-29e799a56b9e")] \ No newline at end of file diff --git a/src/ColumnizerLib.UnitTests/ColumnTests.cs b/src/ColumnizerLib.UnitTests/ColumnTests.cs index e61e57c5..98830505 100644 --- a/src/ColumnizerLib.UnitTests/ColumnTests.cs +++ b/src/ColumnizerLib.UnitTests/ColumnTests.cs @@ -1,85 +1,72 @@ -using LogExpert; +using LogExpert; + using NUnit.Framework; + using System; using System.Text; -namespace ColumnizerLib.UnitTests +namespace ColumnizerLib.UnitTests; + +[TestFixture] +public class ColumnTests { - [TestFixture] - public class ColumnTests + [Test] + public void Column_LineCutOff () { - [Test] - public void Column_LineCutOf() - { - Column column = new(); - - StringBuilder builder = new(); - - for (int i = 0; i < 4675; i++) - { - builder.Append("6"); - } + var expectedFullValue = new StringBuilder().Append('6', 4675).Append("1234").ToString(); + var expectedDisplayValue = expectedFullValue[..4675] + "..."; // Using substring shorthand - string expected = builder + "..."; - builder.Append("1234"); - - column.FullValue = builder.ToString(); + Column column = new() + { + FullValue = expectedFullValue + }; - Assert.That(column.DisplayValue, Is.EqualTo(expected)); - Assert.That(column.FullValue, Is.EqualTo(builder.ToString())); - } + Assert.That(column.DisplayValue, Is.EqualTo(expectedDisplayValue)); + Assert.That(column.FullValue, Is.EqualTo(expectedFullValue)); + } - [Test] - public void Column_NoLineCutOf() + [Test] + public void Column_NoLineCutOff () + { + var expected = new StringBuilder().Append('6', 4675).ToString(); + Column column = new() { - Column column = new(); - - StringBuilder builder = new(); + FullValue = expected + }; - for (int i = 0; i < 4675; i++) - { - builder.Append("6"); - } + Assert.That(column.DisplayValue, Is.EqualTo(column.FullValue)); + } - string expected = builder.ToString(); + [Test] + public void Column_NullCharReplacement() + { + Column column = new(); - column.FullValue = expected; + column.FullValue = "asdf\0"; - Assert.That(column.DisplayValue, Is.EqualTo(expected)); - Assert.That(column.FullValue, Is.EqualTo(expected)); + //Switch between the different implementation for the windows versions + //Not that great solution but currently I'm out of ideas, I know that currently + //only one implementation depending on the windows version is executed + if (Environment.Version >= Version.Parse("6.2")) + { + Assert.That(column.DisplayValue, Is.EqualTo("asdf␀")); } - - [Test] - public void Column_NullCharReplacement() + else { - Column column = new(); - - column.FullValue = "asdf\0"; - - //Switch between the different implementation for the windows versions - //Not that great solution but currently I'm out of ideas, I know that currently - //only one implementation depending on the windows version is executed - if (Environment.Version >= Version.Parse("6.2")) - { - Assert.That(column.DisplayValue, Is.EqualTo("asdf␀")); - } - else - { - Assert.That(column.DisplayValue, Is.EqualTo("asdf ")); - } - - Assert.That(column.FullValue, Is.EqualTo("asdf\0")); + Assert.That(column.DisplayValue, Is.EqualTo("asdf ")); } - [Test] - public void Column_TabReplacement() - { - Column column = new(); + Assert.That(column.FullValue, Is.EqualTo("asdf\0")); + } - column.FullValue = "asdf\t"; + [Test] + public void Column_TabReplacement() + { + Column column = new(); - Assert.That(column.DisplayValue, Is.EqualTo("asdf ")); - Assert.That(column.FullValue, Is.EqualTo("asdf\t")); - } + column.FullValue = "asdf\t"; + + Assert.That(column.DisplayValue, Is.EqualTo("asdf ")); + Assert.That(column.FullValue, Is.EqualTo("asdf\t")); } } \ No newline at end of file diff --git a/src/ColumnizerLib.UnitTests/ColumnizerLib.UnitTests.csproj b/src/ColumnizerLib.UnitTests/ColumnizerLib.UnitTests.csproj index 68ad9cfc..af5aa1ac 100644 --- a/src/ColumnizerLib.UnitTests/ColumnizerLib.UnitTests.csproj +++ b/src/ColumnizerLib.UnitTests/ColumnizerLib.UnitTests.csproj @@ -1,16 +1,10 @@  - net8.0-windows - Library + net8.0 + true - false ColumnizerLib.UnitTests Microsoft - ColumnizerLib.UnitTests - Copyright © Microsoft 2018 - 1.0.0.0 - 1.0.0.0 - false bin\$(Configuration) diff --git a/src/ColumnizerLib.UnitTests/Extensions/LogLineExtensionsTests.cs b/src/ColumnizerLib.UnitTests/Extensions/LogLineExtensionsTests.cs index a412642c..c6746b62 100644 --- a/src/ColumnizerLib.UnitTests/Extensions/LogLineExtensionsTests.cs +++ b/src/ColumnizerLib.UnitTests/Extensions/LogLineExtensionsTests.cs @@ -1,31 +1,32 @@ using LogExpert; +using LogExpert.Extensions; + using NUnit.Framework; -namespace ColumnizerLib.UnitTests.Extensions -{ - [TestFixture] +namespace ColumnizerLib.UnitTests.Extensions; - internal class LogLineExtensionsTests +[TestFixture] + +internal class LogLineExtensionsTests +{ + private class TestingLogLine : ILogLine { - private class TestingLogLine : ILogLine - { - public string FullLine { get; set; } + public string FullLine { get; set; } - public int LineNumber { get; set; } + public int LineNumber { get; set; } - public string Text { get; set; } - } + public string Text { get; set; } + } - [Test] - public void ToClipBoardText_ReturnsExpected() + [Test] + public void ToClipBoardText_ReturnsExpected() + { + var underTest = new TestingLogLine { - var underTest = new TestingLogLine - { - FullLine = "a fullLine", - LineNumber = 89, - Text = "a text" - }; - Assert.That(underTest.ToClipBoardText(), Is.EqualTo("\t90\ta fullLine")); - } + FullLine = "a fullLine", + LineNumber = 89, + Text = "a text" + }; + Assert.That(underTest.ToClipBoardText(), Is.EqualTo("\t90\ta fullLine")); } } diff --git a/src/ColumnizerLib.UnitTests/Properties/AssemblyInfo.cs b/src/ColumnizerLib.UnitTests/Properties/AssemblyInfo.cs deleted file mode 100644 index 5496df04..00000000 --- a/src/ColumnizerLib.UnitTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("0dbbcbef-4a91-4031-aeab-b7eee802f496")] diff --git a/src/ColumnizerLib/Column.cs b/src/ColumnizerLib/Column.cs index ff5bf308..87bfdd69 100644 --- a/src/ColumnizerLib/Column.cs +++ b/src/ColumnizerLib/Column.cs @@ -1,117 +1,104 @@ -using System; +using System; using System.Collections.Generic; -namespace LogExpert +namespace LogExpert; + +public class Column : IColumn { - public class Column : IColumn - { - #region Fields + #region Fields - private static readonly int _maxLength = 4678 - 3; - private static readonly string _replacement = "..."; + private const int MAXLENGTH = 4678 - 3; + private const string REPLACEMENT = "..."; - private static readonly IEnumerable> _replacements; + private static readonly List> _replacements = [ + //replace tab with 3 spaces, from old coding. Needed??? + input => input.Replace("\t", " ", StringComparison.Ordinal), - private string _fullValue; + //shorten string if it exceeds maxLength + input => input.Length > MAXLENGTH + ? string.Concat(input.AsSpan(0, MAXLENGTH), REPLACEMENT) + : input + ]; - #endregion + private string _fullValue; - #region cTor + #endregion - static Column() - { - List> replacements = new List>( - new Func[] - { - //replace tab with 3 spaces, from old coding. Needed??? - input => input.Replace("\t", " "), - - //shorten string if it exceeds maxLength - input => - { - if (input.Length > _maxLength) - { - return input.Substring(0, _maxLength) + _replacement; - } - - return input; - } - }); - - if (Environment.Version >= Version.Parse("6.2")) - { - //Win8 or newer support full UTF8 chars with the preinstalled fonts. - //Replace null char with UTF8 Symbol U+2400 (␀) - replacements.Add(input => input.Replace("\0", "␀")); - } - else - { - //Everything below Win8 the installed fonts seems to not to support reliabel - //Replace null char with space - replacements.Add(input => input.Replace("\0", " ")); - } + #region cTor - _replacements = replacements; - - EmptyColumn = new Column {FullValue = string.Empty}; + static Column () + { + if (Environment.Version >= Version.Parse("6.2")) + { + //Win8 or newer support full UTF8 chars with the preinstalled fonts. + //Replace null char with UTF8 Symbol U+2400 (␀) + _replacements.Add(input => input.Replace("\0", "␀", StringComparison.Ordinal)); + } + else + { + //Everything below Win8 the installed fonts seems to not to support reliabel + //Replace null char with space + _replacements.Add(input => input.Replace("\0", " ", StringComparison.Ordinal)); } - #endregion + EmptyColumn = new Column { FullValue = string.Empty }; + } - #region Properties + #endregion - public static IColumn EmptyColumn { get; } + #region Properties - public IColumnizedLogLine Parent { get; set; } + public static IColumn EmptyColumn { get; } - public string FullValue - { - get => _fullValue; - set - { - _fullValue = value; + public IColumnizedLogLine Parent { get; set; } - string temp = FullValue; + public string FullValue + { + get => _fullValue; + set + { + _fullValue = value; - foreach (var replacement in _replacements) - { - temp = replacement(temp); - } + var temp = FullValue; - DisplayValue = temp; + foreach (var replacement in _replacements) + { + temp = replacement(temp); } - } - public string DisplayValue { get; private set; } + DisplayValue = temp; + } + } - string ITextValue.Text => DisplayValue; + public string DisplayValue { get; private set; } - #endregion + public string Text => DisplayValue; - #region Public methods + #endregion - public static Column[] CreateColumns(int count, IColumnizedLogLine parent) - { - return CreateColumns(count, parent, string.Empty); - } + #region Public methods - public static Column[] CreateColumns(int count, IColumnizedLogLine parent, string defaultValue) - { - Column[] output = new Column[count]; - - for (int i = 0; i < count; i++) - { - output[i] = new Column {FullValue = defaultValue, Parent = parent}; - } + public static Column[] CreateColumns (int count, IColumnizedLogLine parent) + { + return CreateColumns(count, parent, string.Empty); + } - return output; - } + public static Column[] CreateColumns (int count, IColumnizedLogLine parent, string defaultValue) + { + var output = new Column[count]; - public override string ToString() + for (var i = 0; i < count; i++) { - return DisplayValue ?? string.Empty; + output[i] = new Column { FullValue = defaultValue, Parent = parent }; } - #endregion + return output; } + + public override string ToString () + { + return DisplayValue ?? string.Empty; + } + + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ColumnizedLogLine.cs b/src/ColumnizerLib/ColumnizedLogLine.cs index 41a14e6f..47891d74 100644 --- a/src/ColumnizerLib/ColumnizedLogLine.cs +++ b/src/ColumnizerLib/ColumnizedLogLine.cs @@ -1,13 +1,12 @@ -namespace LogExpert +namespace LogExpert; + +public class ColumnizedLogLine : IColumnizedLogLine { - public class ColumnizedLogLine : IColumnizedLogLine - { - #region Properties + #region Properties - public ILogLine LogLine { get; set; } + public ILogLine LogLine { get; set; } - public IColumn[] ColumnValues { get; set; } + public IColumn[] ColumnValues { get; set; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ColumnizerLib.csproj b/src/ColumnizerLib/ColumnizerLib.csproj index ec4cc262..960aa76e 100644 --- a/src/ColumnizerLib/ColumnizerLib.csproj +++ b/src/ColumnizerLib/ColumnizerLib.csproj @@ -1,36 +1,9 @@  + net8.0 - Library - Properties - LogExpert - false + $(SolutionDir)..\bin\Docs\ColumnizerLib.xml - false - false - $(SolutionDir)..\bin\$(Configuration) - CS1591; - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - - - - Key.snk - - + diff --git a/src/ColumnizerLib/ColumnizerLib.nuspec b/src/ColumnizerLib/ColumnizerLib.nuspec index 043d6dcf..0a242fbf 100644 --- a/src/ColumnizerLib/ColumnizerLib.nuspec +++ b/src/ColumnizerLib/ColumnizerLib.nuspec @@ -4,14 +4,15 @@ LogExpert.ColumnizerLib $version$ LogExpert ColumnizerLib - Zarunbal Previous:Hagen Raab - Zarunbal - MIT - https://github.com/zarunbal/LogExpert + Zarunbal, Hagen Raab, Hirogen, RandallFlagg and others + Zarunbal, Hirogen + MIT + https://github.com/LogExperts/LogExpert false + https://github.com/LogExperts/LogExpert/issues + https://github.com/LogExperts/LogExpert/releases/tag/v$version$ Columnizer Lib for Logexpert plugins - See https://github.com/zarunbal/LogExpert/releases/tag/v$version$ - Copyright 2019 + Copyright 2025 LogExpert Columnizer \ No newline at end of file diff --git a/src/ColumnizerLib/Extensions/LogLineExtensions.cs b/src/ColumnizerLib/Extensions/LogLineExtensions.cs index 01400ea4..2cebb987 100644 --- a/src/ColumnizerLib/Extensions/LogLineExtensions.cs +++ b/src/ColumnizerLib/Extensions/LogLineExtensions.cs @@ -1,10 +1,11 @@ -namespace LogExpert +namespace LogExpert.Extensions; + +//TODO: Move this to LogExpert.UI, change to internal and fix tests +public static class LogLineExtensions { - public static class LogLineExtensions + //TOOD: check if the callers are checking for null before calling + public static string ToClipBoardText (this ILogLine logLine) { - public static string ToClipBoardText(this ILogLine logLine) - { - return "\t" + (logLine.LineNumber + 1).ToString() + "\t" + logLine.FullLine; - } + return logLine == null ? string.Empty : $"\t{logLine.LineNumber + 1}\t{logLine.FullLine}"; } } \ No newline at end of file diff --git a/src/ColumnizerLib/IAutoLogLineColumnizerCallback.cs b/src/ColumnizerLib/IAutoLogLineColumnizerCallback.cs index 8889c8f9..7206b8c9 100644 --- a/src/ColumnizerLib/IAutoLogLineColumnizerCallback.cs +++ b/src/ColumnizerLib/IAutoLogLineColumnizerCallback.cs @@ -1,12 +1,11 @@ -namespace LogExpert +namespace LogExpert; + +public interface IAutoLogLineColumnizerCallback { - public interface IAutoLogLineColumnizerCallback - { - /// - /// Returns the log line with the given index (zero-based). - /// - /// Number of the line to be retrieved - /// A string with line content or null if line number is out of range - ILogLine GetLogLine(int lineNum); - } + /// + /// Returns the log line with the given index (zero-based). + /// + /// Number of the line to be retrieved + /// A string with line content or null if line number is out of range + ILogLine GetLogLine (int lineNum); } \ No newline at end of file diff --git a/src/ColumnizerLib/IColumn.cs b/src/ColumnizerLib/IColumn.cs index d9abc0ab..57ba40bd 100644 --- a/src/ColumnizerLib/IColumn.cs +++ b/src/ColumnizerLib/IColumn.cs @@ -3,18 +3,17 @@ using System.Linq; using System.Text; -namespace LogExpert +namespace LogExpert; + +public interface IColumn : ITextValue { - public interface IColumn : ITextValue - { - #region Properties + #region Properties - IColumnizedLogLine Parent { get; } + IColumnizedLogLine Parent { get; } - string FullValue { get; } + string FullValue { get; } - string DisplayValue { get; } + string DisplayValue { get; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IColumnizedLogLine.cs b/src/ColumnizerLib/IColumnizedLogLine.cs index 491c78f3..dad1ee46 100644 --- a/src/ColumnizerLib/IColumnizedLogLine.cs +++ b/src/ColumnizerLib/IColumnizedLogLine.cs @@ -3,17 +3,16 @@ using System.Linq; using System.Text; -namespace LogExpert +namespace LogExpert; + +public interface IColumnizedLogLine { - public interface IColumnizedLogLine - { - #region Properties + #region Properties - ILogLine LogLine { get; } + ILogLine LogLine { get; } - IColumn[] ColumnValues { get; } + IColumn[] ColumnValues { get; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IColumnizerConfigurator.cs b/src/ColumnizerLib/IColumnizerConfigurator.cs index a9a953e2..a9249d06 100644 --- a/src/ColumnizerLib/IColumnizerConfigurator.cs +++ b/src/ColumnizerLib/IColumnizerConfigurator.cs @@ -1,46 +1,45 @@  -namespace LogExpert +namespace LogExpert; + +/// +/// A Columnizer can implement this interface if it has to show an own settings dialog to the user. +/// The Config button in LogExpert's columnizer dialog is enabled if a Columnizer implements this interface. +/// If you don't need a config dialog you don't have to implement this interface. +/// +public interface IColumnizerConfigurator { + #region Public methods + /// - /// A Columnizer can implement this interface if it has to show an own settings dialog to the user. - /// The Config button in LogExpert's columnizer dialog is enabled if a Columnizer implements this interface. - /// If you don't need a config dialog you don't have to implement this interface. + /// This function is called if the user presses the Config button on the Columnizer dialog. + /// Its up to the Columnizer plugin to show an own configuration dialog and store all + /// required settings. /// - public interface IColumnizerConfigurator - { - #region Public methods - - /// - /// This function is called if the user presses the Config button on the Columnizer dialog. - /// Its up to the Columnizer plugin to show an own configuration dialog and store all - /// required settings. - /// - /// Callback interface with functions which can be used by the columnizer - /// The complete path to the directory where LogExpert stores its settings. - /// You can use this directory, if you want to. Please don't use the file name "settings.dat", because this - /// name is used by LogExpert. - /// - /// - /// This is the place to show a configuration dialog to the user. You have to handle all dialog stuff by yourself. - /// It's also your own job to store the configuration in a config file or on the registry. - /// The callback is passed to this function just in case you need the file name of the current log file - /// or the line count etc. You can also use it to store different settings for every log file. - /// You can use the callback to distinguish between different files. Its passed to all important - /// functions in the Columnizer. - /// - void Configure(ILogLineColumnizerCallback callback, string configDir); + /// Callback interface with functions which can be used by the columnizer + /// The complete path to the directory where LogExpert stores its settings. + /// You can use this directory, if you want to. Please don't use the file name "settings.dat", because this + /// name is used by LogExpert. + /// + /// + /// This is the place to show a configuration dialog to the user. You have to handle all dialog stuff by yourself. + /// It's also your own job to store the configuration in a config file or on the registry. + /// The callback is passed to this function just in case you need the file name of the current log file + /// or the line count etc. You can also use it to store different settings for every log file. + /// You can use the callback to distinguish between different files. Its passed to all important + /// functions in the Columnizer. + /// + void Configure(ILogLineColumnizerCallback callback, string configDir); - /// - /// This function will be called right after LogExpert has loaded your Columnizer class. Use this - /// to load the configuration which was saved in the Configure() function. - /// You have to hold the loaded config data in your Columnizer object. - /// - /// The complete path to the directory where LogExpert stores its settings. - /// You can use this directory, if you want to. Please don't use the file name "settings.dat", because this - /// name is used by LogExpert. - /// - void LoadConfig(string configDir); + /// + /// This function will be called right after LogExpert has loaded your Columnizer class. Use this + /// to load the configuration which was saved in the Configure() function. + /// You have to hold the loaded config data in your Columnizer object. + /// + /// The complete path to the directory where LogExpert stores its settings. + /// You can use this directory, if you want to. Please don't use the file name "settings.dat", because this + /// name is used by LogExpert. + /// + void LoadConfig(string configDir); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IColumnizerPriority.cs b/src/ColumnizerLib/IColumnizerPriority.cs index 5cf85770..2ee01840 100644 --- a/src/ColumnizerLib/IColumnizerPriority.cs +++ b/src/ColumnizerLib/IColumnizerPriority.cs @@ -3,16 +3,15 @@ using System.Linq; using System.Text; -namespace LogExpert +namespace LogExpert; + +public interface IColumnizerPriority { - public interface IColumnizerPriority - { - /// - /// Get the priority for this columnizer so the up layer can decide which columnizer is the best fitted one. - /// - /// - /// - /// - Priority GetPriority(string fileName, IEnumerable samples); - } + /// + /// Get the priority for this columnizer so the up layer can decide which columnizer is the best fitted one. + /// + /// + /// + /// + Priority GetPriority(string fileName, IEnumerable samples); } \ No newline at end of file diff --git a/src/ColumnizerLib/IContextMenuEntry.cs b/src/ColumnizerLib/IContextMenuEntry.cs index 80fd9443..bc59df1e 100644 --- a/src/ColumnizerLib/IContextMenuEntry.cs +++ b/src/ColumnizerLib/IContextMenuEntry.cs @@ -1,54 +1,57 @@ using System.Collections.Generic; -namespace LogExpert +namespace LogExpert; + +/// +/// Implement this interface to add a menu entry to the context menu of LogExpert. +/// +/// +/// +/// The methods in this interface will be called in the GUI thread. So make sure that there's no +/// heavyweight work to do in your implementations. +/// +/// +public interface IContextMenuEntry { + #region Public methods + /// - /// Implement this interface to add a menu entry to the context menu of LogExpert. + /// This function is called from LogExpert if the context menu is about to be displayed. + /// Your implementation can control whether LogExpert will show a menu entry by returning + /// an appropriate value.

///
- /// - /// - /// The methods in this interface will be called in the GUI thread. So make sure that there's no - /// heavyweight work to do in your implementations. - /// - /// - public interface IContextMenuEntry - { - #region Public methods - - /// - /// This function is called from LogExpert if the context menu is about to be displayed. - /// Your implementation can control whether LogExpert will show a menu entry by returning - /// an appropriate value.

- ///
- /// A list containing all selected line numbers. - /// The currently selected Columnizer. You can use it to split log lines, - /// if necessary. - /// The callback interface implemented by LogExpert. You can use the functions - /// for retrieving log lines or pass it along to functions of the Columnizer if needed. - /// - /// Return the string which should be displayed in the context menu.

- /// You can control the menu behaviour by returning the the following values:

- ///
    - ///
  • Normal string: The string is displayed as a menu entry
  • - ///
  • String starting with underscore: The string is displayed as a disabled menu entry
  • - ///
  • null: No menu entry is displayed.
  • - ///
- ///
- string GetMenuText(IList lines, ILogLineColumnizer columnizer, ILogExpertCallback callback); - - - /// - /// This function is called from LogExpert if the menu entry is choosen by the user.

- /// Note that this function is called from the GUI thread. So try to avoid time consuming operations. - ///
- /// A list containing all selected line numbers. - /// The currently selected Columnizer. You can use it to split log lines, - /// if necessary. - /// The callback interface implemented by LogExpert. You can use the functions - /// for retrieving log lines or pass it along to functions of the Columnizer if needed. - void MenuSelected(IList lines, ILogLineColumnizer columnizer, ILogExpertCallback callback); - - #endregion - } + /// A list containing all selected line numbers. + /// The currently selected Columnizer. You can use it to split log lines, + /// if necessary. + /// The callback interface implemented by LogExpert. You can use the functions + /// for retrieving log lines or pass it along to functions of the Columnizer if needed. + /// + /// Return the string which should be displayed in the context menu.

+ /// You can control the menu behaviour by returning the the following values:

+ ///
    + ///
  • Normal string: The string is displayed as a menu entry
  • + ///
  • String starting with underscore: The string is displayed as a disabled menu entry
  • + ///
  • null: No menu entry is displayed.
  • + ///
+ ///
+ string GetMenuText(IList lines, ILogLineColumnizer columnizer, ILogExpertCallback callback); + + string GetMenuText(int linesCount, ILogLineColumnizer columnizer, ILogLine line); + + + /// + /// This function is called from LogExpert if the menu entry is choosen by the user.

+ /// Note that this function is called from the GUI thread. So try to avoid time consuming operations. + ///
+ /// A list containing all selected line numbers. + /// The currently selected Columnizer. You can use it to split log lines, + /// if necessary. + /// The callback interface implemented by LogExpert. You can use the functions + /// for retrieving log lines or pass it along to functions of the Columnizer if needed. + void MenuSelected(IList lines, ILogLineColumnizer columnizer, ILogExpertCallback callback); + + void MenuSelected(int linesCount, ILogLineColumnizer columnizer, ILogLine line); + + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IFileSystemCallback.cs b/src/ColumnizerLib/IFileSystemCallback.cs index bac789b7..faac1728 100644 --- a/src/ColumnizerLib/IFileSystemCallback.cs +++ b/src/ColumnizerLib/IFileSystemCallback.cs @@ -2,21 +2,20 @@ using System.Collections.Generic; using System.Text; -namespace LogExpert +namespace LogExpert; + +/// +/// Service interface implemented by LogExpert. This can be used by IFileSystemPlugin implementations to get certain services. +/// +public interface IFileSystemCallback { + #region Public methods + /// - /// Service interface implemented by LogExpert. This can be used by IFileSystemPlugin implementations to get certain services. + /// Retrieve a logger. The plugin can use the logger to write log messages into LogExpert's log file. /// - public interface IFileSystemCallback - { - #region Public methods - - /// - /// Retrieve a logger. The plugin can use the logger to write log messages into LogExpert's log file. - /// - /// - ILogExpertLogger GetLogger(); + /// + ILogExpertLogger GetLogger(); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IFileSystemPlugin.cs b/src/ColumnizerLib/IFileSystemPlugin.cs index 25c41361..8e86be48 100644 --- a/src/ColumnizerLib/IFileSystemPlugin.cs +++ b/src/ColumnizerLib/IFileSystemPlugin.cs @@ -1,50 +1,45 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace LogExpert +namespace LogExpert; + +/// +/// Interface for file system plugins. A file system plugin is responsible for feeding file data to LogExpert. +/// +/// +/// LogExperts file handling is done via file system plugins. The selection if the appropriate plugin for a file is based +/// on URI schemes. If a file system plugin returns true to the method, it will be selected +/// to handle a file. +/// +public interface IFileSystemPlugin { + #region Properties + + /// + /// Name of the plugin. Will be used in the Settings dialog. + /// + string Text { get; } + + /// + /// Short description. Currently unused, but maybe used later for displaying a short info about the plugin. + /// + string Description { get; } + + #endregion + + #region Public methods + /// - /// Interface for file system plugins. A file system plugin is responsible for feeding file data to LogExpert. + /// Called from LogExpert to determine a file system plugin for a given URI. /// - /// - /// LogExperts file handling is done via file system plugins. The selection if the appropriate plugin for a file is based - /// on URI schemes. If a file system plugin returns true to the method, it will be selected - /// to handle a file. - /// - public interface IFileSystemPlugin - { - #region Properties - - /// - /// Name of the plugin. Will be used in the Settings dialog. - /// - string Text { get; } - - /// - /// Short description. Currently unused, but maybe used later for displaying a short info about the plugin. - /// - string Description { get; } - - #endregion - - #region Public methods - - /// - /// Called from LogExpert to determine a file system plugin for a given URI. - /// - /// The URI of the file to be loaded. - /// Return true if the file system plugin can handle the URI. - bool CanHandleUri(string uriString); - - /// - /// Return a file system specific implementation of here. - /// The method is called from LogExpert when a file is about to be opened. It's called after was called. - /// - /// - /// - ILogFileInfo GetLogfileInfo(string uriString); - - #endregion - } + /// The URI of the file to be loaded. + /// Return true if the file system plugin can handle the URI. + bool CanHandleUri(string uriString); + + /// + /// Return a file system specific implementation of here. + /// The method is called from LogExpert when a file is about to be opened. It's called after was called. + /// + /// + /// + ILogFileInfo GetLogfileInfo(string uriString); + + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IInitColumnizer.cs b/src/ColumnizerLib/IInitColumnizer.cs index 6c90ae49..586f9af5 100644 --- a/src/ColumnizerLib/IInitColumnizer.cs +++ b/src/ColumnizerLib/IInitColumnizer.cs @@ -2,41 +2,40 @@ using System.Collections.Generic; using System.Text; -namespace LogExpert +namespace LogExpert; + +/// +/// Implement this interface in your columnizer if you need to do some initialization work +/// every time the columnizer is selected. +/// +/// +/// +/// The methods in this interface will be called in the GUI thread. So make sure that there's no +/// heavyweight work to do in your implementations. +/// +/// If a file is reloaded, the current Columnizer is set again. That means that the methods of this +/// interface will be called again. Generally you should do no assumptions about how often the +/// methods will be called. The file is already loaded when the columnizer is set. So +/// you can use the methods in the given callbacks to get informations about the file or to +/// retrieve specific lines. +/// +/// +public interface IInitColumnizer { + #region Public methods + /// - /// Implement this interface in your columnizer if you need to do some initialization work - /// every time the columnizer is selected. + /// This method is called when the Columnizer is selected as the current columnizer. /// - /// - /// - /// The methods in this interface will be called in the GUI thread. So make sure that there's no - /// heavyweight work to do in your implementations. - /// - /// If a file is reloaded, the current Columnizer is set again. That means that the methods of this - /// interface will be called again. Generally you should do no assumptions about how often the - /// methods will be called. The file is already loaded when the columnizer is set. So - /// you can use the methods in the given callbacks to get informations about the file or to - /// retrieve specific lines. - /// - /// - public interface IInitColumnizer - { - #region Public methods - - /// - /// This method is called when the Columnizer is selected as the current columnizer. - /// - /// Callback that can be used to retrieve some informations, if needed. - void Selected(ILogLineColumnizerCallback callback); + /// Callback that can be used to retrieve some informations, if needed. + void Selected(ILogLineColumnizerCallback callback); - /// - /// This method is called when the Columnizer is de-selected (i.e. when another Columnizer is - /// selected). - /// - /// Callback that can be used to retrieve some informations, if needed. - void DeSelected(ILogLineColumnizerCallback callback); + /// + /// This method is called when the Columnizer is de-selected (i.e. when another Columnizer is + /// selected). + /// + /// Callback that can be used to retrieve some informations, if needed. + void DeSelected(ILogLineColumnizerCallback callback); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IKeywordAction.cs b/src/ColumnizerLib/IKeywordAction.cs index 1329f36d..04d6259d 100644 --- a/src/ColumnizerLib/IKeywordAction.cs +++ b/src/ColumnizerLib/IKeywordAction.cs @@ -2,50 +2,49 @@ using System.Collections.Generic; using System.Text; -namespace LogExpert +namespace LogExpert; + +/// +/// Implement this interface to execute a self defined action when LogExpert detects a +/// keyword on incomig log file content. +/// These kind of plugins can be used in the "Highlight and Action Triggers" dialog. +/// +public interface IKeywordAction { + #region Public methods + /// - /// Implement this interface to execute a self defined action when LogExpert detects a - /// keyword on incomig log file content. - /// These kind of plugins can be used in the "Highlight and Action Triggers" dialog. + /// Is called when LogExpert detects a keyword match which is configured for this plugin. + /// The keywords are configured in the Highlight dialog. + /// You have to implement this method to execute your desired actions. /// - public interface IKeywordAction - { - #region Public methods + /// The keyword which triggered the call. + /// The parameter configured for the plugin launch (in the Highlight dialog). + /// A callback which can be used by the plugin. + /// The current columnizer. Can be used to obtain timestamps + /// (if supported by Columnizer) or to split the log line into fields. + /// + /// This method is called in a background thread from the process' thread pool (using BeginInvoke()). + /// So you cannot rely on state information retrieved by the given callback. E.g. the line count + /// may change during the execution of the method. The only exception from this rule is the current line number + /// retrieved from the callback. This is of course the line number of the line that has triggered + /// the keyword match. + /// + void Execute(string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer); - /// - /// Is called when LogExpert detects a keyword match which is configured for this plugin. - /// The keywords are configured in the Highlight dialog. - /// You have to implement this method to execute your desired actions. - /// - /// The keyword which triggered the call. - /// The parameter configured for the plugin launch (in the Highlight dialog). - /// A callback which can be used by the plugin. - /// The current columnizer. Can be used to obtain timestamps - /// (if supported by Columnizer) or to split the log line into fields. - /// - /// This method is called in a background thread from the process' thread pool (using BeginInvoke()). - /// So you cannot rely on state information retrieved by the given callback. E.g. the line count - /// may change during the execution of the method. The only exception from this rule is the current line number - /// retrieved from the callback. This is of course the line number of the line that has triggered - /// the keyword match. - /// - void Execute(string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer); - - /// - /// Return the name of your plugin here. The returned name is used for displaying the plugin list - /// in the settings. - /// - /// The name of the plugin. - string GetName(); + /// + /// Return the name of your plugin here. The returned name is used for displaying the plugin list + /// in the settings. + /// + /// The name of the plugin. + string GetName(); - /// - /// Return a description of your plugin here. E.g. a short explanation of parameters. The descriptions - /// will be displayed in the plugin chooser dialog which is used by the Highlight settings. - /// - /// The description of the plugin. - string GetDescription(); + /// + /// Return a description of your plugin here. E.g. a short explanation of parameters. The descriptions + /// will be displayed in the plugin chooser dialog which is used by the Highlight settings. + /// + /// The description of the plugin. + string GetDescription(); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogExpertCallback.cs b/src/ColumnizerLib/ILogExpertCallback.cs index aae48283..d1ddca26 100644 --- a/src/ColumnizerLib/ILogExpertCallback.cs +++ b/src/ColumnizerLib/ILogExpertCallback.cs @@ -1,68 +1,65 @@ using System.Collections.Generic; -namespace LogExpert +namespace LogExpert; + +/// +/// This callback interface is implemented by LogExpert. You can use it e.g. when implementing a +/// context menu plugin. +/// +public interface ILogExpertCallback : ILogLineColumnizerCallback { + #region Public methods + /// - /// This callback interface is implemented by LogExpert. You can use it e.g. when implementing a - /// context menu plugin. + /// Call this function to add a new temporary file tab to LogExpert. This may be usefull + /// if your plugin creates some output into a file which has to be shown in LogExpert. /// - public interface ILogExpertCallback : ILogLineColumnizerCallback - { - #region Public methods - - /// - /// Call this function to add a new temporary file tab to LogExpert. This may be usefull - /// if your plugin creates some output into a file which has to be shown in LogExpert. - /// - /// Path of the file to be loaded. - /// Title shown on the tab. - /// - /// The file tab is internally handled like the temp file tabs which LogExpert uses for - /// FilterTabs or clipboard copy tabs. - /// This has some implications: - ///
    - ///
  • The file path is not shown. Only the title is shown.
  • - ///
  • The encoding of the file is expected to be 2-byte Unicode!
  • - ///
  • The file will not be added to the history of opened files.
  • - ///
  • The file will be deleted when closing the tab!
  • - ///
- ///
- void AddTempFileTab(string fileName, string title); - - - /// - /// With this function you can create a new tab and add a bunch of text lines to it. - /// - /// A list with LineEntry items containing text and an - /// optional reference to the original file location. - /// The title for the new tab. - /// - /// - /// The lines are given by a list of . If you set the lineNumber field - /// in each LineEntry to a lineNumber of the original logfile (the logfile for which the context - /// menu is called for), you can create a 'link' from the line of your 'target output' to a line - /// in the 'source tab'. - /// - /// - /// The user can then navigate from the line in the new tab to the referenced - /// line in the original file (by using "locate in original file" from the context menu). - /// This is especially useful for plugins that generate output lines which are directly associated - /// to the selected input lines. - /// - /// - /// If you can't provide a reference to a location in the logfile, set the line number to -1. This - /// will disable the "locate in original file" menu entry. - /// - /// - void AddPipedTab(IList lineEntryList, string title); + /// Path of the file to be loaded. + /// Title shown on the tab. + /// + /// The file tab is internally handled like the temp file tabs which LogExpert uses for + /// FilterTabs or clipboard copy tabs. + /// This has some implications: + ///
    + ///
  • The file path is not shown. Only the title is shown.
  • + ///
  • The encoding of the file is expected to be 2-byte Unicode!
  • + ///
  • The file will not be added to the history of opened files.
  • + ///
  • The file will be deleted when closing the tab!
  • + ///
+ ///
+ void AddTempFileTab(string fileName, string title); + /// + /// With this function you can create a new tab and add a bunch of text lines to it. + /// + /// A list with LineEntry items containing text and an + /// optional reference to the original file location. + /// The title for the new tab. + /// + /// + /// The lines are given by a list of . If you set the lineNumber field + /// in each LineEntry to a lineNumber of the original logfile (the logfile for which the context + /// menu is called for), you can create a 'link' from the line of your 'target output' to a line + /// in the 'source tab'. + /// + /// + /// The user can then navigate from the line in the new tab to the referenced + /// line in the original file (by using "locate in original file" from the context menu). + /// This is especially useful for plugins that generate output lines which are directly associated + /// to the selected input lines. + /// + /// + /// If you can't provide a reference to a location in the logfile, set the line number to -1. This + /// will disable the "locate in original file" menu entry. + /// + /// + void AddPipedTab(IList lineEntryList, string title); - /// - /// Returns the title of the current tab (the tab for which the context menu plugin was called for). - /// - /// - string GetTabTitle(); + /// + /// Returns the title of the current tab (the tab for which the context menu plugin was called for). + /// + /// + string GetTabTitle(); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogExpertLogger.cs b/src/ColumnizerLib/ILogExpertLogger.cs index aec36cfe..cfbbd884 100644 --- a/src/ColumnizerLib/ILogExpertLogger.cs +++ b/src/ColumnizerLib/ILogExpertLogger.cs @@ -1,44 +1,45 @@ -using System; +using System; using System.Collections.Generic; +using System.Globalization; using System.Text; -namespace LogExpert +namespace LogExpert; + +/// +/// Simple Logger interface to let plugins log into LogExpert's application log file. +/// +public interface ILogExpertLogger { + #region Public methods + /// - /// Simple Logger interface to let plugins log into LogExpert's application log file. + /// Logs a message on INFO level to LogExpert#s log file. The logfile is only active in debug builds. + /// The logger in LogExpert will automatically add the class and the method name of the caller. /// - public interface ILogExpertLogger - { - #region Public methods - - /// - /// Logs a message on INFO level to LogExpert#s log file. The logfile is only active in debug builds. - /// The logger in LogExpert will automatically add the class and the method name of the caller. - /// - /// A message to be logged. - void Info(string msg); + /// A message to be logged. + void Info(string msg); + void Info (IFormatProvider formatProvider, string msg); - /// - /// Logs a message on DEBUG level to LogExpert#s log file. The logfile is only active in debug builds. - /// The logger in LogExpert will automatically add the class and the method name of the caller. - /// - /// A message to be logged. - void Debug(string msg); + /// + /// Logs a message on DEBUG level to LogExpert#s log file. The logfile is only active in debug builds. + /// The logger in LogExpert will automatically add the class and the method name of the caller. + /// + /// A message to be logged. + void Debug(string msg); - /// - /// Logs a message on WARN level to LogExpert#s log file. The logfile is only active in debug builds. - /// The logger in LogExpert will automatically add the class and the method name of the caller. - /// - /// A message to be logged. - void LogWarn(string msg); + /// + /// Logs a message on WARN level to LogExpert#s log file. The logfile is only active in debug builds. + /// The logger in LogExpert will automatically add the class and the method name of the caller. + /// + /// A message to be logged. + void LogWarn(string msg); - /// - /// Logs a message on ERROR level to LogExpert#s log file. The logfile is only active in debug builds. - /// The logger in LogExpert will automatically add the class and the method name of the caller. - /// - /// A message to be logged. - void LogError(string msg); + /// + /// Logs a message on ERROR level to LogExpert#s log file. The logfile is only active in debug builds. + /// The logger in LogExpert will automatically add the class and the method name of the caller. + /// + /// A message to be logged. + void LogError(string msg); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogExpertPlugin.cs b/src/ColumnizerLib/ILogExpertPlugin.cs index 041e64d5..51c40971 100644 --- a/src/ColumnizerLib/ILogExpertPlugin.cs +++ b/src/ColumnizerLib/ILogExpertPlugin.cs @@ -2,27 +2,26 @@ using System.Collections.Generic; using System.Text; -namespace LogExpert +namespace LogExpert; + +/// +/// Implement this interface to get notified of various global events in LogExpert. +/// The interface can be implemented by all currently known type of LogExpert plugins (Columnizers, +/// keyword plugins, context menu plugins). +/// +public interface ILogExpertPlugin { + #region Public methods + /// - /// Implement this interface to get notified of various global events in LogExpert. - /// The interface can be implemented by all currently known type of LogExpert plugins (Columnizers, - /// keyword plugins, context menu plugins). + /// Called on application exit. May be used for cleanup purposes, /// - public interface ILogExpertPlugin - { - #region Public methods - - /// - /// Called on application exit. May be used for cleanup purposes, - /// - void AppExiting(); + void AppExiting(); - /// - /// Called when the plugin is loaded at plugin registration while LogExpert startup. - /// - void PluginLoaded(); + /// + /// Called when the plugin is loaded at plugin registration while LogExpert startup. + /// + void PluginLoaded(); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogExpertPluginConfigurator.cs b/src/ColumnizerLib/ILogExpertPluginConfigurator.cs index c142541b..9981528c 100644 --- a/src/ColumnizerLib/ILogExpertPluginConfigurator.cs +++ b/src/ColumnizerLib/ILogExpertPluginConfigurator.cs @@ -2,92 +2,91 @@ using System.Collections.Generic; using System.Text; -namespace LogExpert +namespace LogExpert; + +/// +/// If your context menu plugin or keyword action plugin has some configuration it should +/// implement this interface. +/// When your plugin has implemented this interface, it will get notified if it has to +/// show a config dialog and to save/load config data.

+/// Like in the IColumnizerConfigurator, you have to do all the saving and loading stuff +/// by yourself. +///
+public interface ILogExpertPluginConfigurator { + #region Public methods + /// - /// If your context menu plugin or keyword action plugin has some configuration it should - /// implement this interface. - /// When your plugin has implemented this interface, it will get notified if it has to - /// show a config dialog and to save/load config data.

- /// Like in the IColumnizerConfigurator, you have to do all the saving and loading stuff - /// by yourself. + /// Return whether your plugin will provide an embedded config dialog or wants to provide + /// a 'popup' dialog for the configuration.



+ /// 'Embedded' means that the dialog is shown directly in the Settings dialog of LogExpert on the + /// right pane of the plugin config tab. ///
- public interface ILogExpertPluginConfigurator - { - #region Public methods + /// Return true if your plugin config dialog should be displayed embedded. + bool HasEmbeddedForm(); - /// - /// Return whether your plugin will provide an embedded config dialog or wants to provide - /// a 'popup' dialog for the configuration.



- /// 'Embedded' means that the dialog is shown directly in the Settings dialog of LogExpert on the - /// right pane of the plugin config tab. - ///
- /// Return true if your plugin config dialog should be displayed embedded. - bool HasEmbeddedForm(); - - /// - /// This function is called when LogExpert fills the list of plugins in the Settings dialog. - /// This is the right time to create a 'temporary copy' of your current settings. The temporary copy - /// can be used for initializing the config dialogs. - /// - void StartConfig(); + /// + /// This function is called when LogExpert fills the list of plugins in the Settings dialog. + /// This is the right time to create a 'temporary copy' of your current settings. The temporary copy + /// can be used for initializing the config dialogs. + /// + void StartConfig(); - /// - /// Implement this function if your plugins uses an embedded config dialog. - /// This function is called when the user selects the plugin in the list of the Settings dialog - /// and the plugin uses an embedded dialog.



- /// You have to create a non-toplevel dialog and set the given parentPanel as the parent of your - /// dialog. Then make your dialog visible (using Show()). - /// You don't need an OK or Cancel button. Changes made in the dialog should be retrieved - /// to a temporary config every time the function is called. - /// The temporary config should be permanently stored when the function - /// is called. - ///
- /// - /// Set this panel as the parent for you config dialog. - void ShowConfigForm(object parentPanel); + /// + /// Implement this function if your plugins uses an embedded config dialog. + /// This function is called when the user selects the plugin in the list of the Settings dialog + /// and the plugin uses an embedded dialog.



+ /// You have to create a non-toplevel dialog and set the given parentPanel as the parent of your + /// dialog. Then make your dialog visible (using Show()). + /// You don't need an OK or Cancel button. Changes made in the dialog should be retrieved + /// to a temporary config every time the function is called. + /// The temporary config should be permanently stored when the function + /// is called. + ///
+ /// + /// Set this panel as the parent for you config dialog. + void ShowConfigForm(object parentPanel); - /// - /// Implement this function if your plugin uses an own top level dialog for the configuration (modal config dialog). - /// This function is called if the user clicks on the 'Config' button on the plugin settings. - ///



- /// You have to create a top level dialog and set the given Form as the owner. Then show - /// the dialog as a modal window (Form.ShowDialog()). Changes made in the dialog should be retrieved - /// after Form.ShowDialog() returns and then put to the temporary copy of your config. - /// The temporary copy config should be permanently stored when the function - /// is called. - ///
- /// - /// Set the given Form as the owner of your dialog. - void ShowConfigDialog(object owner); + /// + /// Implement this function if your plugin uses an own top level dialog for the configuration (modal config dialog). + /// This function is called if the user clicks on the 'Config' button on the plugin settings. + ///



+ /// You have to create a top level dialog and set the given Form as the owner. Then show + /// the dialog as a modal window (Form.ShowDialog()). Changes made in the dialog should be retrieved + /// after Form.ShowDialog() returns and then put to the temporary copy of your config. + /// The temporary copy config should be permanently stored when the function + /// is called. + ///
+ /// + /// Set the given Form as the owner of your dialog. + void ShowConfigDialog(object owner); - /// - /// This function is called when the user selects another plugin in the list. You should retrieve - /// the changes made in the config dialog to a temporary copy of the config and destroy your dialog. - /// Don't make the changes permanent here, because the user may click the cancel button of LogExpert's - /// Settings dialog. In this case he/she would expect the changes to be discarded.

- /// The right place for making changes permanent is the function. - ///
- /// - /// The method is also called when the settings dialog is closed. If the settings dialog is closed - /// by OK button this method is called before the method. - /// - void HideConfigForm(); + /// + /// This function is called when the user selects another plugin in the list. You should retrieve + /// the changes made in the config dialog to a temporary copy of the config and destroy your dialog. + /// Don't make the changes permanent here, because the user may click the cancel button of LogExpert's + /// Settings dialog. In this case he/she would expect the changes to be discarded.

+ /// The right place for making changes permanent is the function. + ///
+ /// + /// The method is also called when the settings dialog is closed. If the settings dialog is closed + /// by OK button this method is called before the method. + /// + void HideConfigForm(); - /// - /// Called by LogExpert if the user clicks the OK button in LogExpert's Settings dialog. - /// Save your temporary copy of the config here. - /// - /// The location where LogExpert stores its settings. - void SaveConfig(string configDir); + /// + /// Called by LogExpert if the user clicks the OK button in LogExpert's Settings dialog. + /// Save your temporary copy of the config here. + /// + /// The location where LogExpert stores its settings. + void SaveConfig(string configDir); - /// - /// This function is called when LogExpert is started and scans the plugin directory. - /// You should load your settings here. - /// - /// The location where LogExpert stores its settings. - void LoadConfig(string configDir); + /// + /// This function is called when LogExpert is started and scans the plugin directory. + /// You should load your settings here. + /// + /// The location where LogExpert stores its settings. + void LoadConfig(string configDir); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogFileInfo.cs b/src/ColumnizerLib/ILogFileInfo.cs index 39392fb0..a65ee5b1 100644 --- a/src/ColumnizerLib/ILogFileInfo.cs +++ b/src/ColumnizerLib/ILogFileInfo.cs @@ -1,85 +1,84 @@ -using System.IO; using System; +using System.IO; + +namespace LogExpert; -namespace LogExpert +/// +/// Interface which represents a file in LogExpert. 'File' could be anything that represents text data to be displayed in LogExpert. +/// +public interface ILogFileInfo { + #region Properties + + /// + /// The file name (complete path) of the log file. This should be a unique name. E.g. an URI or a path on local disk. + /// + string FullName { get; } + + /// + /// The file name without path. + /// + string FileName { get; } + + /// + /// The directory of the log file. In most cases this is the FullName minus FileName. + /// + string DirectoryName { get; } + + /// + /// Character used to separate directories in a path string. + /// + char DirectorySeparatorChar { get; } + + /// + /// The URI of the log file. + /// + Uri Uri { get; } + /// - /// Interface which represents a file in LogExpert. 'File' could be anything that represents text data to be displayed in LogExpert. + /// Current length of the file. Return -1 if the file is not found. /// - public interface ILogFileInfo - { - #region Properties - - /// - /// The file name (complete path) of the log file. This should be a unique name. E.g. an URI or a path on local disk. - /// - string FullName { get; } - - /// - /// The file name without path. - /// - string FileName { get; } - - /// - /// The directory of the log file. In most cases this is the FullName minus FileName. - /// - string DirectoryName { get; } - - /// - /// Character used to separate directories in a path string. - /// - char DirectorySeparatorChar { get; } - - /// - /// The URI of the log file. - /// - Uri Uri { get; } - - /// - /// Current length of the file. Return -1 if the file is not found. - /// - long Length { get; } - - /// - /// Initial file length at the time the ILogFileInfo instance was created. This is used for the buffer shifting when - /// using the multi file feature. This value should not change after the instance has been created. - /// - long OriginalLength { get; } - - /// - /// Whether the file exists. - /// - bool FileExists { get; } - - /// - /// The interval (in ms) LogExpert should check for file changes. The property is checked by LogExpert repeatedly in the loop which - /// checks for file changes. So you can adjust the poll interval as needed. E.g. you can lower the interval when many changes occur and - /// raise the interval when the file has not been changed for a certain amount of time. - /// - int PollInterval { get; } - - #endregion - - #region Public methods - - /// - /// Returns a stream for the log file file. The actual type of stream depends on the implementation. - /// The caller (LogExpert) is responsible for closing the stream. - /// - /// - /// The returned Stream must support read and seek. Writing is not needed. - /// - /// A Stream open for reading - Stream OpenStream(); - - /// - /// Return true if the file has been changed since the last call to this method. - /// - /// - /// LogExpert will poll this method with the interval returned from PollInterval. - /// - bool FileHasChanged(); - - #endregion - } + long Length { get; } + + /// + /// Initial file length at the time the ILogFileInfo instance was created. This is used for the buffer shifting when + /// using the multi file feature. This value should not change after the instance has been created. + /// + long OriginalLength { get; } + + /// + /// Whether the file exists. + /// + bool FileExists { get; } + + /// + /// The interval (in ms) LogExpert should check for file changes. The property is checked by LogExpert repeatedly in the loop which + /// checks for file changes. So you can adjust the poll interval as needed. E.g. you can lower the interval when many changes occur and + /// raise the interval when the file has not been changed for a certain amount of time. + /// + int PollInterval { get; } + + #endregion + + #region Public methods + + /// + /// Returns a stream for the log file file. The actual type of stream depends on the implementation. + /// The caller (LogExpert) is responsible for closing the stream. + /// + /// + /// The returned Stream must support read and seek. Writing is not needed. + /// + /// A Stream open for reading + Stream OpenStream(); + + /// + /// Return true if the file has been changed since the last call to this method. + /// + /// + /// LogExpert will poll this method with the interval returned from PollInterval. + /// + bool FileHasChanged(); + + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogLine.cs b/src/ColumnizerLib/ILogLine.cs index 8ffe7e9f..7599acbf 100644 --- a/src/ColumnizerLib/ILogLine.cs +++ b/src/ColumnizerLib/ILogLine.cs @@ -1,13 +1,12 @@ -namespace LogExpert +namespace LogExpert; + +public interface ILogLine : ITextValue { - public interface ILogLine : ITextValue - { - #region Properties + #region Properties - string FullLine { get; } + string FullLine { get; } - int LineNumber { get; } + int LineNumber { get; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogLineColumnizer.cs b/src/ColumnizerLib/ILogLineColumnizer.cs index e12988ac..70ccc8a2 100644 --- a/src/ColumnizerLib/ILogLineColumnizer.cs +++ b/src/ColumnizerLib/ILogLineColumnizer.cs @@ -1,121 +1,120 @@ using System; -namespace LogExpert +namespace LogExpert; + +/// +/// This interface defines a so-called 'Columnizer' for LogExpert. +/// A columnizer splits a single text line into well defined columns. These columns +/// are used in the data grid view of LogExpert. +///



+/// Optionally a columnizer can parse the log line to determine the date/time of +/// the log line (assuming that all log lines have a timestamp). This is needed for +/// some of the features of LogExpert (see user documentation for more information). +///



+/// You can implement your own columnizers for your logfile format, if needed. +///
+public interface ILogLineColumnizer { - /// - /// This interface defines a so-called 'Columnizer' for LogExpert. - /// A columnizer splits a single text line into well defined columns. These columns - /// are used in the data grid view of LogExpert. - ///



- /// Optionally a columnizer can parse the log line to determine the date/time of - /// the log line (assuming that all log lines have a timestamp). This is needed for - /// some of the features of LogExpert (see user documentation for more information). - ///



- /// You can implement your own columnizers for your logfile format, if needed. - ///
- public interface ILogLineColumnizer - { - #region Public methods + #region Public methods - /// - /// Returns the name for the columnizer. This name is used for the columnizer selection dialog. - /// - string GetName(); + /// + /// Returns the name for the columnizer. This name is used for the columnizer selection dialog. + /// + string GetName(); - /// - /// Returns the description of the columnizer. This text is used in the columnizer selection dialog. - /// - string GetDescription(); + /// + /// Returns the description of the columnizer. This text is used in the columnizer selection dialog. + /// + string GetDescription(); - /// - /// Returns the number of columns the columnizer will split lines into. - /// - /// - /// This value does not include the column for displaying the line number. The line number column - /// is added by LogExpert and is not handled by columnizers. - /// - int GetColumnCount(); + /// + /// Returns the number of columns the columnizer will split lines into. + /// + /// + /// This value does not include the column for displaying the line number. The line number column + /// is added by LogExpert and is not handled by columnizers. + /// + int GetColumnCount(); - /// - /// Returns the names of the columns. The returned names are used by LogExpert for the column headers in the data grid view. - /// The names are expected in order from left to right. - /// - string[] GetColumnNames(); + /// + /// Returns the names of the columns. The returned names are used by LogExpert for the column headers in the data grid view. + /// The names are expected in order from left to right. + /// + string[] GetColumnNames(); - /// - /// Given a single line of the logfile this function splits the line content into columns. The function returns - /// a string array containing the splitted content. - /// - /// - /// This function is called by LogExpert for every line that has to be drawn in the grid view. The faster your code - /// handles the splitting, the faster LogExpert can draw the grid view content.

- ///

- /// Notes about timeshift handling:

- /// If your columnizer implementation supports timeshift (see IsTimeshiftImplemented) - /// you have to add the timestamp offset to the columns representing the timestamp (e.g. columns like 'date' and 'time'). - /// In practice this means you have to parse the date/time value of your log line (see GetTimestamp) - /// add the offset and convert the timestamp back to string value(s). - ///
- /// Callback interface with functions which can be used by the columnizer - /// The line content to be splitted - IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line); + /// + /// Given a single line of the logfile this function splits the line content into columns. The function returns + /// a string array containing the splitted content. + /// + /// + /// This function is called by LogExpert for every line that has to be drawn in the grid view. The faster your code + /// handles the splitting, the faster LogExpert can draw the grid view content.

+ ///

+ /// Notes about timeshift handling:

+ /// If your columnizer implementation supports timeshift (see IsTimeshiftImplemented) + /// you have to add the timestamp offset to the columns representing the timestamp (e.g. columns like 'date' and 'time'). + /// In practice this means you have to parse the date/time value of your log line (see GetTimestamp) + /// add the offset and convert the timestamp back to string value(s). + ///
+ /// Callback interface with functions which can be used by the columnizer + /// The line content to be splitted + IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line); - /// - /// Returns true, if the columnizer supports timeshift handling. - /// - /// - /// If you return true, you also have to implement the function SetTimeOffset(), GetTimeOffset() and GetTimestamp(). - /// You also must handle PushValue() for the column(s) that displays the timestamp. - /// - bool IsTimeshiftImplemented(); + /// + /// Returns true, if the columnizer supports timeshift handling. + /// + /// + /// If you return true, you also have to implement the function SetTimeOffset(), GetTimeOffset() and GetTimestamp(). + /// You also must handle PushValue() for the column(s) that displays the timestamp. + /// + bool IsTimeshiftImplemented(); - /// - /// Sets an offset to be used for displaying timestamp values. You have to implement this function, if - /// your IsTimeshiftImplemented() function return true. - /// - /// - /// You have to store the given value in the Columnizer instance and add this offset to the timestamp column(s) returned by SplitLine() - /// (e.g. in the date and time columns). - /// - /// The timestamp offset in milliseconds. - void SetTimeOffset(int msecOffset); + /// + /// Sets an offset to be used for displaying timestamp values. You have to implement this function, if + /// your IsTimeshiftImplemented() function return true. + /// + /// + /// You have to store the given value in the Columnizer instance and add this offset to the timestamp column(s) returned by SplitLine() + /// (e.g. in the date and time columns). + /// + /// The timestamp offset in milliseconds. + void SetTimeOffset(int msecOffset); - /// - /// Returns the current stored timestamp offset (set by SetTimeOffset()). - /// - int GetTimeOffset(); + /// + /// Returns the current stored timestamp offset (set by SetTimeOffset()). + /// + int GetTimeOffset(); - /// - /// Returns the timestamp value of the given line as a .NET DateTime object. If there's no valid timestamp in the - /// given line you have to return DateTime.MinValue. - /// - /// - /// When implementing this function you have to parse the given log line for a valid date/time to get a DateTime object. - /// Before returning the DateTime object you have to add the offset which was set by SetTimeOffset().

- ///

- /// Note: If not all lines of your log files contain a valid date/time it's recommended to do some fail-fast pre checks before - /// calling the parse functions of DateTime. This saves a lot of time because DateTime.ParseExact() is very slow when fed with - /// invalid input. - ///
- /// Callback interface with functions which can be used by the columnizer - /// The line content which timestamp has to be returned. - DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line); + /// + /// Returns the timestamp value of the given line as a .NET DateTime object. If there's no valid timestamp in the + /// given line you have to return DateTime.MinValue. + /// + /// + /// When implementing this function you have to parse the given log line for a valid date/time to get a DateTime object. + /// Before returning the DateTime object you have to add the offset which was set by SetTimeOffset().

+ ///

+ /// Note: If not all lines of your log files contain a valid date/time it's recommended to do some fail-fast pre checks before + /// calling the parse functions of DateTime. This saves a lot of time because DateTime.ParseExact() is very slow when fed with + /// invalid input. + ///
+ /// Callback interface with functions which can be used by the columnizer + /// The line content which timestamp has to be returned. + DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line); - /// - /// This function is called if the user changes a value in a column (edit mode in the log view). - /// The purpose of the function is to determine a new timestamp offset. So you have to handle the - /// call only if the given column displays a timestamp. - /// - /// - /// You should parse both values (oldValue, value) for valid timestamps, determine the time offset and store the offset as - /// the new timeshift offset (and of course use this offset in the GetTimestamp() and SplitLine() functions). - /// - /// Callback interface with functions which can be used by the columnizer - /// The column number which value has changed. - /// The new value. - /// The old value. - void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue); + /// + /// This function is called if the user changes a value in a column (edit mode in the log view). + /// The purpose of the function is to determine a new timestamp offset. So you have to handle the + /// call only if the given column displays a timestamp. + /// + /// + /// You should parse both values (oldValue, value) for valid timestamps, determine the time offset and store the offset as + /// the new timeshift offset (and of course use this offset in the GetTimestamp() and SplitLine() functions). + /// + /// Callback interface with functions which can be used by the columnizer + /// The column number which value has changed. + /// The new value. + /// The old value. + void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogLineColumnizerCallback.cs b/src/ColumnizerLib/ILogLineColumnizerCallback.cs index 1b72fb2b..3cdb8988 100644 --- a/src/ColumnizerLib/ILogLineColumnizerCallback.cs +++ b/src/ColumnizerLib/ILogLineColumnizerCallback.cs @@ -1,51 +1,46 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace LogExpert; -namespace LogExpert +/// +///This is a callback interface. Some of the ILogLineColumnizer functions +///are called with this interface as an argument. You don't have to implement this interface. It's implemented +///by LogExpert. You can use it in your own columnizers, if you need it. +/// +/// +///Implementors of ILogLineColumnizer can use the provided functions to get some more informations +///about the log file. In the most cases you don't need this interface. It's provided here for special cases.

+///

+///An example would be when the log lines contains only the time of day but the date is coded in the file name. In this situation +///you can use the GetFileName() function to retrieve the name of the current file to build a complete timestamp. +///
+public interface ILogLineColumnizerCallback { - /// - ///This is a callback interface. Some of the ILogLineColumnizer functions - ///are called with this interface as an argument. You don't have to implement this interface. It's implemented - ///by LogExpert. You can use it in your own columnizers, if you need it. - /// - /// - ///Implementors of ILogLineColumnizer can use the provided functions to get some more informations - ///about the log file. In the most cases you don't need this interface. It's provided here for special cases.

- ///

- ///An example would be when the log lines contains only the time of day but the date is coded in the file name. In this situation - ///you can use the GetFileName() function to retrieve the name of the current file to build a complete timestamp. - ///
- public interface ILogLineColumnizerCallback - { - #region Public methods + #region Public methods - /// - /// This function returns the current line number. That is the line number of the log line - /// a ILogLineColumnizer function is called for (e.g. the line that has to be painted). - /// - /// The current line number starting at 0 - int GetLineNum(); + /// + /// This property returns the current line number. That is the line number of the log line + /// a ILogLineColumnizer function is called for (e.g. the line that has to be painted). + /// + /// The current line number starting at 0 + int LineNum { get; } - /// - /// Returns the full file name (path + name) of the current log file. - /// - /// File name of current log file - string GetFileName(); + /// + /// Returns the full file name (path + name) of the current log file. + /// + /// File name of current log file + string GetFileName (); - /// - /// Returns the log line with the given index (zero-based). - /// - /// Number of the line to be retrieved - /// A string with line content or null if line number is out of range - ILogLine GetLogLine(int lineNum); + /// + /// Returns the log line with the given index (zero-based). + /// + /// Number of the line to be retrieved + /// A string with line content or null if line number is out of range + ILogLine GetLogLine (int lineNum); - /// - /// Returns the number of lines of the logfile. - /// - /// Number of lines. - int GetLineCount(); + /// + /// Returns the number of lines of the logfile. + /// + /// Number of lines. + int GetLineCount (); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ILogLineXmlColumnizer.cs b/src/ColumnizerLib/ILogLineXmlColumnizer.cs index cc79e1dd..9ab6845b 100644 --- a/src/ColumnizerLib/ILogLineXmlColumnizer.cs +++ b/src/ColumnizerLib/ILogLineXmlColumnizer.cs @@ -1,77 +1,72 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace LogExpert; -namespace LogExpert +/// +/// This is the interface for a Columnizer which supports XML log files. This interface extends +/// the interface. +/// LogExpert will automatically load a log file in XML mode if the current Columnizer implements +/// this interface. +/// +/// +/// +/// Note that the ILogLineXmlColumnizer interface is also a marker interface. If the user selects a +/// Columnizer that implements ILogLineXmlColumnizer then the log file will be treatet as XML file. +///

+/// When in XML mode, LogExpert will scan for XML fragmets. These fragments are defined by opening +/// and closing tags (e.g. <log4j:event> and </log4j:event>). Every fragment is +/// transformed by using a XSLT template. The result of the transformation (which may be multi-lined) +/// is splitted into single lines. These single lines are the lines you will see in LogExpert's display. +///
+/// +/// If you implement a XML Columnizer you have to provide the start tag and end tag and a +/// XSLT. Also you have to provide a namespace declaration, if your logfile uses name spaces. +/// All this stuff must be provided by returning a IXmlLogConfiguration in the method. +/// +/// +/// The processing of XML log files is done in the following steps: +///
    +///
  1. LogExpert reads the file and separates it into fragments of XML content using the given +/// start/end tags ()
  2. +///
  3. The fragments will be translated using the given XSLT () +/// The result is one or more lines of text content. These lines will be the lines LogExpert will 'see' +/// in its internal buffer and line management. They will be handled like normal text lines in other +/// (non-XML) log files. +///
  4. +///
  5. The lines will be passed to the usual methods before displaying. So you can handle +/// field splitting in the way known from . +///
  6. +///
+///
+///
+public interface ILogLineXmlColumnizer : ILogLineColumnizer { + #region Public methods + + /// + /// You have to implement this function to provide a configuration for LogExpert's XML reader. + /// + /// + IXmlLogConfiguration GetXmlLogConfiguration (); + /// - /// This is the interface for a Columnizer which supports XML log files. This interface extends - /// the interface. - /// LogExpert will automatically load a log file in XML mode if the current Columnizer implements - /// this interface. + /// Returns the text which should be copied into the clipboard when the user want to copy selected + /// lines to clipboard. /// + /// The line as retrieved from the internal log reader. This is + /// the result of the XSLT processing with your provided stylesheet. + /// + /// Callback which may be used by the Columnizer + /// A string which is placed into the clipboard /// - /// - /// Note that the ILogLineXmlColumnizer interface is also a marker interface. If the user selects a - /// Columnizer that implements ILogLineXmlColumnizer then the log file will be treatet as XML file. + /// This function is intended to convert the representation of a log line produced by XSLT transformation into + /// a format suitable for clipboard. + /// The method can be used in the case that the XSLT transformation result is not very 'human readable'. ///

- /// When in XML mode, LogExpert will scan for XML fragmets. These fragments are defined by opening - /// and closing tags (e.g. <log4j:event> and </log4j:event>). Every fragment is - /// transformed by using a XSLT template. The result of the transformation (which may be multi-lined) - /// is splitted into single lines. These single lines are the lines you will see in LogExpert's display. - ///
- /// - /// If you implement a XML Columnizer you have to provide the start tag and end tag and a - /// XSLT. Also you have to provide a namespace declaration, if your logfile uses name spaces. - /// All this stuff must be provided by returning a IXmlLogConfiguration in the method. - /// - /// - /// The processing of XML log files is done in the following steps: - ///
    - ///
  1. LogExpert reads the file and separates it into fragments of XML content using the given - /// start/end tags ()
  2. - ///
  3. The fragments will be translated using the given XSLT () - /// The result is one or more lines of text content. These lines will be the lines LogExpert will 'see' - /// in its internal buffer and line management. They will be handled like normal text lines in other - /// (non-XML) log files. - ///
  4. - ///
  5. The lines will be passed to the usual methods before displaying. So you can handle - /// field splitting in the way known from . - ///
  6. - ///
- ///
+ /// An example is the included Log4jXMLColumnizer. It uses special characters to separate the fields. + /// The characters are added while XSLT transformation. The usual Columnizer functions (e.g. SplitLIne()) will + /// use these markers for line splitting. + /// When copying to clipboard, this method will remove the special characters and replace them with spaces. ///
- public interface ILogLineXmlColumnizer : ILogLineColumnizer - { - #region Public methods - - /// - /// You have to implement this function to provide a configuration for LogExpert's XML reader. - /// - /// - IXmlLogConfiguration GetXmlLogConfiguration(); - - /// - /// Returns the text which should be copied into the clipboard when the user want to copy selected - /// lines to clipboard. - /// - /// The line as retrieved from the internal log reader. This is - /// the result of the XSLT processing with your provided stylesheet. - /// - /// Callback which may be used by the Columnizer - /// A string which is placed into the clipboard - /// - /// This function is intended to convert the representation of a log line produced by XSLT transformation into - /// a format suitable for clipboard. - /// The method can be used in the case that the XSLT transformation result is not very 'human readable'. - ///

- /// An example is the included Log4jXMLColumnizer. It uses special characters to separate the fields. - /// The characters are added while XSLT transformation. The usual Columnizer functions (e.g. SplitLIne()) will - /// use these markers for line splitting. - /// When copying to clipboard, this method will remove the special characters and replace them with spaces. - ///
- ILogLine GetLineTextForClipboard(ILogLine logLine, ILogLineColumnizerCallback callback); + ILogLine GetLineTextForClipboard (ILogLine logLine, ILogLineColumnizerCallback callback); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IPreProcessColumnizer.cs b/src/ColumnizerLib/IPreProcessColumnizer.cs index 6c8e9cbd..92a1ea86 100644 --- a/src/ColumnizerLib/IPreProcessColumnizer.cs +++ b/src/ColumnizerLib/IPreProcessColumnizer.cs @@ -2,64 +2,63 @@ using System.Collections.Generic; using System.Text; -namespace LogExpert +namespace LogExpert; + +/// +/// +/// Implement this interface in your columnizer if you want to pre-process every line +/// directly when it's loaded from file system. +/// +/// You can also use this to drop lines. +/// +/// +/// +/// +/// By implementing this interface with your Columnizer you get the ability to modify the +/// content of a log file right before it will be seen by LogExpert. +/// +/// +/// Note that the +/// method is only used when loading a line from disk. Because of internal buffering a log line may +/// be read only once or multiple times. You have to ensure that the behaviour is consistent +/// for every call to for a specific line. That's especially true +/// when dropping lines. Dropping a line changes the line count seen by LogExpert. That has implications +/// for things like bookmarks etc. +/// +/// +public interface IPreProcessColumnizer { + #region Public methods + /// - /// - /// Implement this interface in your columnizer if you want to pre-process every line - /// directly when it's loaded from file system. - /// - /// You can also use this to drop lines. - /// + /// This function is called for every line read from the log file. You can change the content + /// by returning a different string. You can also drop the complete line by returning null. /// + /// Line content + /// Line number as seen by LogExpert + /// Actual line number in the file + /// The changed content or null to drop the line /// /// - /// By implementing this interface with your Columnizer you get the ability to modify the - /// content of a log file right before it will be seen by LogExpert. + /// The values of lineNum and realLineNum differ only if you drop lines (by returning null). + /// When you drop a line, this line is hidden completely from LogExpert's log buffers. No chance + /// to bring it back later. When you drop a line, the lineNum will stay the same for the next + /// method call (for the next line). But realLineNum will increase for every call. + /// + /// + /// A usage example is the CsvColumnizer: If configuration says that there are field names + /// in the first line if the CSV file, the CsvColumnizer will store the first line for later + /// field name retrieval. But then the line is dropped. So the line isn't seen by LogExpert. + /// Detecting the first line in the file is only possible by checking the realLineNum parameter. /// /// - /// Note that the - /// method is only used when loading a line from disk. Because of internal buffering a log line may - /// be read only once or multiple times. You have to ensure that the behaviour is consistent - /// for every call to for a specific line. That's especially true - /// when dropping lines. Dropping a line changes the line count seen by LogExpert. That has implications - /// for things like bookmarks etc. + /// Remember that the method is called in an early state + /// when loading the file. So the file isn't loaded completely and the internal state + /// of LogExpert isn't complete. You cannot make any assumptions about file size or other + /// things. The given parameters are the only 'stateful' informations you can rely on. /// /// - public interface IPreProcessColumnizer - { - #region Public methods - - /// - /// This function is called for every line read from the log file. You can change the content - /// by returning a different string. You can also drop the complete line by returning null. - /// - /// Line content - /// Line number as seen by LogExpert - /// Actual line number in the file - /// The changed content or null to drop the line - /// - /// - /// The values of lineNum and realLineNum differ only if you drop lines (by returning null). - /// When you drop a line, this line is hidden completely from LogExpert's log buffers. No chance - /// to bring it back later. When you drop a line, the lineNum will stay the same for the next - /// method call (for the next line). But realLineNum will increase for every call. - /// - /// - /// A usage example is the CsvColumnizer: If configuration says that there are field names - /// in the first line if the CSV file, the CsvColumnizer will store the first line for later - /// field name retrieval. But then the line is dropped. So the line isn't seen by LogExpert. - /// Detecting the first line in the file is only possible by checking the realLineNum parameter. - /// - /// - /// Remember that the method is called in an early state - /// when loading the file. So the file isn't loaded completely and the internal state - /// of LogExpert isn't complete. You cannot make any assumptions about file size or other - /// things. The given parameters are the only 'stateful' informations you can rely on. - /// - /// - string PreProcessLine(string logLine, int lineNum, int realLineNum); + string PreProcessLine(string logLine, int lineNum, int realLineNum); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/ITextValue.cs b/src/ColumnizerLib/ITextValue.cs index bc6a218c..b072fb91 100644 --- a/src/ColumnizerLib/ITextValue.cs +++ b/src/ColumnizerLib/ITextValue.cs @@ -1,11 +1,10 @@ -namespace LogExpert +namespace LogExpert; + +public interface ITextValue { - public interface ITextValue - { - #region Properties + #region Properties - string Text { get; } + string Text { get; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/IXmlLogConfiguration.cs b/src/ColumnizerLib/IXmlLogConfiguration.cs index e6d9c659..b65422ed 100644 --- a/src/ColumnizerLib/IXmlLogConfiguration.cs +++ b/src/ColumnizerLib/IXmlLogConfiguration.cs @@ -1,41 +1,36 @@ -using System; -using System.Collections.Generic; -using System.Text; +namespace LogExpert; -namespace LogExpert +/// +/// This interface declares the configuration data which is needed for XML log file parsing. +/// +public interface IXmlLogConfiguration { + #region Properties + /// - /// This interface declares the configuration data which is needed for XML log file parsing. + /// The opening XML tag for a log entry. Every log entry starts with this tag.

+ /// Example: <log4j:event> ///
- public interface IXmlLogConfiguration - { - #region Properties - - /// - /// The opening XML tag for a log entry. Every log entry starts with this tag.

- /// Example: <log4j:event> - ///
- string XmlStartTag { get; } + string XmlStartTag { get; } - /// - /// The closing tag for a log entry.

- /// Example: </log4j:event> - ///
- string XmlEndTag { get; } + /// + /// The closing tag for a log entry.

+ /// Example: </log4j:event> + ///
+ string XmlEndTag { get; } - /// - /// A complete XSLT which is used to transform the XML fragments into text lines which can be - /// processed by the Columnizer. - /// - string Stylesheet { get; } + /// + /// A complete XSLT which is used to transform the XML fragments into text lines which can be + /// processed by the Columnizer. + /// + string Stylesheet { get; } - /// - /// A namespace declaration. The returned array must contain 2 strings: The namespace and its declaration.

- /// Example: {"log4j", "http://jakarta.apache.org/log4j"} - /// - ///
- string[] Namespace { get; } + /// + /// A namespace declaration. The returned array must contain 2 strings: The namespace and its declaration.

+ /// Example: {"log4j", "http://jakarta.apache.org/log4j"} + /// + ///
+ string[] GetNamespaceDeclaration (); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/ColumnizerLib/LineEntry.cs b/src/ColumnizerLib/LineEntry.cs index c0f02c17..e59c1791 100644 --- a/src/ColumnizerLib/LineEntry.cs +++ b/src/ColumnizerLib/LineEntry.cs @@ -1,20 +1,39 @@ -namespace LogExpert +using System; + +namespace LogExpert; + +/// +/// This helper struct holds a log line and its line number (zero based). +/// This struct is used by . +/// +/// +public struct LineEntry : IEquatable { /// - /// This helper struct holds a log line and its line number (zero based). - /// This struct is used by . + /// The content of the line. + /// + public ILogLine LogLine { get; set; } + + /// + /// The line number. See for an explanation of the line number. /// - /// - public struct LineEntry + public int LineNum { get; set; } + + public override bool Equals(object obj) { - /// - /// The content of the line. - /// - public ILogLine logLine; + return obj is LineEntry other && Equals(other); + } + + public readonly bool Equals(LineEntry other) + { + return LineNum == other.LineNum && Equals(LogLine, other.LogLine); + } - /// - /// The line number. See for an explanation of the line number. - /// - public int lineNum; + public override readonly int GetHashCode() + { + return HashCode.Combine(LineNum, LogLine); } + + public static bool operator == (LineEntry left, LineEntry right) => left.Equals(right); + public static bool operator != (LineEntry left, LineEntry right) => !left.Equals(right); } \ No newline at end of file diff --git a/src/ColumnizerLib/Priority.cs b/src/ColumnizerLib/Priority.cs index de968b24..964820aa 100644 --- a/src/ColumnizerLib/Priority.cs +++ b/src/ColumnizerLib/Priority.cs @@ -1,33 +1,32 @@ -namespace LogExpert +namespace LogExpert; + +/// +/// Priority for columnizer. +/// +public enum Priority { /// - /// Priority for columnizer. + /// Not support target file. /// - public enum Priority - { - /// - /// Not support target file. - /// - NotSupport = 0, + NotSupport = 0, - /// - /// Can support target file. E.g. default one CanSupport most of the files. - /// - CanSupport, + /// + /// Can support target file. E.g. default one CanSupport most of the files. + /// + CanSupport, - /// - /// Target file is soundly supported. E.g. JsonColumnizer WellSupport all json files. - /// - WellSupport, + /// + /// Target file is soundly supported. E.g. JsonColumnizer WellSupport all json files. + /// + WellSupport, - /// - /// The columnizer is designed to support target file. E.g. JsonCompactColumnizer PerfectlySupport all compact Json files. - /// - PerfectlySupport, + /// + /// The columnizer is designed to support target file. E.g. JsonCompactColumnizer PerfectlySupport all compact Json files. + /// + PerfectlySupport, - /// - /// Target file is only supported by this columnizer. - /// - Exclusive - } + /// + /// Target file is only supported by this columnizer. + /// + Exclusive } \ No newline at end of file diff --git a/src/CsvColumnizer/CsvColumn.cs b/src/CsvColumnizer/CsvColumn.cs index b2beb5ee..c899c940 100644 --- a/src/CsvColumnizer/CsvColumn.cs +++ b/src/CsvColumnizer/CsvColumn.cs @@ -1,20 +1,10 @@ -namespace CsvColumnizer -{ - internal class CsvColumn - { - #region cTor - - public CsvColumn(string name) - { - Name = name; - } +namespace CsvColumnizer; - #endregion - - #region Properties +internal class CsvColumn(string name) +{ + #region Properties - public string Name { get; } + public string Name { get; } = name; - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/CsvColumnizer/CsvColumnizer.cs b/src/CsvColumnizer/CsvColumnizer.cs index d2e46764..9254c4ca 100644 --- a/src/CsvColumnizer/CsvColumnizer.cs +++ b/src/CsvColumnizer/CsvColumnizer.cs @@ -1,6 +1,3 @@ -using CsvHelper; -using LogExpert; -using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; @@ -9,279 +6,283 @@ using System.Runtime.Versioning; using System.Windows.Forms; +using CsvHelper; + +using LogExpert; + +using Newtonsoft.Json; + [assembly: SupportedOSPlatform("windows")] -namespace CsvColumnizer +namespace CsvColumnizer; + +/// +/// This Columnizer can parse CSV files. It uses the IInitColumnizer interface for support of dynamic field count. +/// The IPreProcessColumnizer is implemented to read field names from the very first line of the file. Then +/// the line is dropped. So it's not seen by LogExpert. The field names will be used as column names. +/// +public class CsvColumnizer : ILogLineColumnizer, IInitColumnizer, IColumnizerConfigurator, IPreProcessColumnizer, IColumnizerPriority { - /// - /// This Columnizer can parse CSV files. It uses the IInitColumnizer interface for support of dynamic field count. - /// The IPreProcessColumnizer is implemented to read field names from the very first line of the file. Then - /// the line is dropped. So it's not seen by LogExpert. The field names will be used as column names. - /// - public class CsvColumnizer : ILogLineColumnizer, IInitColumnizer, IColumnizerConfigurator, IPreProcessColumnizer, IColumnizerPriority - { - #region Fields + #region Fields - private static readonly string _configFileName = "csvcolumnizer.json"; + private const string CONFIGFILENAME = "csvcolumnizer.json"; - private readonly IList _columnList = new List(); - private CsvColumnizerConfig _config; + private readonly IList _columnList = []; + private CsvColumnizerConfig _config; - private ILogLine _firstLine; + private ILogLine _firstLine; - // if CSV is detected to be 'invalid' the columnizer will behave like a default columnizer - private bool _isValidCsv; + // if CSV is detected to be 'invalid' the columnizer will behave like a default columnizer + private bool _isValidCsv; - #endregion + #endregion - #region Public methods + #region Public methods - public string PreProcessLine(string logLine, int lineNum, int realLineNum) + public string PreProcessLine (string logLine, int lineNum, int realLineNum) + { + if (realLineNum == 0) { - if (realLineNum == 0) - { - // store for later field names and field count retrieval - _firstLine = new CsvLogLine(logLine, 0); + // store for later field names and field count retrieval + _firstLine = new CsvLogLine(logLine, 0); - if (_config.MinColumns > 0) + if (_config.MinColumns > 0) + { + using CsvReader csv = new(new StringReader(logLine), _config.ReaderConfiguration); + if (csv.Parser.Count < _config.MinColumns) { - using (CsvReader csv = new CsvReader(new StringReader(logLine), _config.ReaderConfiguration)) - { - if (csv.Parser.Count < _config.MinColumns) - { - // on invalid CSV don't hide the first line from LogExpert, since the file will be displayed in plain mode - _isValidCsv = false; - return logLine; - } - } + // on invalid CSV don't hide the first line from LogExpert, since the file will be displayed in plain mode + _isValidCsv = false; + return logLine; } - - _isValidCsv = true; - } - - if (_config.HasFieldNames && realLineNum == 0) - { - return null; // hide from LogExpert - } - - if (_config.CommentChar != ' ' && logLine.StartsWith("" + _config.CommentChar)) - { - return null; } - return logLine; + _isValidCsv = true; } - public string GetName() + if (_config.HasFieldNames && realLineNum == 0) { - return "CSV Columnizer"; + return null; // hide from LogExpert } - public string GetDescription() + if (_config.CommentChar != ' ' && logLine.StartsWith("" + _config.CommentChar)) { - return "Splits CSV files into columns.\r\n\r\nCredits:\r\nThis Columnizer uses the CsvHelper. https://github.com/JoshClose/CsvHelper. \r\n"; + return null; } - public int GetColumnCount() - { - return _isValidCsv ? _columnList.Count : 1; - } + return logLine; + } - public string[] GetColumnNames() - { - string[] names = new string[GetColumnCount()]; - if (_isValidCsv) - { - int i = 0; - foreach (CsvColumn column in _columnList) - { - names[i++] = column.Name; - } - } - else - { - names[0] = "Text"; - } + public string GetName () + { + return "CSV Columnizer"; + } - return names; - } + public string GetDescription () + { + return "Splits CSV files into columns.\r\n\r\nCredits:\r\nThis Columnizer uses the CsvHelper. https://github.com/JoshClose/CsvHelper. \r\n"; + } + + public int GetColumnCount () + { + return _isValidCsv ? _columnList.Count : 1; + } - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + public string[] GetColumnNames () + { + var names = new string[GetColumnCount()]; + if (_isValidCsv) { - if (_isValidCsv) + var i = 0; + foreach (CsvColumn column in _columnList) { - return SplitCsvLine(line); + names[i++] = column.Name; } - - return CreateColumnizedLogLine(line); } - - private static ColumnizedLogLine CreateColumnizedLogLine(ILogLine line) + else { - ColumnizedLogLine cLogLine = new ColumnizedLogLine(); - cLogLine.LogLine = line; - cLogLine.ColumnValues = new IColumn[] { new Column { FullValue = line.FullLine, Parent = cLogLine } }; - return cLogLine; + names[0] = "Text"; } - public bool IsTimeshiftImplemented() - { - return false; - } + return names; + } - public void SetTimeOffset(int msecOffset) + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) + { + if (_isValidCsv) { - throw new NotImplementedException(); + return SplitCsvLine(line); } - public int GetTimeOffset() - { - throw new NotImplementedException(); - } + return CreateColumnizedLogLine(line); + } - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + private static ColumnizedLogLine CreateColumnizedLogLine (ILogLine line) + { + ColumnizedLogLine cLogLine = new() { - throw new NotImplementedException(); - } + LogLine = line + }; + cLogLine.ColumnValues = [new Column { FullValue = line.FullLine, Parent = cLogLine }]; + return cLogLine; + } - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - throw new NotImplementedException(); - } + public bool IsTimeshiftImplemented () + { + return false; + } + + public void SetTimeOffset (int msecOffset) + { + throw new NotImplementedException(); + } + + public int GetTimeOffset () + { + throw new NotImplementedException(); + } + + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) + { + throw new NotImplementedException(); + } - public void Selected(ILogLineColumnizerCallback callback) + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + throw new NotImplementedException(); + } + + public void Selected (ILogLineColumnizerCallback callback) + { + if (_isValidCsv) // see PreProcessLine() { - if (_isValidCsv) // see PreProcessLine() + _columnList.Clear(); + ILogLine line = _config.HasFieldNames ? _firstLine : callback.GetLogLine(0); + + if (line != null) { - _columnList.Clear(); - ILogLine line = _config.HasFieldNames ? _firstLine : callback.GetLogLine(0); + using CsvReader csv = new(new StringReader(line.FullLine), _config.ReaderConfiguration); + csv.Read(); + csv.ReadHeader(); + + var fieldCount = csv.Parser.Count; - if (line != null) + var headerRecord = csv.HeaderRecord; + + if (_config.HasFieldNames && headerRecord != null) + { + foreach (var headerColumn in headerRecord) + { + _columnList.Add(new CsvColumn(headerColumn)); + } + } + else { - using (CsvReader csv = new CsvReader(new StringReader(line.FullLine), _config.ReaderConfiguration)) + for (var i = 0; i < fieldCount; ++i) { - csv.Read(); - csv.ReadHeader(); - - int fieldCount = csv.Parser.Count; - - string[] headerRecord = csv.HeaderRecord; - - if (_config.HasFieldNames && headerRecord != null) - { - foreach (string headerColumn in headerRecord) - { - _columnList.Add(new CsvColumn(headerColumn)); - } - } - else - { - for (int i = 0; i < fieldCount; ++i) - { - _columnList.Add(new CsvColumn("Column " + i + 1)); - } - } + _columnList.Add(new CsvColumn("Column " + i + 1)); } } } } + } - public void DeSelected(ILogLineColumnizerCallback callback) - { - // nothing to do - } + public void DeSelected (ILogLineColumnizerCallback callback) + { + // nothing to do + } + + public void Configure (ILogLineColumnizerCallback callback, string configDir) + { + var configPath = configDir + "\\" + CONFIGFILENAME; + FileInfo fileInfo = new(configPath); - public void Configure(ILogLineColumnizerCallback callback, string configDir) + CsvColumnizerConfigDlg dlg = new(_config); + + if (dlg.ShowDialog() == DialogResult.OK) { - string configPath = configDir + "\\" + _configFileName; - FileInfo fileInfo = new FileInfo(configPath); + _config.VersionBuild = Assembly.GetExecutingAssembly().GetName().Version.Build; - CsvColumnizerConfigDlg dlg = new CsvColumnizerConfigDlg(_config); - if (dlg.ShowDialog() == DialogResult.OK) + using (StreamWriter sw = new(fileInfo.Create())) { - _config.VersionBuild = Assembly.GetExecutingAssembly().GetName().Version.Build; - - using (StreamWriter sw = new StreamWriter(fileInfo.Create())) - { - JsonSerializer serializer = new JsonSerializer(); - serializer.Serialize(sw, _config); - } + JsonSerializer serializer = new(); + serializer.Serialize(sw, _config); + } - _config.ConfigureReaderConfiguration(); + _config.ConfigureReaderConfiguration(); - Selected(callback); - } + Selected(callback); } + } - public void LoadConfig(string configDir) - { - string configPath = Path.Combine(configDir, _configFileName); + public void LoadConfig (string configDir) + { + var configPath = Path.Combine(configDir, CONFIGFILENAME); - if (!File.Exists(configPath)) + if (!File.Exists(configPath)) + { + _config = new CsvColumnizerConfig(); + _config.InitDefaults(); + } + else + { + try { - _config = new CsvColumnizerConfig(); - _config.InitDefaults(); + _config = JsonConvert.DeserializeObject(File.ReadAllText(configPath)); + _config.ConfigureReaderConfiguration(); } - else + catch (Exception e) { - try - { - _config = JsonConvert.DeserializeObject(File.ReadAllText(configPath)); - _config.ConfigureReaderConfiguration(); - } - catch (Exception e) - { - MessageBox.Show($"Error while deserializing config data: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); - _config = new CsvColumnizerConfig(); - _config.InitDefaults(); - } + MessageBox.Show($"Error while deserializing config data: {e.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + _config = new CsvColumnizerConfig(); + _config.InitDefaults(); } } + } - public Priority GetPriority(string fileName, IEnumerable samples) - { - Priority result = Priority.NotSupport; - - if (fileName.EndsWith("csv", StringComparison.OrdinalIgnoreCase)) - { - result = Priority.CanSupport; - } + public Priority GetPriority (string fileName, IEnumerable samples) + { + Priority result = Priority.NotSupport; - return result; + if (fileName.EndsWith("csv", StringComparison.OrdinalIgnoreCase)) + { + result = Priority.CanSupport; } - #endregion + return result; + } - #region Private Methods + #endregion - private IColumnizedLogLine SplitCsvLine(ILogLine line) - { - ColumnizedLogLine cLogLine = new ColumnizedLogLine(); - cLogLine.LogLine = line; - - using (CsvReader csv = new CsvReader(new StringReader(line.FullLine), _config.ReaderConfiguration)) - { - csv.Read(); - csv.ReadHeader(); + #region Private Methods - //we only read line by line and not the whole file so it is always the header - string[] records = csv.HeaderRecord; + private IColumnizedLogLine SplitCsvLine (ILogLine line) + { + ColumnizedLogLine cLogLine = new() + { + LogLine = line + }; - if (records != null) - { - List columns = new List(); + using CsvReader csv = new(new StringReader(line.FullLine), _config.ReaderConfiguration); + csv.Read(); + csv.ReadHeader(); - foreach (string record in records) - { - columns.Add(new Column { FullValue = record, Parent = cLogLine }); - } + //we only read line by line and not the whole file so it is always the header + var records = csv.HeaderRecord; - cLogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); - } + if (records != null) + { + List columns = []; - return cLogLine; + foreach (var record in records) + { + columns.Add(new Column { FullValue = record, Parent = cLogLine }); } + + cLogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); } - #endregion + return cLogLine; } + + #endregion } \ No newline at end of file diff --git a/src/CsvColumnizer/CsvColumnizer.csproj b/src/CsvColumnizer/CsvColumnizer.csproj index 070afa9e..4e54cc43 100644 --- a/src/CsvColumnizer/CsvColumnizer.csproj +++ b/src/CsvColumnizer/CsvColumnizer.csproj @@ -2,45 +2,21 @@ net8.0-windows true - Library - false - false + true true - false $(SolutionDir)..\bin\$(Configuration)\plugins true + CsvColumnizer - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + - - - Key.snk - - + - - CsvColumnizer - +
diff --git a/src/CsvColumnizer/CsvColumnizerConfig.cs b/src/CsvColumnizer/CsvColumnizerConfig.cs index b0ef0d5d..e2841bcf 100644 --- a/src/CsvColumnizer/CsvColumnizerConfig.cs +++ b/src/CsvColumnizer/CsvColumnizerConfig.cs @@ -1,68 +1,69 @@ -using System; -using System.Globalization; -using CsvHelper.Configuration; +using CsvHelper.Configuration; + using Newtonsoft.Json; -namespace CsvColumnizer +using System; +using System.Globalization; + +namespace CsvColumnizer; + +[Serializable] +public class CsvColumnizerConfig { - [Serializable] - public class CsvColumnizerConfig - { - #region Fields + #region Fields + + public char CommentChar { get; set; } + + public string DelimiterChar { get; set; } - public char CommentChar { get; set; } + public char EscapeChar { get; set; } - public string DelimiterChar { get; set; } - - public char EscapeChar { get; set; } - - public bool HasFieldNames { get; set; } - - public int MinColumns { get; set; } - - public char QuoteChar { get; set; } + public bool HasFieldNames { get; set; } - public int VersionBuild { get; set; } + public int MinColumns { get; set; } - [JsonIgnore] - public IReaderConfiguration ReaderConfiguration { get; set; } + public char QuoteChar { get; set; } - #endregion + public int VersionBuild { get; set; } - #region Public methods + [JsonIgnore] + public IReaderConfiguration ReaderConfiguration { get; set; } - public void InitDefaults() + #endregion + + #region Public methods + + public void InitDefaults() + { + ReaderConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture) { - ReaderConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture) - { - Delimiter = ";", - Escape = '"', - Quote = '"', - Comment = '#', - HasHeaderRecord = true, - TrimOptions = TrimOptions.None - }; - - DelimiterChar = ReaderConfiguration.Delimiter; - EscapeChar = ReaderConfiguration.Escape; - QuoteChar = ReaderConfiguration.Quote; - CommentChar = ReaderConfiguration.Comment; - HasFieldNames = ReaderConfiguration.HasHeaderRecord; - MinColumns = 0; - } - - public void ConfigureReaderConfiguration() + Delimiter = ";", + Escape = '"', + Quote = '"', + Comment = '#', + HasHeaderRecord = true, + TrimOptions = TrimOptions.None + }; + + DelimiterChar = ReaderConfiguration.Delimiter; + EscapeChar = ReaderConfiguration.Escape; + QuoteChar = ReaderConfiguration.Quote; + CommentChar = ReaderConfiguration.Comment; + HasFieldNames = ReaderConfiguration.HasHeaderRecord; + MinColumns = 0; + } + + public void ConfigureReaderConfiguration() + { + ReaderConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture) { - ReaderConfiguration = new CsvConfiguration(CultureInfo.InvariantCulture) - { - Delimiter = DelimiterChar, - Escape = EscapeChar, - Quote = QuoteChar, - Comment = CommentChar, - HasHeaderRecord = HasFieldNames - }; - } - - #endregion + Delimiter = DelimiterChar, + Escape = EscapeChar, + Quote = QuoteChar, + Comment = CommentChar, + HasHeaderRecord = HasFieldNames + }; } + + #endregion } \ No newline at end of file diff --git a/src/CsvColumnizer/CsvColumnizerConfigDlg.cs b/src/CsvColumnizer/CsvColumnizerConfigDlg.cs index 4c2fd0ab..61d421f9 100644 --- a/src/CsvColumnizer/CsvColumnizerConfigDlg.cs +++ b/src/CsvColumnizer/CsvColumnizerConfigDlg.cs @@ -2,71 +2,70 @@ using System.Drawing; using System.Windows.Forms; -namespace CsvColumnizer -{ - public partial class CsvColumnizerConfigDlg : Form - { - #region Fields +namespace CsvColumnizer; - private readonly CsvColumnizerConfig _config; +public partial class CsvColumnizerConfigDlg : Form +{ + #region Fields - #endregion + private readonly CsvColumnizerConfig _config; - #region cTor + #endregion - public CsvColumnizerConfigDlg(CsvColumnizerConfig config) - { - SuspendLayout(); - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; + #region cTor - _config = config; - InitializeComponent(); - FillValues(); - ResumeLayout(); - } + public CsvColumnizerConfigDlg(CsvColumnizerConfig config) + { + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + _config = config; + InitializeComponent(); + FillValues(); + ResumeLayout(); + } - #endregion + #endregion - #region Private Methods + #region Private Methods - private void FillValues() - { - delimiterTextBox.Text = _config.DelimiterChar; - textBoxQuoteChar.Text = _config.QuoteChar.ToString(); - textboxEscapeChar.Text = _config.EscapeChar.ToString(); - checkBoxEscape.Checked = _config.EscapeChar != '\0'; - textBoxCommentChar.Text = _config.CommentChar.ToString(); - checkBoxFieldNames.Checked = _config.HasFieldNames; - textboxEscapeChar.Enabled = checkBoxEscape.Checked; - numericUpDownMinColumns.Value = _config.MinColumns; - } + private void FillValues() + { + delimiterTextBox.Text = _config.DelimiterChar; + textBoxQuoteChar.Text = _config.QuoteChar.ToString(); + textboxEscapeChar.Text = _config.EscapeChar.ToString(); + checkBoxEscape.Checked = _config.EscapeChar != '\0'; + textBoxCommentChar.Text = _config.CommentChar.ToString(); + checkBoxFieldNames.Checked = _config.HasFieldNames; + textboxEscapeChar.Enabled = checkBoxEscape.Checked; + numericUpDownMinColumns.Value = _config.MinColumns; + } - private void RetrieveValues() - { - _config.DelimiterChar = delimiterTextBox.Text; - _config.QuoteChar = textBoxQuoteChar.Text[0]; - _config.EscapeChar = checkBoxEscape.Checked ? textboxEscapeChar.Text[0] : '\0'; - _config.CommentChar = textBoxCommentChar.Text[0]; - _config.HasFieldNames = checkBoxFieldNames.Checked; - _config.MinColumns = (int)numericUpDownMinColumns.Value; - } + private void RetrieveValues() + { + _config.DelimiterChar = delimiterTextBox.Text; + _config.QuoteChar = textBoxQuoteChar.Text[0]; + _config.EscapeChar = checkBoxEscape.Checked ? textboxEscapeChar.Text[0] : '\0'; + _config.CommentChar = textBoxCommentChar.Text[0]; + _config.HasFieldNames = checkBoxFieldNames.Checked; + _config.MinColumns = (int)numericUpDownMinColumns.Value; + } - #endregion + #endregion - #region Events handler + #region Events handler - private void OnOkButtonClick(object sender, EventArgs e) - { - RetrieveValues(); - } + private void OnOkButtonClick(object sender, EventArgs e) + { + RetrieveValues(); + } - private void OnEscapeCheckBoxCheckedChanged(object sender, EventArgs e) - { - textboxEscapeChar.Enabled = checkBoxEscape.Checked; - } + private void OnEscapeCheckBoxCheckedChanged(object sender, EventArgs e) + { + textboxEscapeChar.Enabled = checkBoxEscape.Checked; + } - #endregion + #endregion - } } \ No newline at end of file diff --git a/src/CsvColumnizer/CsvLogLine.cs b/src/CsvColumnizer/CsvLogLine.cs index f2d3917e..8187a496 100644 --- a/src/CsvColumnizer/CsvLogLine.cs +++ b/src/CsvColumnizer/CsvLogLine.cs @@ -1,24 +1,16 @@ using LogExpert; -namespace CsvColumnizer -{ - public class CsvLogLine : ILogLine - { - public CsvLogLine(string fullLine, int lineNumber) - { - FullLine = fullLine; - LineNumber = lineNumber; - } - - #region Properties +namespace CsvColumnizer; - public string FullLine { get; set; } +public class CsvLogLine(string fullLine, int lineNumber) : ILogLine +{ + #region Properties - public int LineNumber { get; set; } + public string FullLine { get; set; } = fullLine; - string ITextValue.Text => FullLine; + public int LineNumber { get; set; } = lineNumber; - #endregion - } + string ITextValue.Text => FullLine; + #endregion } \ No newline at end of file diff --git a/src/CsvColumnizer/Properties/AssemblyInfo.cs b/src/CsvColumnizer/Properties/AssemblyInfo.cs deleted file mode 100644 index d689fe35..00000000 --- a/src/CsvColumnizer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("d939a82b-591f-4403-9c9b-7d1f54043019")] \ No newline at end of file diff --git a/src/DefaultPlugins/DefaultPlugins.csproj b/src/DefaultPlugins/DefaultPlugins.csproj index d3c7b1c6..20255a67 100644 --- a/src/DefaultPlugins/DefaultPlugins.csproj +++ b/src/DefaultPlugins/DefaultPlugins.csproj @@ -1,41 +1,14 @@  - net8.0-windows - true - Library - false - LogExpert - false - true - true - false + net8.0 + $(SolutionDir)..\bin\$(Configuration)\plugins - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + - - - Key.snk - - + diff --git a/src/DefaultPlugins/Eminus.cs b/src/DefaultPlugins/Eminus.cs deleted file mode 100644 index d062fd5a..00000000 --- a/src/DefaultPlugins/Eminus.cs +++ /dev/null @@ -1,286 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Xml; -using System.Windows.Forms; -using System.Net.Sockets; -using System.IO; -using System.Runtime.Serialization; -using Newtonsoft.Json; -using System.Runtime.Versioning; - -[assembly: SupportedOSPlatform("windows")] -namespace LogExpert -{ - public class Eminus : IContextMenuEntry, ILogExpertPluginConfigurator - { - #region Fields - - private const string CFG_FILE_NAME = "eminus.json"; - private const string dot = "."; - private const string doubleDot = ":"; - private EminusConfig _config = new(); - private EminusConfigDlg dlg; - private EminusConfig tmpConfig = new(); - - #endregion - - #region Properties - - public string Text - { - get { return "eminus"; } - } - - #endregion - - #region Private Methods - - private XmlDocument BuildParam(ILogLine line) - { - string temp = line.FullLine; - // no Java stacktrace but some special logging of our applications at work: - if (temp.Contains("Exception of type", StringComparison.CurrentCulture) || temp.Contains("Nested:", StringComparison.CurrentCulture)) - { - int pos = temp.IndexOf("created in "); - if (pos == -1) - { - return null; - } - - pos += "created in ".Length; - int endPos = temp.IndexOf(dot, pos); - - if (endPos == -1) - { - return null; - } - - string className = temp[pos..endPos]; - pos = temp.IndexOf(doubleDot, pos); - - if (pos == -1) - { - return null; - } - - string lineNum = temp[(pos + 1)..]; - XmlDocument doc = BuildXmlDocument(className, lineNum); - return doc; - } - - if (temp.Contains("at ", StringComparison.CurrentCulture)) - { - string str = temp.Trim(); - string className = null; - string lineNum = null; - int pos = str.IndexOf("at ") + 3; - str = str[pos..]; // remove 'at ' - int idx = str.IndexOfAny(['(', '$', '<']); - - if (idx != -1) - { - if (str[idx] == '$') - { - className = str[..idx]; - } - else - { - pos = str.LastIndexOf('.', idx); - if (pos == -1) - { - return null; - } - className = str[..pos]; - } - - idx = str.LastIndexOf(':'); - - if (idx == -1) - { - return null; - } - - pos = str.IndexOf(')', idx); - - if (pos == -1) - { - return null; - } - - lineNum = str.Substring(idx + 1, pos - idx - 1); - } - /* - * - - - - - - - */ - - XmlDocument doc = BuildXmlDocument(className, lineNum); - return doc; - } - return null; - } - - private XmlDocument BuildXmlDocument(string className, string lineNum) - { - XmlDocument xmlDoc = new(); - xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); - XmlElement rootElement = xmlDoc.CreateElement("eminus"); - xmlDoc.AppendChild(rootElement); - rootElement.SetAttribute("authKey", _config.password); - - XmlElement loadElement = xmlDoc.CreateElement("loadclass"); - loadElement.SetAttribute("mode", "dialog"); - rootElement.AppendChild(loadElement); - - XmlElement elemClassName = xmlDoc.CreateElement("classname"); - XmlElement elemLineNum = xmlDoc.CreateElement("linenumber"); - elemClassName.InnerText = className; - elemLineNum.InnerText = lineNum; - loadElement.AppendChild(elemClassName); - loadElement.AppendChild(elemLineNum); - return xmlDoc; - } - - #endregion - - #region IContextMenuEntry Member - - public string GetMenuText(IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) - { - if (logLines.Count == 1 && BuildParam(callback.GetLogLine(logLines[0])) != null) - { - return "Load class in Eclipse"; - } - else - { - return "_Load class in Eclipse"; - } - } - - public void MenuSelected(IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) - { - if (logLines.Count != 1) - { - return; - } - - XmlDocument doc = BuildParam(callback.GetLogLine(logLines[0])); - if (doc == null) - { - MessageBox.Show("Cannot parse Java stack trace line", "LogExpert"); - } - else - { - try - { - TcpClient client = new(_config.host, _config.port); - NetworkStream stream = client.GetStream(); - StreamWriter writer = new(stream); - doc.Save(writer); - writer.Flush(); - stream.Flush(); - writer.Close(); - stream.Close(500); - client.Close(); - } - catch (Exception e) - { - MessageBox.Show(e.Message, "LogExpert"); - } - } - } - - #endregion - - - #region ILogExpertPluginConfigurator Member - - public void LoadConfig(string configDir) - { - string configPath = configDir + CFG_FILE_NAME; - - FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + CFG_FILE_NAME); - - if (!File.Exists(configPath)) - { - _config = new EminusConfig(); - } - else - { - try - { - _config = JsonConvert.DeserializeObject(File.ReadAllText($"{fileInfo.FullName}")); - } - catch (SerializationException e) - { - MessageBox.Show(e.Message, "Deserialize"); - _config = new EminusConfig(); - } - } - } - - - public void SaveConfig(string configDir) - { - FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + CFG_FILE_NAME); - - dlg?.ApplyChanges(); - - _config = tmpConfig.Clone(); - - using StreamWriter sw = new(fileInfo.Create()); - JsonSerializer serializer = new(); - serializer.Serialize(sw, _config); - } - - public bool HasEmbeddedForm() - { - return true; - } - - public void ShowConfigForm(object panel) - { - dlg = new EminusConfigDlg(tmpConfig); - dlg.Parent = (Panel)panel; - dlg.Show(); - } - - /// - /// Implemented only for demonstration purposes. This function is called when the config button - /// is pressed (HasEmbeddedForm() must return false for this). - /// - /// - public void ShowConfigDialog(object owner) - { - dlg = new EminusConfigDlg(tmpConfig); - dlg.TopLevel = true; - dlg.Owner = (Form)owner; - dlg.ShowDialog(); - dlg.ApplyChanges(); - } - - - public void HideConfigForm() - { - if (dlg != null) - { - dlg.ApplyChanges(); - dlg.Hide(); - dlg.Dispose(); - dlg = null; - } - } - - public void StartConfig() - { - tmpConfig = _config.Clone(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/DefaultPlugins/EminusConfig.cs b/src/DefaultPlugins/EminusConfig.cs deleted file mode 100644 index 5bfa22f6..00000000 --- a/src/DefaultPlugins/EminusConfig.cs +++ /dev/null @@ -1,29 +0,0 @@ -using System; - -namespace LogExpert -{ - [Serializable] - public class EminusConfig - { - #region Fields - - public string host = "127.0.0.1"; - public string password = ""; - public int port = 12345; - - #endregion - - #region Public methods - - public EminusConfig Clone() - { - EminusConfig config = new(); - config.host = host; - config.port = port; - config.password = password; - return config; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/DefaultPlugins/EminusConfigDlg.cs b/src/DefaultPlugins/EminusConfigDlg.cs deleted file mode 100644 index d1464a96..00000000 --- a/src/DefaultPlugins/EminusConfigDlg.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Windows.Forms; - -namespace LogExpert -{ - public partial class EminusConfigDlg : Form - { - #region Fields - - #endregion - - #region cTor - - public EminusConfigDlg(EminusConfig config) - { - InitializeComponent(); - TopLevel = false; - Config = config; - - hostTextBox.Text = config.host; - portTextBox.Text = "" + config.port; - passwordTextBox.Text = config.password; - } - - #endregion - - #region Properties - - public EminusConfig Config { get; set; } - - #endregion - - #region Public methods - - public void ApplyChanges() - { - Config.host = hostTextBox.Text; - try - { - Config.port = short.Parse(portTextBox.Text); - } - catch (FormatException) - { - Config.port = 0; - } - Config.password = passwordTextBox.Text; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/DefaultPlugins/ProcessLauncher.cs b/src/DefaultPlugins/ProcessLauncher.cs index 0d916765..e2527955 100644 --- a/src/DefaultPlugins/ProcessLauncher.cs +++ b/src/DefaultPlugins/ProcessLauncher.cs @@ -1,77 +1,79 @@ -using System; +using System; using System.Diagnostics; -namespace LogExpert +namespace LogExpert; + +internal class ProcessLauncher : IKeywordAction { - public class ProcessLauncher : IKeywordAction - { - #region Properties + #region Properties - public string Text => GetName(); + public string Text => GetName(); - #endregion + #endregion - #region IKeywordAction Member + #region IKeywordAction Member - private readonly object _callbackLock = new object(); + private readonly object _callbackLock = new(); + + public void Execute (string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer) + { + var start = 0; + int end; - public void Execute(string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer) + if (param.StartsWith('"')) { - int start = 0; - int end = 0; - if (param.StartsWith("\"")) - { - start = 1; - end = param.IndexOf("\"", start, StringComparison.Ordinal); - } - else - { - end = param.IndexOf(" ", StringComparison.Ordinal); - } - if (end == -1) - { - end = param.Length; - } - string procName = param.Substring(start, end - start); - - lock(_callbackLock) - { - string parameters = param.Substring(end).Trim(); - parameters = parameters.Replace("%F", callback.GetFileName()); - parameters = parameters.Replace("%K", keyword); - - int lineNumber = callback.GetLineNum(); //Line Numbers start at 0, but are displayed (+1) - string logline = callback.GetLogLine(lineNumber).FullLine; - parameters = parameters.Replace("%L", string.Empty + lineNumber); - parameters = parameters.Replace("%T", callback.GetTabTitle()); - parameters = parameters.Replace("%C", logline); - - Process explorer = new Process(); - explorer.StartInfo.FileName = procName; - explorer.StartInfo.Arguments = parameters; - explorer.StartInfo.UseShellExecute = false; - explorer.Start(); - } + start = 1; + end = param.IndexOf('"', start); + } + else + { + end = param.IndexOf(' ', StringComparison.Ordinal); } - public string GetName() + if (end == -1) { - return "ProcessLauncher keyword plugin"; + end = param.Length; } + var procName = param[start..end]; - public string GetDescription() + lock (_callbackLock) { - return "Launches an external process. The plugin's parameter is the process name " + - "and its (optional) command line.\r\n" + - "Use the following variables for command line replacements:\r\n" + - "%F = Log file name (full path)\r\n" + - "%T = Tab title\r\n" + - "%L = Line number of keyword hit\r\n" + - "%K = Keyword\r\n" + - "%C = Complete line content"; + var parameters = param[end..].Trim(); + parameters = parameters.Replace("%F", callback.GetFileName(), StringComparison.Ordinal); + parameters = parameters.Replace("%K", keyword, StringComparison.Ordinal); + + var lineNumber = callback.LineNum; //Line Numbers start at 0, but are displayed (+1) + var logline = callback.GetLogLine(lineNumber).FullLine; + parameters = parameters.Replace("%L", string.Empty + lineNumber, System.StringComparison.Ordinal); + parameters = parameters.Replace("%T", callback.GetTabTitle(), StringComparison.Ordinal); + parameters = parameters.Replace("%C", logline, StringComparison.Ordinal); + + Process explorer = new(); + explorer.StartInfo.FileName = procName; + explorer.StartInfo.Arguments = parameters; + explorer.StartInfo.UseShellExecute = false; + explorer.Start(); } + } - #endregion + public string GetName () + { + return "ProcessLauncher keyword plugin"; } + + + public string GetDescription () + { + return "Launches an external process. The plugin's parameter is the process name " + + "and its (optional) command line.\r\n" + + "Use the following variables for command line replacements:\r\n" + + "%F = Log file name (full path)\r\n" + + "%T = Tab title\r\n" + + "%L = Line number of keyword hit\r\n" + + "%K = Keyword\r\n" + + "%C = Complete line content"; + } + + #endregion } \ No newline at end of file diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 11a29ac4..76e48ec8 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -1,10 +1,55 @@ - 8.2.0 - 2.0.0.0 - 2.0.0.0 - 2.0.0.0-rc1 + 1.20.0.0 + 1.20.0.0 + 1.20.0.0 + 1.20.0.0 Hirogen, zarunbal, RandallFlagg, TheNicker Log Expert - - \ No newline at end of file + enable + enable + false + false + ..\Solution Items\Key.snk + false + Properties + LogExpert + false + + true + true + LogExpert + Copyright © LogExpert 2025 + false + false + false + false + + LogExpert + + LogExpert is a Windows tail program (a GUI replacement for the Unix tail command). + + Summary of (most) features: + + * Tail mode + * MDI-Interface with Tabs + * Search function (including RegEx) + * Bookmarks + * A very flexible filter view and possibility to filter to tab + * Highlighting lines via search criteria + * Triggers (e.g. create Bookmark or execute a plugin) via search criteria + * Columnizers: Plugins which split log lines into columns + * Unicode support + * log4j XML file support + * 3rd party plugin support + * Plugin API for more log file data sources + +
+ + + + + + + + diff --git a/src/Directory.Packages.props b/src/Directory.Packages.props index 95be07a3..d357ea89 100644 --- a/src/Directory.Packages.props +++ b/src/Directory.Packages.props @@ -5,27 +5,22 @@ $(NoWarn);NU1507 - - - - - - - - - - + + + + + - - - + + + - + - - - + + + \ No newline at end of file diff --git a/src/FlashIconHighlighter/FlashIconHighlighter.csproj b/src/FlashIconHighlighter/FlashIconHighlighter.csproj index cc54b3b7..50489d9a 100644 --- a/src/FlashIconHighlighter/FlashIconHighlighter.csproj +++ b/src/FlashIconHighlighter/FlashIconHighlighter.csproj @@ -1,39 +1,16 @@  + net8.0-windows true - Library - false - false true true - false $(SolutionDir)..\bin\$(Configuration)\plugins + true - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + - - - Key.snk - - - + diff --git a/src/FlashIconHighlighter/FlashIconPlugin.cs b/src/FlashIconHighlighter/FlashIconPlugin.cs index 9572b4d9..fdf4e2f3 100644 --- a/src/FlashIconHighlighter/FlashIconPlugin.cs +++ b/src/FlashIconHighlighter/FlashIconPlugin.cs @@ -1,60 +1,57 @@ -using LogExpert; - using System; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Windows.Forms; +using LogExpert; + [assembly: SupportedOSPlatform("windows")] -namespace FlashIconHighlighter +namespace FlashIconHighlighter; + +internal class FlashIconPlugin : IKeywordAction { - internal class FlashIconPlugin : IKeywordAction - { - #region Properties + #region Properties - public string Text - { - get { return GetName(); } - } + public string Text => GetName(); - #endregion + #endregion - #region IKeywordAction Member + #region IKeywordAction Member - public void Execute(string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer) + public void Execute (string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer) + { + FormCollection openForms = Application.OpenForms; + foreach (Form form in openForms) { - FormCollection openForms = Application.OpenForms; - foreach (Form form in openForms) + if (form.TopLevel && form.Name.Equals("LogTabWindow", StringComparison.OrdinalIgnoreCase) && form.Text.Contains(callback.GetFileName(), StringComparison.Ordinal)) { - if (form.TopLevel && form.Name.Equals("LogTabWindow") && form.Text.Contains(callback.GetFileName())) - { - form.BeginInvoke(FlashWindow, [form]); - } + form.BeginInvoke(FlashWindow, [form]); } } + } - private void FlashWindow(Form form) + private void FlashWindow (Form form) + { + FLASHWINFO fw = new() { - FLASHWINFO fw = new FLASHWINFO(); + cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(FLASHWINFO))), + hwnd = form.Handle, + dwFlags = 14, + uCount = 0 + }; - fw.cbSize = Convert.ToUInt32(Marshal.SizeOf(typeof(FLASHWINFO))); - fw.hwnd = form.Handle; - fw.dwFlags = 14; - fw.uCount = 0; - - Win32Stuff.FlashWindowEx(ref fw); - } - - public string GetDescription() - { - return "Let the taskbar icon flash "; - } + Win32Stuff.FlashWindowEx(ref fw); + } - public string GetName() - { - return "Flash Icon"; - } + public string GetDescription () + { + return "Let the taskbar icon flash "; + } - #endregion + public string GetName () + { + return "Flash Icon"; } + + #endregion } \ No newline at end of file diff --git a/src/FlashIconHighlighter/Win32Stuff.cs b/src/FlashIconHighlighter/Win32Stuff.cs index e807a59b..bc68f3c0 100644 --- a/src/FlashIconHighlighter/Win32Stuff.cs +++ b/src/FlashIconHighlighter/Win32Stuff.cs @@ -1,32 +1,28 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Runtime.InteropServices; -namespace FlashIconHighlighter -{ - /* - * Flash stuff stolen from http://blogs.x2line.com/al/archive/2008/04/19/3392.aspx - */ +namespace FlashIconHighlighter; - [StructLayout(LayoutKind.Sequential)] - public struct FLASHWINFO - { - public uint cbSize; - public IntPtr hwnd; - public int dwFlags; - public uint uCount; - public int dwTimeout; - } +/* + * Flash stuff stolen from http://blogs.x2line.com/al/archive/2008/04/19/3392.aspx + */ +[StructLayout(LayoutKind.Sequential)] +public struct FLASHWINFO +{ + public uint cbSize; + public IntPtr hwnd; + public int dwFlags; + public uint uCount; + public int dwTimeout; +} - public class Win32Stuff - { - #region Public methods +public partial class Win32Stuff +{ + #region Public methods - [DllImport("user32.dll")] - public static extern int FlashWindowEx(ref FLASHWINFO pwfi); + [LibraryImport("user32.dll")] + public static partial int FlashWindowEx(ref FLASHWINFO pwfi); - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/GlassfishColumnizer/GlassFishLogLine.cs b/src/GlassfishColumnizer/GlassFishLogLine.cs new file mode 100644 index 00000000..284b4073 --- /dev/null +++ b/src/GlassfishColumnizer/GlassFishLogLine.cs @@ -0,0 +1,16 @@ +using LogExpert; + +namespace GlassfishColumnizer; + +internal class GlassFishLogLine : ILogLine +{ + #region Properties + + public string FullLine { get; set; } + + public int LineNumber { get; set; } + + string ITextValue.Text => FullLine; + + #endregion +} \ No newline at end of file diff --git a/src/GlassfishColumnizer/GlassfishColumnizer.cs b/src/GlassfishColumnizer/GlassfishColumnizer.cs index a498e8d5..d80cc0c9 100644 --- a/src/GlassfishColumnizer/GlassfishColumnizer.cs +++ b/src/GlassfishColumnizer/GlassfishColumnizer.cs @@ -1,244 +1,215 @@ -using System; -using System.Collections.Generic; -using System.Text; -using LogExpert; +using System; using System.Globalization; using System.Linq; -namespace GlassfishColumnizer +using LogExpert; + +namespace GlassfishColumnizer; + +internal class GlassfishColumnizer : ILogLineXmlColumnizer { - internal class XmlConfig : IXmlLogConfiguration - { - #region Properties + #region Fields - public string XmlStartTag { get; } = "[#|"; + public const int COLUMN_COUNT = 2; + private const string DATETIME_FORMAT = "yyyy-MM-ddTHH:mm:ss.fffzzzz"; + private const string DATETIME_FORMAT_OUT = "yyyy-MM-dd HH:mm:ss.fff"; + private const char separatorChar = '|'; - public string XmlEndTag { get; } = "|#]"; + private static readonly XmlConfig xmlConfig = new(); - public string Stylesheet { get; } = null; + private readonly char[] trimChars = ['|']; + private readonly CultureInfo cultureInfo = new("en-US"); + private int timeOffset; - public string[] Namespace => null; + #endregion - #endregion - } + #region cTor - internal class GlassfishColumnizer : ILogLineXmlColumnizer + public GlassfishColumnizer () { - #region Fields - - public const int COLUMN_COUNT = 2; - protected const string DATETIME_FORMAT = "yyyy-MM-ddTHH:mm:ss.fffzzzz"; - protected const string DATETIME_FORMAT_OUT = "yyyy-MM-dd HH:mm:ss.fff"; + } - private static readonly XmlConfig xmlConfig = new XmlConfig(); - private readonly char separatorChar = '|'; - private readonly char[] trimChars = new char[] {'|'}; - protected CultureInfo cultureInfo = new CultureInfo("en-US"); - protected int timeOffset = 0; + #endregion - #endregion + #region Public methods - #region cTor + public IXmlLogConfiguration GetXmlLogConfiguration () + { + return xmlConfig; + } - public GlassfishColumnizer() + public ILogLine GetLineTextForClipboard (ILogLine logLine, ILogLineColumnizerCallback callback) + { + GlassFishLogLine line = new() { - } + FullLine = logLine.FullLine.Replace(separatorChar, '|'), + LineNumber = logLine.LineNumber + }; - #endregion + return line; + } - #region Public methods + public string GetName () + { + return "Classfish"; + } - public IXmlLogConfiguration GetXmlLogConfiguration() - { - return xmlConfig; - } + public string GetDescription () + { + return "Parse the timestamps in Glassfish logfiles."; + } - public ILogLine GetLineTextForClipboard(ILogLine logLine, ILogLineColumnizerCallback callback) - { - GlassFishLogLine line = new GlassFishLogLine - { - FullLine = logLine.FullLine.Replace(separatorChar, '|'), - LineNumber = logLine.LineNumber - }; + public int GetColumnCount () + { + return COLUMN_COUNT; + } - return line; - } + public string[] GetColumnNames () + { + return ["Date/Time", "Message"]; + } - public string GetName() - { - return "Classfish"; - } + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) + { + ColumnizedLogLine cLogLine = new(); + cLogLine.LogLine = line; + + var temp = line.FullLine; - public string GetDescription() + Column[] columns = Column.CreateColumns(COLUMN_COUNT, cLogLine); + cLogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); + + // delete '[#|' and '|#]' + if (temp.StartsWith("[#|")) { - return "Parse the timestamps in Glassfish logfiles."; + temp = temp[3..]; } - public int GetColumnCount() + if (temp.EndsWith("|#]")) { - return COLUMN_COUNT; + temp = temp[..^3]; } - public string[] GetColumnNames() + // If the line is too short (i.e. does not follow the format for this columnizer) return the whole line content + // in colum 8 (the log message column). Date and time column will be left blank. + if (temp.Length < 28) { - return new string[] {"Date/Time", "Message"}; + columns[1].FullValue = temp; } - - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + else { - ColumnizedLogLine cLogLine = new ColumnizedLogLine(); - cLogLine.LogLine = line; - - string temp = line.FullLine; - - Column[] columns = Column.CreateColumns(COLUMN_COUNT, cLogLine); - cLogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); - - // delete '[#|' and '|#]' - if (temp.StartsWith("[#|")) + try { - temp = temp.Substring(3); - } + DateTime dateTime = GetTimestamp(callback, line); + if (dateTime == DateTime.MinValue) + { + columns[1].FullValue = temp; + } - if (temp.EndsWith("|#]")) + var newDate = dateTime.ToString(DATETIME_FORMAT_OUT); + columns[0].FullValue = newDate; + } + catch (Exception) { - temp = temp.Substring(0, temp.Length - 3); + columns[0].FullValue = "n/a"; } - // If the line is too short (i.e. does not follow the format for this columnizer) return the whole line content - // in colum 8 (the log message column). Date and time column will be left blank. - if (temp.Length < 28) + Column timestmp = columns[0]; + + string[] cols; + cols = temp.Split(trimChars, COLUMN_COUNT, StringSplitOptions.None); + + if (cols.Length != COLUMN_COUNT) { + columns[0].FullValue = string.Empty; columns[1].FullValue = temp; } else { - try - { - DateTime dateTime = GetTimestamp(callback, line); - if (dateTime == DateTime.MinValue) - { - columns[1].FullValue = temp; - } - - string newDate = dateTime.ToString(DATETIME_FORMAT_OUT); - columns[0].FullValue = newDate; - } - catch (Exception) - { - columns[0].FullValue = "n/a"; - } + columns[0] = timestmp; + columns[1].FullValue = cols[1]; + } + } + + return cLogLine; + } - Column timestmp = columns[0]; + public bool IsTimeshiftImplemented () + { + return true; + } - string[] cols; - cols = temp.Split(trimChars, COLUMN_COUNT, StringSplitOptions.None); + public void SetTimeOffset (int msecOffset) + { + timeOffset = msecOffset; + } - if (cols.Length != COLUMN_COUNT) - { - columns[0].FullValue = string.Empty; - columns[1].FullValue = temp; - } - else - { - columns[0] = timestmp; - columns[1].FullValue = cols[1]; - } - } + public int GetTimeOffset () + { + return timeOffset; + } - return cLogLine; - } + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine logLine) + { + var temp = logLine.FullLine; - public bool IsTimeshiftImplemented() + // delete '[#|' and '|#]' + if (temp.StartsWith("[#|")) { - return true; + temp = temp[3..]; } - public void SetTimeOffset(int msecOffset) + if (temp.EndsWith("|#]")) { - timeOffset = msecOffset; + temp = temp[..^3]; } - public int GetTimeOffset() + if (temp.Length < 28) { - return timeOffset; + return DateTime.MinValue; } - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine logLine) + var endIndex = temp.IndexOf(separatorChar, 1); + if (endIndex > 28 || endIndex < 0) { - string temp = logLine.FullLine; - - // delete '[#|' and '|#]' - if (temp.StartsWith("[#|")) - { - temp = temp.Substring(3); - } - - if (temp.EndsWith("|#]")) - { - temp = temp.Substring(0, temp.Length - 3); - } + return DateTime.MinValue; + } - if (temp.Length < 28) - { - return DateTime.MinValue; - } + var value = temp[..endIndex]; - int endIndex = temp.IndexOf(separatorChar, 1); - if (endIndex > 28 || endIndex < 0) + try + { + // convert glassfish timestamp into a readable format: + if (DateTime.TryParseExact(value, DATETIME_FORMAT, cultureInfo, DateTimeStyles.None, out DateTime timestamp)) { - return DateTime.MinValue; + return timestamp.AddMilliseconds(timeOffset); } - string value = temp.Substring(0, endIndex); + return DateTime.MinValue; + } + catch (Exception) + { + return DateTime.MinValue; + } + } + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + if (column == 0) + { try { - // convert glassfish timestamp into a readable format: - if (DateTime.TryParseExact(value, DATETIME_FORMAT, cultureInfo, DateTimeStyles.None, out DateTime timestamp)) - { - return timestamp.AddMilliseconds(timeOffset); - } - - return DateTime.MinValue; + var newDateTime = DateTime.ParseExact(value, DATETIME_FORMAT_OUT, cultureInfo); + var oldDateTime = DateTime.ParseExact(oldValue, DATETIME_FORMAT_OUT, cultureInfo); + var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; + var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; + timeOffset = (int)(mSecsNew - mSecsOld); } - catch (Exception) - { - return DateTime.MinValue; - } - } - - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - if (column == 0) + catch (FormatException) { - try - { - DateTime newDateTime = DateTime.ParseExact(value, DATETIME_FORMAT_OUT, cultureInfo); - DateTime oldDateTime = DateTime.ParseExact(oldValue, DATETIME_FORMAT_OUT, cultureInfo); - long mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; - long mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - timeOffset = (int) (mSecsNew - mSecsOld); - } - catch (FormatException) - { - } } } - - #endregion - - private class GlassFishLogLine : ILogLine - { - #region Properties - - public string FullLine { get; set; } - - public int LineNumber { get; set; } - - string ITextValue.Text => FullLine; - - #endregion - } } + + #endregion } \ No newline at end of file diff --git a/src/GlassfishColumnizer/GlassfishColumnizer.csproj b/src/GlassfishColumnizer/GlassfishColumnizer.csproj index c9928ba1..23bf3af2 100644 --- a/src/GlassfishColumnizer/GlassfishColumnizer.csproj +++ b/src/GlassfishColumnizer/GlassfishColumnizer.csproj @@ -1,39 +1,14 @@  - net8.0-windows - Library - false - false - false + net8.0 + $(SolutionDir)..\bin\$(Configuration)\plugins + GlassfishColumnizer + Glassfish logfile support for LogExpert - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + - - - Key.snk - - - - GlassfishColumnizer - Glassfish logfile support for LogExpert - + diff --git a/src/GlassfishColumnizer/Properties/AssemblyInfo.cs b/src/GlassfishColumnizer/Properties/AssemblyInfo.cs deleted file mode 100644 index 3346c8f5..00000000 --- a/src/GlassfishColumnizer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("ffea3945-9d17-476d-b565-268f0700704c")] \ No newline at end of file diff --git a/src/GlassfishColumnizer/XmlConfig.cs b/src/GlassfishColumnizer/XmlConfig.cs new file mode 100644 index 00000000..925be273 --- /dev/null +++ b/src/GlassfishColumnizer/XmlConfig.cs @@ -0,0 +1,18 @@ +using LogExpert; + +namespace GlassfishColumnizer; + +internal class XmlConfig : IXmlLogConfiguration +{ + #region Properties + + public string XmlStartTag { get; } = "[#|"; + + public string XmlEndTag { get; } = "|#]"; + + public string Stylesheet { get; } + + public string[] GetNamespaceDeclaration () => null; + + #endregion +} \ No newline at end of file diff --git a/src/JsonColumnizer/JsonColumn.cs b/src/JsonColumnizer/JsonColumn.cs new file mode 100644 index 00000000..5ac9ed9e --- /dev/null +++ b/src/JsonColumnizer/JsonColumn.cs @@ -0,0 +1,10 @@ +namespace JsonColumnizer; + +public class JsonColumn(string name) +{ + #region Properties + + public string Name { get; } = name; + + #endregion +} \ No newline at end of file diff --git a/src/JsonColumnizer/JsonColumnizer.cs b/src/JsonColumnizer/JsonColumnizer.cs index 712377fd..48dacfea 100644 --- a/src/JsonColumnizer/JsonColumnizer.cs +++ b/src/JsonColumnizer/JsonColumnizer.cs @@ -1,247 +1,221 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; + using LogExpert; + using Newtonsoft.Json; using Newtonsoft.Json.Linq; -namespace JsonColumnizer +namespace JsonColumnizer; + +/// +/// This Columnizer can parse JSON files. +/// +public class JsonColumnizer : ILogLineColumnizer, IInitColumnizer, IColumnizerPriority { - public class JsonColumn - { - #region cTor + #region Properties - public JsonColumn(string name) - { - Name = name; - } + public HashSet ColumnSet { get; set; } = []; - #endregion + protected IList ColumnList { get; } = new List([InitialColumn]); - #region Properties + protected static JsonColumn InitialColumn { get; } = new JsonColumn("Text"); - public string Name { get; } + #endregion - #endregion - } + #region Public methods - /// - /// This Columnizer can parse JSON files. - /// - public class JsonColumnizer : ILogLineColumnizer, IInitColumnizer, IColumnizerPriority + public virtual void Selected (ILogLineColumnizerCallback callback) { - #region Fields - - private static readonly JsonColumn _initialColumn = new JsonColumn("Text"); - - private readonly IList _columnList = new List(new[] {InitialColumn}); - - #endregion - - #region Properties - - public HashSet ColumnSet { get; set; } = new HashSet(); - - protected IList ColumnList => _columnList; + ColumnList.Clear(); + ColumnSet.Clear(); - protected static JsonColumn InitialColumn => _initialColumn; + ILogLine line = callback.GetLogLine(0); - #endregion - - #region Public methods - - public virtual void Selected(ILogLineColumnizerCallback callback) + if (line != null) { - ColumnList.Clear(); - ColumnSet.Clear(); - - var line = callback.GetLogLine(0); - - if (line != null) + JObject json = ParseJson(line); + if (json != null) { - var json = ParseJson(line); - if (json != null) - { - var fieldCount = json.Properties().Count(); + var fieldCount = json.Properties().Count(); - for (var i = 0; i < fieldCount; ++i) + for (var i = 0; i < fieldCount; ++i) + { + var columeName = json.Properties().ToArray()[i].Name; + if (ColumnSet.Add(columeName)) { - var columeName = json.Properties().ToArray()[i].Name; - if (!ColumnSet.Contains(columeName)) - { - ColumnSet.Add(columeName); - ColumnList.Add(new JsonColumn(columeName)); - } + ColumnList.Add(new JsonColumn(columeName)); } } - else - { - ColumnSet.Add("Text"); - ColumnList.Add(InitialColumn); - } } - - if (ColumnList.Count() == 0) + else { - ColumnSet.Add("Text"); + _ = ColumnSet.Add("Text"); ColumnList.Add(InitialColumn); } } - public virtual void DeSelected(ILogLineColumnizerCallback callback) + if (ColumnList.Count == 0) { - // nothing to do + _ = ColumnSet.Add("Text"); + ColumnList.Add(InitialColumn); } + } - public virtual string GetName() - { - return "JSON Columnizer"; - } + public virtual void DeSelected (ILogLineColumnizerCallback callback) + { + // nothing to do + } - public virtual string GetDescription() + public virtual string GetName () + { + return "JSON Columnizer"; + } + + public virtual string GetDescription () + { + return "Splits JSON files into columns.\r\n\r\nCredits:\r\nThis Columnizer uses the Newtonsoft json package.\r\n\r\nFirst line must be valid or else only one column will be displayed and the other values dropped!"; + } + + public virtual int GetColumnCount () + { + return ColumnList.Count; + } + + public virtual string[] GetColumnNames () + { + var names = new string[GetColumnCount()]; + var i = 0; + foreach (JsonColumn column in ColumnList) { - return "Splits JSON files into columns.\r\n\r\nCredits:\r\nThis Columnizer uses the Newtonsoft json package.\r\n\r\nFirst line must be valid or else only one column will be displayed and the other values dropped!"; + names[i++] = column.Name; } - public virtual int GetColumnCount() + return names; + } + + public virtual IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) + { + JObject json = ParseJson(line); + + if (json != null) { - return ColumnList.Count; + return SplitJsonLine(line, json); } - public virtual string[] GetColumnNames() - { - string[] names = new string[GetColumnCount()]; - int i = 0; - foreach (var column in ColumnList) - { - names[i++] = column.Name; - } + var cLogLine = new ColumnizedLogLine { LogLine = line }; - return names; - } + Column[] columns = Column.CreateColumns(ColumnList.Count, cLogLine); - public virtual IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) - { - JObject json = ParseJson(line); + columns.Last().FullValue = line.FullLine; - if (json != null) - { - return SplitJsonLine(line, json); - } + cLogLine.ColumnValues = columns.Select(a => (IColumn)a).ToArray(); - var cLogLine = new ColumnizedLogLine {LogLine = line}; + return cLogLine; + } - var columns = Column.CreateColumns(ColumnList.Count, cLogLine); + public virtual bool IsTimeshiftImplemented () + { + return false; + } - columns.Last().FullValue = line.FullLine; + public virtual void SetTimeOffset (int msecOffset) + { + throw new NotImplementedException(); + } - cLogLine.ColumnValues = columns.Select(a => (IColumn) a).ToArray(); + public virtual int GetTimeOffset () + { + throw new NotImplementedException(); + } - return cLogLine; - } + public virtual DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) + { + throw new NotImplementedException(); + } - public virtual bool IsTimeshiftImplemented() - { - return false; - } + public virtual void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + throw new NotImplementedException(); + } - public virtual void SetTimeOffset(int msecOffset) + public virtual Priority GetPriority (string fileName, IEnumerable samples) + { + Priority result = Priority.NotSupport; + if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) { - throw new NotImplementedException(); + result = Priority.WellSupport; } - public virtual int GetTimeOffset() - { - throw new NotImplementedException(); - } + return result; + } - public virtual DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) - { - throw new NotImplementedException(); - } + #endregion - public virtual void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - throw new NotImplementedException(); - } + #region Private Methods - public virtual Priority GetPriority(string fileName, IEnumerable samples) + protected static JObject ParseJson (ILogLine line) + { + return JsonConvert.DeserializeObject(line.FullLine, new JsonSerializerSettings() { - Priority result = Priority.NotSupport; - if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) - { - result = Priority.WellSupport; - } + Error = (sender, args) => { args.ErrorContext.Handled = true; } //We ignore the error and handle the null value + }); + } - return result; - } + public class ColumnWithName : Column + { + public string ColumnName { get; set; } + } - #endregion + // + // Following two log lines should be loaded and displayed in correct grid. + // {"time":"2019-02-13T02:55:35.5186240Z","message":"Hosting starting"} + // {"time":"2019-02-13T02:55:35.5186240Z","level":"warning", "message":"invalid host."} + // + protected virtual IColumnizedLogLine SplitJsonLine (ILogLine line, JObject json) + { + var cLogLine = new ColumnizedLogLine { LogLine = line }; - #region Private Methods + var columns = json.Properties().Select(property => new ColumnWithName { FullValue = property.Value.ToString(), ColumnName = property.Name.ToString(), Parent = cLogLine }).ToList(); - protected static JObject ParseJson(ILogLine line) + foreach (ColumnWithName jsonColumn in columns) { - return JsonConvert.DeserializeObject(line.FullLine, new JsonSerializerSettings() + // When find new column in a log line, add a new column in the end of the list. + if (!ColumnSet.Contains(jsonColumn.ColumnName)) { - Error = (sender, args) => { args.ErrorContext.Handled = true; } //We ignore the error and handle the null value - }); - } + if (ColumnList.Count == 1 && !ColumnSet.Contains(ColumnList[0].Name)) + { + ColumnList.Clear(); + } - public class ColumnWithName : Column - { - public string ColumneName { get; set; } + _ = ColumnSet.Add(jsonColumn.ColumnName); + ColumnList.Add(new JsonColumn(jsonColumn.ColumnName)); + } } // - // Following two log lines should be loaded and displayed in correct grid. - // {"time":"2019-02-13T02:55:35.5186240Z","message":"Hosting starting"} - // {"time":"2019-02-13T02:55:35.5186240Z","level":"warning", "message":"invalid host."} + // Always rearrage the order of all json fields within a line to follow the sequence of columnNameList. + // This will make sure the log line displayed correct even the order of json fields changed. // - protected virtual IColumnizedLogLine SplitJsonLine(ILogLine line, JObject json) + List returnColumns = []; + foreach (JsonColumn column in ColumnList) { - var cLogLine = new ColumnizedLogLine {LogLine = line}; - - var columns = json.Properties().Select(property => new ColumnWithName {FullValue = property.Value.ToString(), ColumneName = property.Name.ToString(), Parent = cLogLine}).ToList(); - - foreach (var jsonColumn in columns) + ColumnWithName existingColumn = columns.Find(x => x.ColumnName == column.Name); + if (existingColumn != null) { - // When find new column in a log line, add a new column in the end of the list. - if (!ColumnSet.Contains(jsonColumn.ColumneName)) - { - if (ColumnList.Count == 1 && !ColumnSet.Contains(ColumnList[0].Name)) - { - ColumnList.Clear(); - } - - ColumnSet.Add(jsonColumn.ColumneName); - ColumnList.Add(new JsonColumn(jsonColumn.ColumneName)); - } - } - - // - // Always rearrage the order of all json fields within a line to follow the sequence of columnNameList. - // This will make sure the log line displayed correct even the order of json fields changed. - // - List returnColumns = new List(); - foreach (var column in ColumnList) - { - var existingColumn = columns.Find(x => x.ColumneName == column.Name); - if (existingColumn != null) - { - returnColumns.Add(new Column() {FullValue = existingColumn.FullValue, Parent = cLogLine}); - continue; - } - - // Fields that is missing in current line should be shown as empty. - returnColumns.Add(new Column() {FullValue = "", Parent = cLogLine}); + returnColumns.Add(new Column() { FullValue = existingColumn.FullValue, Parent = cLogLine }); + continue; } - cLogLine.ColumnValues = returnColumns.ToArray(); - - return cLogLine; + // Fields that is missing in current line should be shown as empty. + returnColumns.Add(new Column() { FullValue = "", Parent = cLogLine }); } - #endregion + cLogLine.ColumnValues = [.. returnColumns]; + + return cLogLine; } + + #endregion } \ No newline at end of file diff --git a/src/JsonColumnizer/JsonColumnizer.csproj b/src/JsonColumnizer/JsonColumnizer.csproj index ffcc325e..0092f405 100644 --- a/src/JsonColumnizer/JsonColumnizer.csproj +++ b/src/JsonColumnizer/JsonColumnizer.csproj @@ -1,44 +1,17 @@  - net8.0-windows - true - Library - false - false - true - true - false + net8.0 + $(SolutionDir)..\bin\$(Configuration)\plugins + JsonColumnizer - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + - - - Key.snk - - - - JsonColumnizer - + + diff --git a/src/JsonColumnizer/Properties/AssemblyInfo.cs b/src/JsonColumnizer/Properties/AssemblyInfo.cs deleted file mode 100644 index 113a680e..00000000 --- a/src/JsonColumnizer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("4C0B11AE-BCAF-492C-AFE7-53C9B79148BE")] \ No newline at end of file diff --git a/src/JsonCompactColumnizer/JsonCompactColumnizer.cs b/src/JsonCompactColumnizer/JsonCompactColumnizer.cs index 3630087c..5cc3b33d 100644 --- a/src/JsonCompactColumnizer/JsonCompactColumnizer.cs +++ b/src/JsonCompactColumnizer/JsonCompactColumnizer.cs @@ -1,119 +1,120 @@ -using LogExpert; -using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; -namespace JsonColumnizer +using LogExpert; + +using Newtonsoft.Json.Linq; + +namespace JsonColumnizer; + +/// +/// This Columnizer can parse JSON files. +/// +public class JsonCompactColumnizer : JsonColumnizer, IColumnizerPriority { - /// - /// This Columnizer can parse JSON files. - /// - public class JsonCompactColumnizer : JsonColumnizer, IColumnizerPriority + #region Public methods + + public override string GetName () { - #region Public methods + return "JSON Compact Columnizer"; + } - public override string GetName() - { - return "JSON Compact Columnizer"; - } + public override string GetDescription () + { + return "A JSON columnier for Serilog.Formatting.Compact format."; + } - public override string GetDescription() + public override void Selected (ILogLineColumnizerCallback callback) + { + ColumnList.Clear(); + // Create column header with cached column list. + + foreach (var col in TagDict.Keys) { - return "A JSON columnier for Serilog.Formatting.Compact format."; + ColumnList.Add(new JsonColumn(TagDict[col])); } + } - public override void Selected(ILogLineColumnizerCallback callback) + public override Priority GetPriority (string fileName, IEnumerable samples) + { + Priority result = Priority.NotSupport; + if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) { - ColumnList.Clear(); - // Create column header with cached column list. - - foreach (var col in _tagDict.Keys) - { - ColumnList.Add(new JsonColumn(_tagDict[col])); - } + result = Priority.WellSupport; } - public override Priority GetPriority(string fileName, IEnumerable samples) + if (samples != null && samples.Any()) { - Priority result = Priority.NotSupport; - if (fileName.EndsWith("json", StringComparison.OrdinalIgnoreCase)) + try { - result = Priority.WellSupport; - } - - if (samples != null && samples.Count() > 0) - { - try + var line = samples.First(); + JObject json = ParseJson(line); + if (json != null) { - var line = samples.First(); - JObject json = ParseJson(line); - if (json != null) + var columns = SplitJsonLine(samples.First(), json); + if (columns.ColumnValues.Length > 0 && Array.Exists(columns.ColumnValues, x => !string.IsNullOrEmpty(x.FullValue))) { - var columns = SplitJsonLine(samples.First(), json); - if (columns.ColumnValues.Count() > 0 && Array.Exists(columns.ColumnValues, x => !string.IsNullOrEmpty(x.FullValue))) - { - result = Priority.PerfectlySupport; - } + result = Priority.PerfectlySupport; } } - catch (Exception) - { - // Ignore errors when determine priority. - } } - - return result; + catch (Exception) + { + // Ignore errors when determine priority. + } } - #endregion + return result; + } - #region Private Methods + #endregion - protected Dictionary _tagDict = new Dictionary() - { - {"@t", "Timestamp"}, - {"@l", "Level"}, - {"@m", "Message"}, - {"@x", "Exception"}, - {"@i", "Event id"}, - {"@r", "Renderings"}, - {"@mt", "Message Template"}, - }; - - protected override IColumnizedLogLine SplitJsonLine(ILogLine line, JObject json) - { - List returnColumns = new List(); - var cLogLine = new ColumnizedLogLine {LogLine = line}; + #region Private Methods - var columns = json.Properties().Select(property => new ColumnWithName {FullValue = property.Value.ToString(), ColumneName = property.Name.ToString(), Parent = cLogLine}).ToList(); + protected Dictionary TagDict { get; set; } = new() + { + {"@t", "Timestamp"}, + {"@l", "Level"}, + {"@m", "Message"}, + {"@x", "Exception"}, + {"@i", "Event id"}, + {"@r", "Renderings"}, + {"@mt", "Message Template"}, + }; + + protected override IColumnizedLogLine SplitJsonLine (ILogLine line, JObject json) + { + List returnColumns = []; + var cLogLine = new ColumnizedLogLine { LogLine = line }; - // - // Always rearrage the order of all json fields within a line to follow the sequence of columnNameList. - // This will make sure the log line displayed correct even the order of json fields changed. - // - foreach (var column in _tagDict.Keys) - { - if (column.StartsWith("@")) - { - var existingColumn = columns.Find(x => x.ColumneName == column); + var columns = json.Properties().Select(property => new ColumnWithName { FullValue = property.Value.ToString(), ColumnName = property.Name.ToString(), Parent = cLogLine }).ToList(); - if (existingColumn != null) - { - returnColumns.Add(new Column() {FullValue = existingColumn.FullValue, Parent = cLogLine}); - continue; - } + // + // Always rearrage the order of all json fields within a line to follow the sequence of columnNameList. + // This will make sure the log line displayed correct even the order of json fields changed. + // + foreach (var column in TagDict.Keys) + { + if (column.StartsWith('@')) + { + ColumnWithName existingColumn = columns.Find(x => x.ColumnName == column); - // Fields that is missing in current line should be shown as empty. - returnColumns.Add(new Column() {FullValue = "", Parent = cLogLine}); + if (existingColumn != null) + { + returnColumns.Add(new Column() { FullValue = existingColumn.FullValue, Parent = cLogLine }); + continue; } - } - - cLogLine.ColumnValues = returnColumns.ToArray(); - return cLogLine; + // Fields that is missing in current line should be shown as empty. + returnColumns.Add(new Column() { FullValue = "", Parent = cLogLine }); + } } - #endregion + cLogLine.ColumnValues = [.. returnColumns]; + + return cLogLine; } + + #endregion } \ No newline at end of file diff --git a/src/JsonCompactColumnizer/JsonCompactColumnizer.csproj b/src/JsonCompactColumnizer/JsonCompactColumnizer.csproj index 67cae4d8..48c72fcc 100644 --- a/src/JsonCompactColumnizer/JsonCompactColumnizer.csproj +++ b/src/JsonCompactColumnizer/JsonCompactColumnizer.csproj @@ -1,45 +1,17 @@  - net8.0-windows - true - Library - false + net8.0 + JsonColumnizer - false - true - true - false $(SolutionDir)..\bin\$(Configuration)\plugins + JsonCompactColumnizer - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + - - - Key.snk - - - - JsonCompactColumnizer - + diff --git a/src/JsonCompactColumnizer/Properties/AssemblyInfo.cs b/src/JsonCompactColumnizer/Properties/AssemblyInfo.cs deleted file mode 100644 index 47c642d5..00000000 --- a/src/JsonCompactColumnizer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("6D5A3E51-4D0F-452E-8A86-DDCC313F3A7F")] \ No newline at end of file diff --git a/src/Log4jXmlColumnizer/Log4JLogLine.cs b/src/Log4jXmlColumnizer/Log4JLogLine.cs new file mode 100644 index 00000000..616a1939 --- /dev/null +++ b/src/Log4jXmlColumnizer/Log4JLogLine.cs @@ -0,0 +1,16 @@ +using LogExpert; + +namespace Log4jXmlColumnizer; + +internal class Log4JLogLine : ILogLine +{ + #region Properties + + public string FullLine { get; set; } + + public int LineNumber { get; set; } + + string ITextValue.Text => FullLine; + + #endregion +} \ No newline at end of file diff --git a/src/Log4jXmlColumnizer/Log4jColumnEntry.cs b/src/Log4jXmlColumnizer/Log4jColumnEntry.cs new file mode 100644 index 00000000..ad0e4f39 --- /dev/null +++ b/src/Log4jXmlColumnizer/Log4jColumnEntry.cs @@ -0,0 +1,18 @@ +using System; + +namespace Log4jXmlColumnizer; + +/// +/// Helper class for configuration of the columns. +/// +[Serializable] +public class Log4jColumnEntry(string name, int index, int maxLen) +{ + public int ColumnIndex { get; set; } = index; + + public string ColumnName { get; set; } = name; + + public int MaxLen { get; set; } = maxLen; + + public bool Visible { get; set; } +} \ No newline at end of file diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs index 88e66fc2..0d8833a3 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.cs @@ -1,5 +1,3 @@ -using Newtonsoft.Json; - using System; using System.Collections.Generic; using System.Globalization; @@ -9,455 +7,304 @@ using System.Runtime.Versioning; using System.Windows.Forms; -[assembly: SupportedOSPlatform("windows")] -namespace LogExpert -{ - /// - /// XMl configuration for parsing log4j XML files. The XSL will transform every block of log entries - /// into text lines. The fields in the text lines are separated by a special character (0xFFFD). - /// The special character will be used in the Split() function of the columnizer to split the line - /// into columns. - /// - internal class XmlConfig : IXmlLogConfiguration - { - #region Properties +using LogExpert; - public string XmlStartTag { get; } = "" + - "" + - "" + - "" + - "" + - ""; +public class Log4jXmlColumnizer : ILogLineXmlColumnizer, IColumnizerConfigurator, IColumnizerPriority +{ + #region Fields - public string[] Namespace - { - get { return ["log4j", "http://jakarta.apache.org/log4j"]; } - } + public const int COLUMN_COUNT = 9; + protected const string DATETIME_FORMAT = "dd.MM.yyyy HH:mm:ss.fff"; - #endregion - } + private static readonly XmlConfig xmlConfig = new(); + private const char separatorChar = '\xFFFD'; + private readonly char[] trimChars = ['\xFFFD']; + private Log4jXmlColumnizerConfig _config; + private readonly CultureInfo _cultureInfo = new("de-DE"); + private int _timeOffset; + #endregion - /// - /// Helper class for configuration of the colums. - /// - [Serializable] - public class Log4jColumnEntry - { - #region Fields + #region cTor - public int columnIndex; + public Log4jXmlColumnizer () + { + _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); + } - public string columnName; - public int maxLen; - public bool visible; + #endregion - #endregion + #region Public methods - #region cTor + public IXmlLogConfiguration GetXmlLogConfiguration () + { + return xmlConfig; + } - public Log4jColumnEntry(string name, int index, int maxLen) + public ILogLine GetLineTextForClipboard (ILogLine logLine, ILogLineColumnizerCallback callback) + { + Log4JLogLine line = new() { - columnName = name; - columnIndex = index; - visible = true; - this.maxLen = maxLen; - } + FullLine = logLine.FullLine.Replace(separatorChar, '|'), + LineNumber = logLine.LineNumber + }; - #endregion + return line; } - [Serializable] - public class Log4jXmlColumnizerConfig + public string GetName () { - #region Fields - - public List columnList = new(); - public bool localTimestamps = true; + return "Log4j XML"; + } - #endregion + public string GetDescription () + { + return "Reads and formats XML log files written with log4j."; + } - #region cTor + public int GetColumnCount () + { + return _config.ActiveColumnCount; + } - public Log4jXmlColumnizerConfig(string[] columnNames) - { - FillDefaults(columnNames); - } + public string[] GetColumnNames () + { + return _config.ActiveColumnNames; + } - #endregion + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) + { + ColumnizedLogLine clogLine = new(); + clogLine.LogLine = line; - #region Properties + Column[] columns = Column.CreateColumns(COLUMN_COUNT, clogLine); - /// - /// Returns the column count. Because the user can deactivate columns in the config - /// the actual column count may be smaller than the number of available columns. - /// - public int ActiveColumnCount + // If the line is too short (i.e. does not follow the format for this columnizer) return the whole line content + // in colum 8 (the log message column). Date and time column will be left blank. + if (line.FullLine.Length < 15) { - get - { - int count = 0; - foreach (Log4jColumnEntry entry in columnList) - { - if (entry.visible) - { - count++; - } - } - return count; - } + columns[8].FullValue = line.FullLine; } - - /// - /// Returns the names of all active columns. - /// - public string[] ActiveColumnNames + else { - get + try { - string[] names = new string[ActiveColumnCount]; - int index = 0; - foreach (Log4jColumnEntry entry in columnList) + DateTime dateTime = GetTimestamp(callback, line); + + if (dateTime == DateTime.MinValue) { - if (entry.visible) - { - names[index++] = entry.columnName; - } + columns[8].FullValue = line.FullLine; } - return names; - } - } - - #endregion - #region Public methods - - public void FillDefaults(string[] columnNames) - { - columnList.Clear(); - for (int i = 0; i < columnNames.Length; ++i) - { - columnList.Add(new Log4jColumnEntry(columnNames[i], i, 0)); + var newDate = dateTime.ToString(DATETIME_FORMAT); + columns[0].FullValue = newDate; } - } - - #endregion - } - - - public class Log4jXmlColumnizer : ILogLineXmlColumnizer, IColumnizerConfigurator, IColumnizerPriority - { - #region Fields - - public const int COLUMN_COUNT = 9; - protected const string DATETIME_FORMAT = "dd.MM.yyyy HH:mm:ss.fff"; - - private static readonly XmlConfig xmlConfig = new(); - private readonly char separatorChar = '\xFFFD'; - private readonly char[] trimChars = ['\xFFFD']; - private Log4jXmlColumnizerConfig _config; - protected CultureInfo cultureInfo = new("de-DE"); - protected int timeOffset = 0; - - #endregion - - #region cTor - - public Log4jXmlColumnizer() - { - _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); - } - - #endregion - - #region Public methods - - public IXmlLogConfiguration GetXmlLogConfiguration() - { - return xmlConfig; - } - - public ILogLine GetLineTextForClipboard(ILogLine logLine, ILogLineColumnizerCallback callback) - { - Log4JLogLine line = new() + catch (Exception) { - FullLine = logLine.FullLine.Replace(separatorChar, '|'), - LineNumber = logLine.LineNumber - }; - - return line; - } - - public string GetName() - { - return "Log4j XML"; - } - - public string GetDescription() - { - return "Reads and formats XML log files written with log4j."; - } - - public int GetColumnCount() - { - return _config.ActiveColumnCount; - } - - public string[] GetColumnNames() - { - return _config.ActiveColumnNames; - } + columns[0].FullValue = "n/a"; + } - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) - { - ColumnizedLogLine clogLine = new(); - clogLine.LogLine = line; + Column timestmp = columns[0]; - Column[] columns = Column.CreateColumns(COLUMN_COUNT, clogLine); + string[] cols; + cols = line.FullLine.Split(trimChars, COLUMN_COUNT, StringSplitOptions.None); - // If the line is too short (i.e. does not follow the format for this columnizer) return the whole line content - // in colum 8 (the log message column). Date and time column will be left blank. - if (line.FullLine.Length < 15) + if (cols.Length != COLUMN_COUNT) { + columns[0].FullValue = ""; + columns[1].FullValue = ""; + columns[2].FullValue = ""; + columns[3].FullValue = ""; + columns[4].FullValue = ""; + columns[5].FullValue = ""; + columns[6].FullValue = ""; + columns[7].FullValue = ""; columns[8].FullValue = line.FullLine; } else { - try - { - DateTime dateTime = GetTimestamp(callback, line); - - if (dateTime == DateTime.MinValue) - { - columns[8].FullValue = line.FullLine; - } + columns[0] = timestmp; - string newDate = dateTime.ToString(DATETIME_FORMAT); - columns[0].FullValue = newDate; - } - catch (Exception) + for (var i = 1; i < cols.Length; i++) { - columns[0].FullValue = "n/a"; + columns[i].FullValue = cols[i]; } + } + } - Column timestmp = columns[0]; - - string[] cols; - cols = line.FullLine.Split(trimChars, COLUMN_COUNT, StringSplitOptions.None); + Column[] filteredColumns = MapColumns(columns); - if (cols.Length != COLUMN_COUNT) - { - columns[0].FullValue = ""; - columns[1].FullValue = ""; - columns[2].FullValue = ""; - columns[3].FullValue = ""; - columns[4].FullValue = ""; - columns[5].FullValue = ""; - columns[6].FullValue = ""; - columns[7].FullValue = ""; - columns[8].FullValue = line.FullLine; - } - else - { - columns[0] = timestmp; + clogLine.ColumnValues = filteredColumns.Select(a => a as IColumn).ToArray(); - for (int i = 1; i < cols.Length; i++) - { - columns[i].FullValue = cols[i]; - } - } - } - Column[] filteredColumns = MapColumns(columns); + return clogLine; + } - clogLine.ColumnValues = filteredColumns.Select(a => a as IColumn).ToArray(); + public bool IsTimeshiftImplemented () + { + return true; + } - return clogLine; - } + public void SetTimeOffset (int msecOffset) + { + _timeOffset = msecOffset; + } + public int GetTimeOffset () + { + return _timeOffset; + } - public bool IsTimeshiftImplemented() + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) + { + if (line.FullLine.Length < 15) { - return true; + return DateTime.MinValue; } - public void SetTimeOffset(int msecOffset) - { - timeOffset = msecOffset; - } + var endIndex = line.FullLine.IndexOf(separatorChar, 1); - public int GetTimeOffset() + if (endIndex > 20 || endIndex < 0) { - return timeOffset; + return DateTime.MinValue; } + var value = line.FullLine.Substring(0, endIndex); - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + try { - if (line.FullLine.Length < 15) + // convert log4j timestamp into a readable format: + if (long.TryParse(value, out var timestamp)) { - return DateTime.MinValue; - } - - int endIndex = line.FullLine.IndexOf(separatorChar, 1); + // Add the time offset before returning + DateTime dateTime = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + dateTime = dateTime.AddMilliseconds(timestamp); - if (endIndex > 20 || endIndex < 0) - { - return DateTime.MinValue; - } - string value = line.FullLine.Substring(0, endIndex); - - try - { - // convert log4j timestamp into a readable format: - if (long.TryParse(value, out long timestamp)) + if (_config.LocalTimestamps) { - // Add the time offset before returning - DateTime dateTime = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - dateTime = dateTime.AddMilliseconds(timestamp); - - if (_config.localTimestamps) - { - dateTime = dateTime.ToLocalTime(); - } - return dateTime.AddMilliseconds(timeOffset); - } - else - { - return DateTime.MinValue; + dateTime = dateTime.ToLocalTime(); } + return dateTime.AddMilliseconds(_timeOffset); } - catch (Exception) + else { return DateTime.MinValue; } } + catch (Exception) + { + return DateTime.MinValue; + } + } - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + if (column == 0) { - if (column == 0) + try + { + var newDateTime = DateTime.ParseExact(value, DATETIME_FORMAT, _cultureInfo); + var oldDateTime = DateTime.ParseExact(oldValue, DATETIME_FORMAT, _cultureInfo); + var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; + var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; + _timeOffset = (int)(mSecsNew - mSecsOld); + } + catch (FormatException) { - try - { - DateTime newDateTime = DateTime.ParseExact(value, DATETIME_FORMAT, cultureInfo); - DateTime oldDateTime = DateTime.ParseExact(oldValue, DATETIME_FORMAT, cultureInfo); - long mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; - long mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - timeOffset = (int)(mSecsNew - mSecsOld); - } - catch (FormatException) - { - } } } + } - public void Configure(ILogLineColumnizerCallback callback, string configDir) - { - FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"); + public void Configure (ILogLineColumnizerCallback callback, string configDir) + { + FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"); - Log4jXmlColumnizerConfigDlg dlg = new(_config); + Log4jXmlColumnizerConfigDlg dlg = new(_config); - if (dlg.ShowDialog() == DialogResult.OK) - { - using StreamWriter sw = new(fileInfo.Create()); - JsonSerializer serializer = new(); - serializer.Serialize(sw, _config); - } + if (dlg.ShowDialog() == DialogResult.OK) + { + using StreamWriter sw = new(fileInfo.Create()); + JsonSerializer serializer = new(); + serializer.Serialize(sw, _config); } + } - public void LoadConfig(string configDir) - { - string configPath = configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"; + public void LoadConfig (string configDir) + { + var configPath = configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"; - FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"); + FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + "log4jxmlcolumnizer.json"); - if (!File.Exists(configPath)) - { - _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); - } - else + if (!File.Exists(configPath)) + { + _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); + } + else + { + try { - try - { - _config = JsonConvert.DeserializeObject(File.ReadAllText($"{fileInfo.FullName}")); - if (_config.columnList.Count < COLUMN_COUNT) - { - _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); - } - } - catch (SerializationException e) + _config = JsonConvert.DeserializeObject(File.ReadAllText($"{fileInfo.FullName}")); + if (_config.ColumnList.Count < COLUMN_COUNT) { - MessageBox.Show(e.Message, "Deserialize"); _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); } } - } - - public Priority GetPriority(string fileName, IEnumerable samples) - { - Priority result = Priority.NotSupport; - if (fileName.EndsWith("xml", StringComparison.OrdinalIgnoreCase)) + catch (SerializationException e) { - result = Priority.CanSupport; + MessageBox.Show(e.Message, "Deserialize"); + _config = new Log4jXmlColumnizerConfig(GetAllColumnNames()); } - return result; } + } - #endregion + public Priority GetPriority (string fileName, IEnumerable samples) + { + Priority result = Priority.NotSupport; + if (fileName.EndsWith("xml", StringComparison.OrdinalIgnoreCase)) + { + result = Priority.CanSupport; + } + return result; + } - #region Private Methods + #endregion - private string[] GetAllColumnNames() => ["Timestamp", "Level", "Logger", "Thread", "Class", "Method", "File", "Line", "Message"]; + #region Private Methods + private string[] GetAllColumnNames () => ["Timestamp", "Level", "Logger", "Thread", "Class", "Method", "File", "Line", "Message"]; - /// - /// Returns only the columns which are "active". The order of the columns depends on the column order in the config - /// - /// - /// - private Column[] MapColumns(Column[] cols) + /// + /// Returns only the columns which are "active". The order of the columns depends on the column order in the config + /// + /// + /// + private Column[] MapColumns (Column[] cols) + { + List output = []; + var index = 0; + foreach (Log4jColumnEntry entry in _config.ColumnList) { - List output = []; - int index = 0; - foreach (Log4jColumnEntry entry in _config.columnList) + if (entry.Visible) { - if (entry.visible) - { - Column column = cols[index]; - output.Add(column); + Column column = cols[index]; + output.Add(column); - if (entry.maxLen > 0 && column.FullValue.Length > entry.maxLen) - { - column.FullValue = column.FullValue.Substring(column.FullValue.Length - entry.maxLen); - } + if (entry.MaxLen > 0 && column.FullValue.Length > entry.MaxLen) + { + column.FullValue = column.FullValue[^entry.MaxLen..]; } - index++; } - - - return [.. output]; + index++; } - #endregion - - private class Log4JLogLine : ILogLine - { - #region Properties - - public string FullLine { get; set; } - - public int LineNumber { get; set; } - - string ITextValue.Text => FullLine; - #endregion - } + return [.. output]; } + + #endregion } \ No newline at end of file diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.csproj b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.csproj index 11231a69..3008beb6 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizer.csproj +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizer.csproj @@ -2,42 +2,20 @@ net8.0-windows true - Library - false - false + true true - false $(SolutionDir)..\bin\$(Configuration)\plugins - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + + - - - Key.snk - - + diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs new file mode 100644 index 00000000..3d070108 --- /dev/null +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfig.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; + +namespace Log4jXmlColumnizer; + +[Serializable] +public class Log4jXmlColumnizerConfig +{ + #region cTor + + public Log4jXmlColumnizerConfig (string[] columnNames) + { + FillDefaults(columnNames); + } + + #endregion + + #region Properties + + /// + /// Returns the column count. Because the user can deactivate columns in the config + /// the actual column count may be smaller than the number of available columns. + /// + public int ActiveColumnCount + { + get + { + var count = 0; + foreach (Log4jColumnEntry entry in ColumnList) + { + if (entry.Visible) + { + count++; + } + } + + return count; + } + } + + /// + /// Returns the names of all active columns. + /// + public string[] ActiveColumnNames + { + get + { + var names = new string[ActiveColumnCount]; + var index = 0; + foreach (Log4jColumnEntry entry in ColumnList) + { + if (entry.Visible) + { + names[index++] = entry.ColumnName; + } + } + + return names; + } + } + + public List ColumnList { get; set; } = []; + + public bool LocalTimestamps { get; set; } = true; + + #endregion + + #region Public methods + + public void FillDefaults (string[] columnNames) + { + ColumnList.Clear(); + for (var i = 0; i < columnNames.Length; ++i) + { + ColumnList.Add(new Log4jColumnEntry(columnNames[i], i, 0)); + } + } + + #endregion +} \ No newline at end of file diff --git a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs index fae1414d..00fc2a71 100644 --- a/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs +++ b/src/Log4jXmlColumnizer/Log4jXmlColumnizerConfigDlg.cs @@ -1,82 +1,83 @@ -using System; +using Log4jXmlColumnizer; + +using System; using System.Drawing; using System.Windows.Forms; -namespace LogExpert +namespace LogExpert; + +public partial class Log4jXmlColumnizerConfigDlg : Form { - public partial class Log4jXmlColumnizerConfigDlg : Form + #region Fields + + private readonly Log4jXmlColumnizerConfig _config; + + #endregion + + #region cTor + + public Log4jXmlColumnizerConfigDlg(Log4jXmlColumnizerConfig config) { - #region Fields + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + _config = config; + InitializeComponent(); + FillListBox(); + localTimeCheckBox.Checked = _config.LocalTimestamps; + ResumeLayout(); + } - private readonly Log4jXmlColumnizerConfig _config; + #endregion - #endregion + #region Private Methods - #region cTor + private void FillListBox() + { + var checkColumn = (DataGridViewCheckBoxColumn)columnGridView.Columns[0]; + var nameColumn = (DataGridViewTextBoxColumn)columnGridView.Columns[1]; + var lenColumn = (DataGridViewTextBoxColumn)columnGridView.Columns[2]; - public Log4jXmlColumnizerConfigDlg(Log4jXmlColumnizerConfig config) + foreach (Log4jColumnEntry entry in _config.ColumnList) { - SuspendLayout(); - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - _config = config; - InitializeComponent(); - FillListBox(); - localTimeCheckBox.Checked = _config.localTimestamps; - ResumeLayout(); + DataGridViewRow row = new(); + row.Cells.Add(new DataGridViewCheckBoxCell()); + row.Cells.Add(new DataGridViewTextBoxCell()); + row.Cells.Add(new DataGridViewTextBoxCell()); + row.Cells[0].Value = entry.Visible; + row.Cells[1].Value = entry.ColumnName; + row.Cells[2].Value = entry.MaxLen > 0 ? "" + entry.MaxLen : ""; + columnGridView.Rows.Add(row); } + } - #endregion + #endregion - #region Private Methods + #region Events handler - private void FillListBox() + private void OkButton_Click(object sender, EventArgs e) + { + // for (int i = 0; i < this.config.columnList.Count; ++i) + // { + // this.config.columnList[i]. visible = this.columnListBox.GetItemChecked(i); + // } + for (var i = 0; i < columnGridView.Rows.Count; ++i) { - DataGridViewCheckBoxColumn checkColumn = (DataGridViewCheckBoxColumn)columnGridView.Columns[0]; - DataGridViewTextBoxColumn nameColumn = (DataGridViewTextBoxColumn)columnGridView.Columns[1]; - DataGridViewTextBoxColumn lenColumn = (DataGridViewTextBoxColumn)columnGridView.Columns[2]; + _config.ColumnList[i].Visible = (bool)columnGridView.Rows[i].Cells[0].Value; + var sLen = (string)columnGridView.Rows[i].Cells[2].Value; - foreach (Log4jColumnEntry entry in _config.columnList) + if (int.TryParse(sLen, out var len)) { - DataGridViewRow row = new(); - row.Cells.Add(new DataGridViewCheckBoxCell()); - row.Cells.Add(new DataGridViewTextBoxCell()); - row.Cells.Add(new DataGridViewTextBoxCell()); - row.Cells[0].Value = entry.visible; - row.Cells[1].Value = entry.columnName; - row.Cells[2].Value = entry.maxLen > 0 ? "" + entry.maxLen : ""; - columnGridView.Rows.Add(row); + _config.ColumnList[i].MaxLen = len; } - } - - #endregion - - #region Events handler - - private void OkButton_Click(object sender, EventArgs e) - { - // for (int i = 0; i < this.config.columnList.Count; ++i) - // { - // this.config.columnList[i]. visible = this.columnListBox.GetItemChecked(i); - // } - for (int i = 0; i < columnGridView.Rows.Count; ++i) + else { - _config.columnList[i].visible = (bool)columnGridView.Rows[i].Cells[0].Value; - string sLen = (string)columnGridView.Rows[i].Cells[2].Value; - - if (int.TryParse(sLen, out int len)) - { - _config.columnList[i].maxLen = len; - } - else - { - _config.columnList[i].maxLen = 0; - } + _config.ColumnList[i].MaxLen = 0; } - _config.localTimestamps = localTimeCheckBox.Checked; } - - #endregion + _config.LocalTimestamps = localTimeCheckBox.Checked; } + + #endregion } \ No newline at end of file diff --git a/src/Log4jXmlColumnizer/XmlConfig.cs b/src/Log4jXmlColumnizer/XmlConfig.cs new file mode 100644 index 00000000..ed852699 --- /dev/null +++ b/src/Log4jXmlColumnizer/XmlConfig.cs @@ -0,0 +1,32 @@ +using LogExpert; + +namespace Log4jXmlColumnizer; + +/// +/// XMl configuration for parsing log4j XML files. The XSL will transform every block of log entries +/// into text lines. The fields in the text lines are separated by a special character (0xFFFD). +/// The special character will be used in the Split() function of the columnizer to split the line +/// into columns. +/// +internal class XmlConfig : IXmlLogConfiguration +{ + #region Properties + + public string XmlStartTag { get; } = "" + + "" + + "" + + "" + + "" + + ""; + + public string[] GetNamespaceDeclaration () => ["log4j", "http://jakarta.apache.org/log4j"]; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Callback/ColumnizerCallback.cs b/src/LogExpert.Core/Callback/ColumnizerCallback.cs new file mode 100644 index 00000000..9984b359 --- /dev/null +++ b/src/LogExpert.Core/Callback/ColumnizerCallback.cs @@ -0,0 +1,55 @@ +using LogExpert.Core.Interface; + +namespace LogExpert.Core.Callback; + +public class ColumnizerCallback(ILogWindow logWindow) : ILogLineColumnizerCallback, IAutoLogLineColumnizerCallback, ICloneable +{ + #region Fields + private readonly ILogWindow _logWindow = logWindow; + + #endregion + + #region Properties + + public int LineNum { get; set; } + + #endregion + + #region cTor + + private ColumnizerCallback(ColumnizerCallback original) : this(original._logWindow) + { + LineNum = original.LineNum; + } + + #endregion + + #region Public methods + + public object Clone() + { + return new ColumnizerCallback(this); + } + + public string GetFileName() + { + return _logWindow.GetCurrentFileName(LineNum); + } + + public ILogLine GetLogLine(int lineNum) + { + return _logWindow.GetLine(lineNum); + } + + public int GetLineCount() + { + return _logWindow.LogFileReader.LineCount; + } + + public void SetLineNum(int lineNum) + { + LineNum = lineNum; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Bookmark/BookmarkDataProvider.cs b/src/LogExpert.Core/Classes/Bookmark/BookmarkDataProvider.cs new file mode 100644 index 00000000..e8b7373c --- /dev/null +++ b/src/LogExpert.Core/Classes/Bookmark/BookmarkDataProvider.cs @@ -0,0 +1,182 @@ +using System.Globalization; + +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; + +using NLog; + +namespace LogExpert.Core.Classes.Bookmark; + +public class BookmarkDataProvider : IBookmarkData +{ + #region Fields + + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + #endregion + + #region cTor + + public BookmarkDataProvider () + { + BookmarkList = []; + } + + public BookmarkDataProvider (SortedList bookmarkList) + { + BookmarkList = bookmarkList; + } + + #endregion + + #region Events + + public event EventHandler BookmarkAdded; + public event EventHandler BookmarkRemoved; + public event EventHandler AllBookmarksRemoved; + + #endregion + + #region Properties + + public BookmarkCollection Bookmarks => new(BookmarkList); + + public SortedList BookmarkList { get; private set; } + + #endregion + + #region Public methods + + public void SetBookmarks (SortedList bookmarkList) + { + BookmarkList = bookmarkList; + } + + public void ToggleBookmark (int lineNum) + { + if (IsBookmarkAtLine(lineNum)) + { + RemoveBookmarkForLine(lineNum); + } + else + { + AddBookmark(new Entities.Bookmark(lineNum)); + } + } + + public bool IsBookmarkAtLine (int lineNum) + { + return BookmarkList.ContainsKey(lineNum); + } + + public int GetBookmarkIndexForLine (int lineNum) + { + return BookmarkList.IndexOfKey(lineNum); + } + + public Entities.Bookmark GetBookmarkForLine (int lineNum) + { + return BookmarkList[lineNum]; + } + + #endregion + + #region Internals + + public void ShiftBookmarks (int offset) + { + SortedList newBookmarkList = []; + + foreach (Entities.Bookmark bookmark in BookmarkList.Values) + { + var line = bookmark.LineNum - offset; + if (line >= 0) + { + bookmark.LineNum = line; + newBookmarkList.Add(line, bookmark); + } + } + + BookmarkList = newBookmarkList; + } + + public int FindPrevBookmarkIndex (int lineNum) + { + IList values = BookmarkList.Values; + for (var i = BookmarkList.Count - 1; i >= 0; --i) + { + if (values[i].LineNum <= lineNum) + { + return i; + } + } + + return BookmarkList.Count - 1; + } + + public int FindNextBookmarkIndex (int lineNum) + { + IList values = BookmarkList.Values; + for (var i = 0; i < BookmarkList.Count; ++i) + { + if (values[i].LineNum >= lineNum) + { + return i; + } + } + return 0; + } + + public void RemoveBookmarkForLine (int lineNum) + { + _ = BookmarkList.Remove(lineNum); + OnBookmarkRemoved(); + } + + //TOOD: check if the callers are checking for null before calling + public void RemoveBookmarksForLines (IEnumerable lineNumList) + { + ArgumentNullException.ThrowIfNull(lineNumList, nameof(lineNumList)); + + foreach (var lineNum in lineNumList) + { + _ = BookmarkList.Remove(lineNum); + + } + + OnBookmarkRemoved(); + } + + //TOOD: check if the callers are checking for null before calling + public void AddBookmark (Entities.Bookmark bookmark) + { + ArgumentNullException.ThrowIfNull(bookmark, nameof(bookmark)); + + BookmarkList.Add(bookmark.LineNum, bookmark); + OnBookmarkAdded(); + } + + public void ClearAllBookmarks () + { + _logger.Debug(CultureInfo.InvariantCulture, "Removing all bookmarks"); + BookmarkList.Clear(); + OnAllBookmarksRemoved(); + } + + #endregion + + protected void OnBookmarkAdded () + { + BookmarkAdded?.Invoke(this, EventArgs.Empty); + } + + protected void OnBookmarkRemoved () + { + BookmarkRemoved?.Invoke(this, EventArgs.Empty); + } + + protected void OnAllBookmarksRemoved () + { + AllBookmarksRemoved?.Invoke(this, EventArgs.Empty); + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs new file mode 100644 index 00000000..433eda96 --- /dev/null +++ b/src/LogExpert.Core/Classes/Columnizer/ClfColumnizer.cs @@ -0,0 +1,194 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace LogExpert.Core.Classes.Columnizer; + +public class ClfColumnizer : ILogLineColumnizer +{ + private const string DateTimeFormat = "dd/MMM/yyyy:HH:mm:ss zzz"; + #region Fields + + private readonly Regex _lineRegex = new("(.*) (-) (.*) (\\[.*\\]) (\".*\") (.*) (.*) (\".*\") (\".*\")"); + + private readonly CultureInfo _cultureInfo = new("en-US"); + private int _timeOffset; + + #endregion + + #region cTor + + // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" + + public ClfColumnizer () + { + } + + #endregion + + #region Public methods + + public bool IsTimeshiftImplemented () + { + return true; + } + + public void SetTimeOffset (int msecOffset) + { + _timeOffset = msecOffset; + } + + public int GetTimeOffset () + { + return _timeOffset; + } + + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) + { + IColumnizedLogLine cols = SplitLine(callback, line); + if (cols == null || cols.ColumnValues.Length < 8) + { + return DateTime.MinValue; + } + + if (cols.ColumnValues[2].FullValue.Length == 0) + { + return DateTime.MinValue; + } + + try + { + var dateTime = DateTime.ParseExact(cols.ColumnValues[2].FullValue, DateTimeFormat, _cultureInfo); + return dateTime; + } + catch (Exception) + { + return DateTime.MinValue; + } + } + + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + if (column == 2) + { + try + { + var newDateTime = + DateTime.ParseExact(value, DateTimeFormat, _cultureInfo); + var oldDateTime = + DateTime.ParseExact(oldValue, DateTimeFormat, _cultureInfo); + var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; + var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; + _timeOffset = (int)(mSecsNew - mSecsOld); + } + catch (FormatException) + { + } + } + } + + public string GetName () + { + return "Webserver CLF Columnizer"; + } + + public string GetDescription () + { + return "Common Logfile Format used by webservers."; + } + + public int GetColumnCount () + { + return 8; + } + + public string[] GetColumnNames () + { + return ["IP", "User", "Date/Time", "Request", "Status", "Bytes", "Referrer", "User agent"]; + } + + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) + { + ColumnizedLogLine cLogLine = new() + { + LogLine = line + }; + + var columns = new Column[8] + { + new() {FullValue = "", Parent = cLogLine}, + new() {FullValue = "", Parent = cLogLine}, + new() {FullValue = "", Parent = cLogLine}, + new() {FullValue = "", Parent = cLogLine}, + new() {FullValue = "", Parent = cLogLine}, + new() {FullValue = "", Parent = cLogLine}, + new() {FullValue = "", Parent = cLogLine}, + new() {FullValue = "", Parent = cLogLine} + }; + + cLogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); + + var temp = line.FullLine; + if (temp.Length > 1024) + { + // spam + temp = temp[..1024]; + columns[3].FullValue = temp; + return cLogLine; + } + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" + + if (_lineRegex.IsMatch(temp)) + { + Match match = _lineRegex.Match(temp); + GroupCollection groups = match.Groups; + if (groups.Count == 10) + { + columns[0].FullValue = groups[1].Value; + columns[1].FullValue = groups[3].Value; + columns[3].FullValue = groups[5].Value; + columns[4].FullValue = groups[6].Value; + columns[5].FullValue = groups[7].Value; + columns[6].FullValue = groups[8].Value; + columns[7].FullValue = groups[9].Value; + + var dateTimeStr = groups[4].Value.Substring(1, 26); + + // dirty probing of date/time format (much faster than DateTime.ParseExact() + if (dateTimeStr[2] == '/' && dateTimeStr[6] == '/' && dateTimeStr[11] == ':') + { + if (_timeOffset != 0) + { + try + { + var dateTime = DateTime.ParseExact(dateTimeStr, DateTimeFormat, _cultureInfo); + dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, _timeOffset)); + var newDate = dateTime.ToString(DateTimeFormat, _cultureInfo); + columns[2].FullValue = newDate; + } + catch (Exception) + { + columns[2].FullValue = "n/a"; + } + } + else + { + columns[2].FullValue = dateTimeStr; + } + } + else + { + columns[2].FullValue = dateTimeStr; + } + } + } + else + { + columns[3].FullValue = temp; + } + + return cLogLine; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs b/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs new file mode 100644 index 00000000..22c859dc --- /dev/null +++ b/src/LogExpert.Core/Classes/Columnizer/ColumnizerPicker.cs @@ -0,0 +1,143 @@ +using System.Reflection; + +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Classes.Columnizer; + +public static class ColumnizerPicker +{ + public static ILogLineColumnizer FindColumnizerByName (string name, IList list) + { + foreach (ILogLineColumnizer columnizer in list) + { + if (columnizer.GetName().Equals(name, StringComparison.Ordinal)) + { + return columnizer; + } + } + return null; + } + + public static ILogLineColumnizer DecideColumnizerByName (string name, IList list) + { + foreach (ILogLineColumnizer columnizer in list) + { + if (columnizer.GetName().Equals(name, StringComparison.Ordinal)) + { + return columnizer; + } + } + + return FindColumnizer(null, null, list); + } + + public static ILogLineColumnizer CloneColumnizer (ILogLineColumnizer columnizer, string directory) + { + if (columnizer == null) + { + return null; + } + ConstructorInfo cti = columnizer.GetType().GetConstructor(Type.EmptyTypes); + + if (cti != null) + { + var o = cti.Invoke([]); + + if (o is IColumnizerConfigurator configurator) + { + configurator.LoadConfig(directory); + } + return (ILogLineColumnizer)o; + } + return null; + } + + /// + /// This method implemented the "auto columnizer" feature. + /// This method should be called after each columnizer is changed to update the columizer. + /// + /// + /// + /// + /// + public static ILogLineColumnizer FindReplacementForAutoColumnizer (string fileName, + IAutoLogLineColumnizerCallback logFileReader, + ILogLineColumnizer logLineColumnizer, + IList list) + { + if (logLineColumnizer == null || logLineColumnizer.GetName() == "Auto Columnizer") + { + return FindColumnizer(fileName, logFileReader, list); + } + return logLineColumnizer; + } + + public static ILogLineColumnizer FindBetterColumnizer (string fileName, + IAutoLogLineColumnizerCallback logFileReader, + ILogLineColumnizer logLineColumnizer, + IList list) + { + var newColumnizer = FindColumnizer(fileName, logFileReader, list); + + if (newColumnizer.GetType().Equals(logLineColumnizer.GetType())) + { + return null; + } + return newColumnizer; + } + + //TOOD: check if the callers are checking for null before calling + /// + /// This method will search all registered columnizer and return one according to the priority that returned + /// by the each columnizer. + /// + /// + /// + /// + public static ILogLineColumnizer FindColumnizer (string fileName, IAutoLogLineColumnizerCallback logFileReader, IList registeredColumnizer) + { + if (string.IsNullOrEmpty(fileName)) + { + return new DefaultLogfileColumnizer(); + } + + ArgumentNullException.ThrowIfNull(registeredColumnizer, nameof(registeredColumnizer)); + + List loglines = []; + + if (logFileReader != null) + { + loglines = + [ + // Sampling a few lines to select the correct columnizer + logFileReader.GetLogLine(0), + logFileReader.GetLogLine(1), + logFileReader.GetLogLine(2), + logFileReader.GetLogLine(3), + logFileReader.GetLogLine(4), + logFileReader.GetLogLine(5), + logFileReader.GetLogLine(25), + logFileReader.GetLogLine(100), + logFileReader.GetLogLine(200), + logFileReader.GetLogLine(400) + ]; + } + + List<(Priority priority, ILogLineColumnizer columnizer)> priorityListOfColumnizers = []; + + foreach (ILogLineColumnizer logLineColumnizer in registeredColumnizer) + { + Priority priority = default; + if (logLineColumnizer is IColumnizerPriority columnizerPriority) + { + priority = columnizerPriority.GetPriority(fileName, loglines); + } + + priorityListOfColumnizers.Add((priority, logLineColumnizer)); + } + + ILogLineColumnizer lineColumnizer = priorityListOfColumnizers.OrderByDescending(item => item.priority).Select(item => item.columnizer).First(); + + return lineColumnizer; + } +} diff --git a/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs new file mode 100644 index 00000000..123db94b --- /dev/null +++ b/src/LogExpert.Core/Classes/Columnizer/SquareBracketColumnizer.cs @@ -0,0 +1,319 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +using static LogExpert.Core.Classes.Columnizer.TimeFormatDeterminer; + +namespace LogExpert.Core.Classes.Columnizer; + +public class SquareBracketColumnizer : ILogLineColumnizer, IColumnizerPriority +{ + #region ILogLineColumnizer implementation + + private int _timeOffset; + private readonly TimeFormatDeterminer _timeFormatDeterminer = new(); + + // TODO: need preparing this columnizer with sample log lines before use it. + private int _columnCount = 5; + private bool _isTimeExists; + + public SquareBracketColumnizer () + { + } + + public SquareBracketColumnizer (int columnCount, bool isTimeExists) : this() + { + // Add message column + _columnCount = columnCount + 1; + _isTimeExists = isTimeExists; + if (_isTimeExists) + { + // Time and date + _columnCount += 2; + } + } + + public bool IsTimeshiftImplemented () + { + return true; + } + + public void SetTimeOffset (int msecOffset) + { + _timeOffset = msecOffset; + } + + public int GetTimeOffset () + { + return _timeOffset; + } + + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) + { + IColumnizedLogLine cols = SplitLine(callback, line); + if (cols == null || cols.ColumnValues == null || cols.ColumnValues.Length < 2) + { + return DateTime.MinValue; + } + + if (cols.ColumnValues[0].FullValue.Length == 0 || cols.ColumnValues[1].FullValue.Length == 0) + { + return DateTime.MinValue; + } + + FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); + if (formatInfo == null) + { + return DateTime.MinValue; + } + + try + { + var dateTime = DateTime.ParseExact( + cols.ColumnValues[0].FullValue + " " + cols.ColumnValues[1].FullValue, formatInfo.DateTimeFormat, + formatInfo.CultureInfo); + return dateTime; + } + catch (Exception) + { + return DateTime.MinValue; + } + } + + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + if (column == 1) + { + try + { + FormatInfo formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); + if (formatInfo == null) + { + return; + } + + var newDateTime = DateTime.ParseExact(value, formatInfo.TimeFormat, formatInfo.CultureInfo); + var oldDateTime = DateTime.ParseExact(oldValue, formatInfo.TimeFormat, formatInfo.CultureInfo); + var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; + var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; + _timeOffset = (int)(mSecsNew - mSecsOld); + } + catch (FormatException) + { + } + } + } + + public string GetName () + { + return "Square Bracket Columnizer"; + } + + public string GetDescription () + { + return "Splits every line into n fields: Date, Time and the rest of the log message"; + } + + public int GetColumnCount () + { + return _columnCount; + } + + public string[] GetColumnNames () + { + var columnNames = new List(GetColumnCount()); + if (_isTimeExists) + { + columnNames.Add("Date"); + columnNames.Add("Time"); + } + + // TODO: Make this configurable. + if (GetColumnCount() > 3) + { + columnNames.Add("Level"); + } + + if (GetColumnCount() > 4) + { + columnNames.Add("Source"); + } + + // Last column is the message + columnNames.Add("Message"); + var i = 1; + while (columnNames.Count < GetColumnCount()) + { + columnNames.Insert(columnNames.Count - 1, $"Source{i++}"); + } + + return columnNames.ToArray(); + } + + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) + { + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 + // 03.01.2008 14:48:00.066 + + ColumnizedLogLine clogLine = new() + { + LogLine = line + }; + + var columns = new Column[] + { + new() {FullValue = "", Parent = clogLine}, + new() {FullValue = "", Parent = clogLine}, + new() {FullValue = "", Parent = clogLine}, + }; + + var temp = line.FullLine; + + if (temp.Length < 3) + { + columns[2].FullValue = temp; + return clogLine; + } + + FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); + if (formatInfo == null) + { + columns[2].FullValue = temp; + SquareSplit(ref columns, temp, 0, 0, 0, clogLine); + } + else + { + var endPos = formatInfo.DateTimeFormat.Length; + var timeLen = formatInfo.TimeFormat.Length; + var dateLen = formatInfo.DateFormat.Length; + try + { + if (_timeOffset != 0) + { + var dateTime = DateTime.ParseExact(temp[..endPos], formatInfo.DateTimeFormat, + formatInfo.CultureInfo); + dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, _timeOffset)); + var newDate = dateTime.ToString(formatInfo.DateTimeFormat, formatInfo.CultureInfo); + + SquareSplit(ref columns, newDate, dateLen, timeLen, endPos, clogLine); + } + else + { + SquareSplit(ref columns, temp, dateLen, timeLen, endPos, clogLine); + } + } + catch (Exception) + { + columns[0].FullValue = "n/a"; + columns[1].FullValue = "n/a"; + columns[2].FullValue = temp; + } + } + + clogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); + + return clogLine; + } + + void SquareSplit (ref Column[] columns, string line, int dateLen, int timeLen, int dateTimeEndPos, ColumnizedLogLine clogLine) + { + List columnList = []; + var restColumn = _columnCount; + if (_isTimeExists) + { + columnList.Add(new Column { FullValue = line[..dateLen], Parent = clogLine }); + columnList.Add(new Column { FullValue = line.Substring(dateLen + 1, timeLen), Parent = clogLine }); + restColumn -= 2; + } + + var nextPos = dateTimeEndPos; + + var rest = line; + + for (var i = 0; i < restColumn; i++) + { + rest = rest[nextPos..]; + //var fullValue = rest.Substring(0, rest.IndexOf(']')).TrimStart(new char[] {' '}).TrimEnd(new char[] { ' ' }); + var trimmed = rest.TrimStart([' ']); + if (string.IsNullOrEmpty(trimmed) || trimmed[0] != '[' || rest.IndexOf(']', StringComparison.Ordinal) < 0 || i == restColumn - 1) + { + columnList.Add(new Column { FullValue = rest, Parent = clogLine }); + break; + } + + nextPos = rest.IndexOf(']', StringComparison.Ordinal) + 1; + var fullValue = rest[..nextPos]; + columnList.Add(new Column { FullValue = fullValue, Parent = clogLine }); + } + + while (columnList.Count < _columnCount) + { + columnList.Insert(columnList.Count - 1, new Column { FullValue = "", Parent = clogLine }); + } + + columns = columnList.ToArray(); + } + + public Priority GetPriority (string fileName, IEnumerable samples) + { + Priority result = Priority.NotSupport; + TimeFormatDeterminer timeDeterminer = new(); + var timeStampExistsCount = 0; + var bracketsExistsCount = 0; + var maxBracketNumbers = 1; + + foreach (ILogLine logline in samples) + { + var line = logline?.FullLine; + if (string.IsNullOrEmpty(line)) + { + continue; + } + + var bracketNumbers = 1; + if (null != timeDeterminer.DetermineDateTimeFormatInfo(line)) + { + timeStampExistsCount++; + } + else + { + timeStampExistsCount--; + } + + var noSpaceLine = line.Replace(" ", string.Empty, StringComparison.Ordinal); + if (noSpaceLine.Contains('[', StringComparison.Ordinal) && noSpaceLine.Contains(']', StringComparison.Ordinal) + && noSpaceLine.IndexOf('[', StringComparison.Ordinal) < noSpaceLine.IndexOf(']', StringComparison.Ordinal)) + { + bracketNumbers += Regex.Matches(noSpaceLine, @"\]\[").Count; + bracketsExistsCount++; + } + else + { + bracketsExistsCount--; + } + + maxBracketNumbers = Math.Max(bracketNumbers, maxBracketNumbers); + } + + // Add message + _columnCount = maxBracketNumbers + 1; + _isTimeExists = timeStampExistsCount > 0; + if (_isTimeExists) + { + _columnCount += 2; + } + + if (maxBracketNumbers > 1) + { + result = Priority.WellSupport; + if (bracketsExistsCount > 0) + { + result = Priority.PerfectlySupport; + } + } + + return result; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Columnizer/TimeFormatDeterminer.cs b/src/LogExpert.Core/Classes/Columnizer/TimeFormatDeterminer.cs new file mode 100644 index 00000000..a0a21f38 --- /dev/null +++ b/src/LogExpert.Core/Classes/Columnizer/TimeFormatDeterminer.cs @@ -0,0 +1,229 @@ +using System.Globalization; + +namespace LogExpert.Core.Classes.Columnizer; + +internal class TimeFormatDeterminer +{ + #region FormatInfo helper class + + public class FormatInfo (string dateFormat, string timeFormat, CultureInfo cultureInfo) + { + + #region Properties + + public string DateFormat { get; } = dateFormat; + + public string TimeFormat { get; } = timeFormat; + + public CultureInfo CultureInfo { get; } = cultureInfo; + + public string DateTimeFormat => DateFormat + " " + TimeFormat; + + public bool IgnoreFirstChar { get; set; } + + #endregion + } + + #endregion + + private readonly FormatInfo formatInfo1 = new("dd.MM.yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo2 = new("dd.MM.yyyy", "HH:mm:ss", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo3 = new("yyyy/MM/dd", "HH:mm:ss.fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo4 = new("yyyy/MM/dd", "HH:mm:ss", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo5 = new("yyyy.MM.dd", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo6 = new("yyyy.MM.dd", "HH:mm:ss", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo7 = new("dd.MM.yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo8 = new("yyyy/MM/dd", "HH:mm:ss,fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo9 = new("yyyy.MM.dd", "HH:mm:ss,fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo10 = new("yyyy-MM-dd", "HH:mm:ss.fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo11 = new("yyyy-MM-dd", "HH:mm:ss,fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo12 = new("yyyy-MM-dd", "HH:mm:ss", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo13 = new("dd MMM yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo14 = new("dd MMM yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo15 = new("dd MMM yyyy", "HH:mm:ss", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo16 = new("dd.MM.yy", "HH:mm:ss.fff", new CultureInfo("de-DE")); + private readonly FormatInfo formatInfo17 = new("yyyy-MM-dd", "HH:mm:ss:ffff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo18 = new("dd/MM/yyyy", "HH:mm:ss.fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo19 = new("dd/MM/yyyy", "HH:mm:ss:fff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo20 = new("yyyy-MM-dd", "HH:mm:ss.ffff", new CultureInfo("en-US")); + private readonly FormatInfo formatInfo21 = new("yyyy-MM-dd", "HH:mm:ss,ffff", new CultureInfo("en-US")); + + + public FormatInfo DetermineDateTimeFormatInfo (string line) + { + if (line.Length < 21) + { + return null; + } + + var temp = line; + var ignoreFirst = false; + + // determine if string starts with bracket and remove it + if (temp[0] is '[' or '(' or '{') + { + temp = temp[1..]; + ignoreFirst = true; + + } + + // dirty hardcoded probing of date/time format (much faster than DateTime.ParseExact() + if (temp[2] == '.' && temp[5] == '.' && temp[13] == ':' && temp[16] == ':') + { + if (temp[19] == '.') + { + formatInfo1.IgnoreFirstChar = ignoreFirst; + return formatInfo1; + } + else if (temp[19] == ',') + { + formatInfo7.IgnoreFirstChar = ignoreFirst; + return formatInfo7; + } + else + { + formatInfo2.IgnoreFirstChar = ignoreFirst; + return formatInfo2; + } + } + else if (temp[2] == '/' && temp[5] == '/' && temp[13] == ':' && temp[16] == ':') + { + if (temp[19] == '.') + { + formatInfo18.IgnoreFirstChar = ignoreFirst; + return formatInfo18; + } + else if (temp[19] == ':') + { + formatInfo19.IgnoreFirstChar = ignoreFirst; + return formatInfo19; + } + } + else if (temp[4] == '/' && temp[7] == '/' && temp[13] == ':' && temp[16] == ':') + { + if (temp[19] == '.') + { + formatInfo3.IgnoreFirstChar = ignoreFirst; + return formatInfo3; + } + else if (temp[19] == ',') + { + formatInfo8.IgnoreFirstChar = ignoreFirst; + return formatInfo8; + } + else + { + formatInfo4.IgnoreFirstChar = ignoreFirst; + return formatInfo4; + } + } + else if (temp[4] == '.' && temp[7] == '.' && temp[13] == ':' && temp[16] == ':') + { + if (temp[19] == '.') + { + formatInfo5.IgnoreFirstChar = ignoreFirst; + return formatInfo5; + } + else if (temp[19] == ',') + { + formatInfo9.IgnoreFirstChar = ignoreFirst; + return formatInfo9; + } + else + { + formatInfo6.IgnoreFirstChar = ignoreFirst; + return formatInfo6; + } + } + else if (temp[4] == '-' && temp[7] == '-' && temp[13] == ':' && temp[16] == ':') + { + if (temp[19] == '.') + { + if (temp.Length > 23 && char.IsDigit(temp[23])) + { + formatInfo20.IgnoreFirstChar = ignoreFirst; + return formatInfo20; + } + else + { + formatInfo10.IgnoreFirstChar = ignoreFirst; + return formatInfo10; + } + } + else if (temp[19] == ',') + { + if (temp.Length > 23 && char.IsDigit(temp[23])) + { + formatInfo21.IgnoreFirstChar = ignoreFirst; + return formatInfo21; + } + else + { + formatInfo11.IgnoreFirstChar = ignoreFirst; + return formatInfo11; + } + } + else if (temp[19] == ':') + { + formatInfo17.IgnoreFirstChar = ignoreFirst; + return formatInfo17; + } + else + { + formatInfo12.IgnoreFirstChar = ignoreFirst; + return formatInfo12; + } + } + else if (temp[2] == ' ' && temp[6] == ' ' && temp[14] == ':' && temp[17] == ':') + { + if (temp[20] == ',') + { + formatInfo13.IgnoreFirstChar = ignoreFirst; + return formatInfo13; + } + else if (temp[20] == '.') + { + formatInfo14.IgnoreFirstChar = ignoreFirst; + return formatInfo14; + } + else + { + formatInfo15.IgnoreFirstChar = ignoreFirst; + return formatInfo15; + } + } + //dd.MM.yy HH:mm:ss.fff + else if (temp[2] == '.' && temp[5] == '.' && temp[11] == ':' && temp[14] == ':' && temp[17] == '.') + { + formatInfo16.IgnoreFirstChar = ignoreFirst; + return formatInfo16; + } + + return null; + } + + public FormatInfo DetermineTimeFormatInfo (string field) + { + // dirty hardcoded probing of time format (much faster than DateTime.ParseExact() + if (field[2] == ':' && field[5] == ':') + { + if (field.Length > 8) + { + if (field[8] == '.') + { + return formatInfo1; + } + else if (field[8] == ',') + { + return formatInfo7; + } + } + else + { + return formatInfo2; + } + } + + return null; + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Columnizer/TimestampColumnizer.cs b/src/LogExpert.Core/Classes/Columnizer/TimestampColumnizer.cs new file mode 100644 index 00000000..20239ceb --- /dev/null +++ b/src/LogExpert.Core/Classes/Columnizer/TimestampColumnizer.cs @@ -0,0 +1,214 @@ +using static LogExpert.Core.Classes.Columnizer.TimeFormatDeterminer; + +namespace LogExpert.Core.Classes.Columnizer; + +public class TimestampColumnizer : ILogLineColumnizer, IColumnizerPriority +{ + #region ILogLineColumnizer implementation + + private int timeOffset; + private readonly TimeFormatDeterminer _timeFormatDeterminer = new(); + + public bool IsTimeshiftImplemented () + { + return true; + } + + public void SetTimeOffset (int msecOffset) + { + timeOffset = msecOffset; + } + + public int GetTimeOffset () + { + return timeOffset; + } + + + public DateTime GetTimestamp (ILogLineColumnizerCallback callback, ILogLine line) + { + IColumnizedLogLine cols = SplitLine(callback, line); + if (cols == null || cols.ColumnValues == null || cols.ColumnValues.Length < 2) + { + return DateTime.MinValue; + } + if (cols.ColumnValues[0].FullValue.Length == 0 || cols.ColumnValues[1].FullValue.Length == 0) + { + return DateTime.MinValue; + } + FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); + if (formatInfo == null) + { + return DateTime.MinValue; + } + + try + { + var dateTime = DateTime.ParseExact( + cols.ColumnValues[0].FullValue + " " + cols.ColumnValues[1].FullValue, formatInfo.DateTimeFormat, + formatInfo.CultureInfo); + return dateTime; + } + catch (Exception) + { + return DateTime.MinValue; + } + } + + + public void PushValue (ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + if (column == 1) + { + try + { + FormatInfo formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); + if (formatInfo == null) + { + return; + } + var newDateTime = DateTime.ParseExact(value, formatInfo.TimeFormat, formatInfo.CultureInfo); + var oldDateTime = DateTime.ParseExact(oldValue, formatInfo.TimeFormat, formatInfo.CultureInfo); + var mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; + var mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; + timeOffset = (int)(mSecsNew - mSecsOld); + } + catch (FormatException) + { + } + } + } + + public string GetName () + { + return "Timestamp Columnizer"; + } + + public string GetDescription () + { + return "Splits every line into 3 fields: Date, Time and the rest of the log message"; + } + + public int GetColumnCount () + { + return 3; + } + + public string[] GetColumnNames () + { + return ["Date", "Time", "Message"]; + } + + public IColumnizedLogLine SplitLine (ILogLineColumnizerCallback callback, ILogLine line) + { + // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 + // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 + // 03.01.2008 14:48:00.066 + + ColumnizedLogLine clogLine = new(); + clogLine.LogLine = line; + + var columns = new Column[3] + { + new() {FullValue = "", Parent = clogLine}, + new() {FullValue = "", Parent = clogLine}, + new() {FullValue = "", Parent = clogLine}, + }; + + clogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); + + var temp = line.FullLine; + + FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(temp); + if (formatInfo == null) + { + columns[2].FullValue = temp; + return clogLine; + } + var endPos = formatInfo.DateTimeFormat.Length; + var timeLen = formatInfo.TimeFormat.Length; + var dateLen = formatInfo.DateFormat.Length; + try + { + if (timeOffset != 0) + { + if (formatInfo.IgnoreFirstChar) + { + // First character is a bracket and should be ignored + var dateTime = DateTime.ParseExact(temp.Substring(1, endPos), formatInfo.DateTimeFormat, + formatInfo.CultureInfo); + dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, timeOffset)); + var newDate = dateTime.ToString(formatInfo.DateTimeFormat, formatInfo.CultureInfo); + columns[0].FullValue = newDate.Substring(0, dateLen); // date + columns[1].FullValue = newDate.Substring(dateLen + 1, timeLen); // time + columns[2].FullValue = temp.Substring(endPos + 2); // rest of line + } + else + { + var dateTime = DateTime.ParseExact(temp.Substring(0, endPos), formatInfo.DateTimeFormat, + formatInfo.CultureInfo); + dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, timeOffset)); + var newDate = dateTime.ToString(formatInfo.DateTimeFormat, formatInfo.CultureInfo); + columns[0].FullValue = newDate.Substring(0, dateLen); // date + columns[1].FullValue = newDate.Substring(dateLen + 1, timeLen); // time + columns[2].FullValue = temp.Substring(endPos); // rest of line + } + } + else + { + if (formatInfo.IgnoreFirstChar) + { + // First character is a bracket and should be ignored + columns[0].FullValue = temp.Substring(1, dateLen); // date + columns[1].FullValue = temp.Substring(dateLen + 2, timeLen); // time + columns[2].FullValue = temp.Substring(endPos + 2); // rest of line + } + else + { + columns[0].FullValue = temp.Substring(0, dateLen); // date + columns[1].FullValue = temp.Substring(dateLen + 1, timeLen); // time + columns[2].FullValue = temp.Substring(endPos); // rest of line + } + } + } + catch (Exception) + { + columns[0].FullValue = "n/a"; + columns[1].FullValue = "n/a"; + columns[2].FullValue = temp; + } + return clogLine; + } + + public Priority GetPriority (string fileName, IEnumerable samples) + { + Priority result = Priority.NotSupport; + + var timeStampCount = 0; + foreach (ILogLine line in samples) + { + if (line == null || string.IsNullOrEmpty(line.FullLine)) + { + continue; + } + var timeDeterminer = new TimeFormatDeterminer(); + if (null != timeDeterminer.DetermineDateTimeFormatInfo(line.FullLine)) + { + timeStampCount++; + } + else + { + timeStampCount--; + } + } + + if (timeStampCount > 0) + { + result = Priority.WellSupport; + } + + return result; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/DateTimeParser/DateFormatPartAdjuster.cs b/src/LogExpert.Core/Classes/DateTimeParser/DateFormatPartAdjuster.cs new file mode 100644 index 00000000..9c85f936 --- /dev/null +++ b/src/LogExpert.Core/Classes/DateTimeParser/DateFormatPartAdjuster.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; + +namespace LogExpert.Core.Classes.DateTimeParser; + +//TODO: This should be moved into LogExpert.UI and changed to internal +// Ensures we have constant width (number of characters) date formats +public static class DateFormatPartAdjuster +{ + private static readonly IDictionary _dateTimePartReplacements = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + ["y"] = "yyy", + ["yyy"] = "yyyy", + ["m"] = "mm", + ["d"] = "dd", + ["h"] = "hh", + ["s"] = "ss" + }; + + public static string AdjustDateTimeFormatPart(string part) + { + ArgumentNullException.ThrowIfNull(part, nameof(part)); + + if (!_dateTimePartReplacements.TryGetValue(part, out var adjustedPart)) + { + return part; + } + + if (char.IsUpper(part[0])) + { + return adjustedPart.ToUpper(); + } + else + { + return adjustedPart.ToLower(); + } + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/DateTimeParser/Parser.cs b/src/LogExpert.Core/Classes/DateTimeParser/Parser.cs new file mode 100644 index 00000000..a6528267 --- /dev/null +++ b/src/LogExpert.Core/Classes/DateTimeParser/Parser.cs @@ -0,0 +1,170 @@ +namespace LogExpert.Core.Classes.DateTimeParser; + +public static class Parser +{ + public static List
ParseSections(string formatString, out bool syntaxError) + { + var tokenizer = new Tokenizer(formatString); + var sections = new List
(); + syntaxError = false; + while (true) + { + var section = ParseSection(tokenizer, sections.Count, out var sectionSyntaxError); + + if (sectionSyntaxError) + { + syntaxError = true; + } + + if (section == null) + { + break; + } + + sections.Add(section); + } + + return sections; + } + + private static Section ParseSection(Tokenizer reader, int index, out bool syntaxError) + { + var hasDateParts = false; + string token; + List tokens = []; + + while ((token = ReadToken(reader, out syntaxError)) != null) + { + if (token == ";") + { + break; + } + + if (Token.IsDatePart(token)) + { + hasDateParts |= true; + tokens.Add(token); + } + else + { + tokens.Add(token); + } + } + + if (syntaxError || tokens.Count == 0) + { + return null; + } + + List generalTextDateDuration; + if (hasDateParts) + { + ParseMilliseconds(tokens, out generalTextDateDuration); + } + else + { + // Unable to parse format string + syntaxError = true; + return null; + } + + return new Section() + { + SectionIndex = index, + GeneralTextDateDurationParts = generalTextDateDuration + }; + } + + private static void ParseMilliseconds(List tokens, out List result) + { + // if tokens form .0 through .000.., combine to single subsecond token + result = []; + for (var i = 0; i < tokens.Count; i++) + { + var token = tokens[i]; + if (token == ".") + { + var zeros = 0; + while (i + 1 < tokens.Count && tokens[i + 1] == "0") + { + i++; + zeros++; + } + + if (zeros > 0) + { + result.Add("." + new string('0', zeros)); + } + else + { + result.Add("."); + } + } + else + { + result.Add(token); + } + } + } + + private static string ReadToken(Tokenizer reader, out bool syntaxError) + { + var offset = reader.Position; + if (ReadLiteral(reader)) + { + syntaxError = false; + var length = reader.Position - offset; + return reader.Substring(offset, length); + } + + if ( + // Symbols + reader.ReadOneOf("#?,!&%+-$€£0123456789{}():;/.@ ") || + + // Date + reader.ReadString("tt", true) || //AM / PM + reader.ReadOneOrMore('y') || + reader.ReadOneOrMore('Y') || + reader.ReadOneOrMore('m') || + reader.ReadOneOrMore('M') || + reader.ReadOneOrMore('d') || + reader.ReadOneOrMore('D') || + reader.ReadOneOrMore('h') || + reader.ReadOneOrMore('H') || + reader.ReadOneOrMore('s') || + reader.ReadOneOrMore('S') || + //Latin Date String: (a.C.n. ante Christum natum) + reader.ReadString("gg")) + { + syntaxError = false; + var length = reader.Position - offset; + return reader.Substring(offset, length); + } + + // Symbols + + syntaxError = reader.Position < reader.Length; + return null; + } + + private static bool ReadLiteral(Tokenizer reader) + { + if (reader.Peek() == '\\' || reader.Peek() == '*' || reader.Peek() == '_') + { + reader.Advance(2); + return true; + } + + if (reader.ReadEnclosed('"', '"')) + { + return true; + } + + if (reader.ReadEnclosed('\'', '\'')) + { + return true; + } + + return false; + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/DateTimeParser/Section.cs b/src/LogExpert.Core/Classes/DateTimeParser/Section.cs new file mode 100644 index 00000000..a6d14c82 --- /dev/null +++ b/src/LogExpert.Core/Classes/DateTimeParser/Section.cs @@ -0,0 +1,10 @@ +using System.Collections.Generic; + +namespace LogExpert.Core.Classes.DateTimeParser; + +public class Section +{ + public int SectionIndex { get; set; } + + public List GeneralTextDateDurationParts { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/DateTimeParser/Token.cs b/src/LogExpert.Core/Classes/DateTimeParser/Token.cs new file mode 100644 index 00000000..3db40686 --- /dev/null +++ b/src/LogExpert.Core/Classes/DateTimeParser/Token.cs @@ -0,0 +1,19 @@ +using System; + +namespace LogExpert.Core.Classes.DateTimeParser; + +public static class Token +{ + //TOOD: check if the callers are checking for null before calling + public static bool IsDatePart(string token) + { + ArgumentNullException.ThrowIfNull(token, nameof(token)); + return + token.StartsWith("y", StringComparison.OrdinalIgnoreCase) || + token.StartsWith("m", StringComparison.OrdinalIgnoreCase) || + token.StartsWith("d", StringComparison.OrdinalIgnoreCase) || + token.StartsWith("s", StringComparison.OrdinalIgnoreCase) || + token.StartsWith("h", StringComparison.OrdinalIgnoreCase) || + token.Equals("tt", StringComparison.OrdinalIgnoreCase); + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/DateTimeParser/Tokenizer.cs b/src/LogExpert.Core/Classes/DateTimeParser/Tokenizer.cs new file mode 100644 index 00000000..864b96f3 --- /dev/null +++ b/src/LogExpert.Core/Classes/DateTimeParser/Tokenizer.cs @@ -0,0 +1,131 @@ +using System; +using System.Globalization; + +namespace LogExpert.Core.Classes.DateTimeParser; + +internal class Tokenizer +{ + private readonly string formatString; + + public Tokenizer (string fmt) + { + formatString = fmt; + } + + public int Position { get; private set; } + + public int Length => formatString.Length; + + public string Substring (int startIndex, int length) + { + return formatString.Substring(startIndex, length); + } + + public int Peek (int offset = 0) + { + if (Position + offset >= formatString.Length) + { + return -1; + } + + return formatString[Position + offset]; + } + + public int PeekUntil (int startOffset, int until) + { + var offset = startOffset; + while (true) + { + var c = Peek(offset++); + if (c == -1) + { + break; + } + + if (c == until) + { + return offset - startOffset; + } + } + return 0; + } + + public bool PeekOneOf (int offset, string s) + { + foreach (var c in s) + { + if (Peek(offset) == c) + { + return true; + } + } + return false; + } + + public void Advance (int characters = 1) + { + Position = Math.Min(Position + characters, formatString.Length); + } + + public bool ReadOneOrMore (int c) + { + if (Peek() != c) + { + return false; + } + + while (Peek() == c) + { + Advance(); + } + + return true; + } + + public bool ReadOneOf (string s) + { + if (PeekOneOf(0, s)) + { + Advance(); + return true; + } + return false; + } + + public bool ReadString (string str, bool ignoreCase = false) + { + if (Position + str.Length > formatString.Length) + { + return false; + } + + for (var i = 0; i < str.Length; i++) + { + var c1 = str[i]; + var c2 = (char)Peek(i); + + if ((ignoreCase && char.ToUpperInvariant(c1) != char.ToUpperInvariant(c2)) || (!ignoreCase && c1 != c2)) + { + return false; + } + } + + Advance(str.Length); + return true; + } + + public bool ReadEnclosed (char open, char close) + { + if (Peek() == open) + { + var length = PeekUntil(1, close); + if (length > 0) + { + Advance(1 + length); + return true; + } + } + + return false; + } +} diff --git a/src/LogExpert.Core/Classes/FileSystemCallback.cs b/src/LogExpert.Core/Classes/FileSystemCallback.cs new file mode 100644 index 00000000..ca8d6688 --- /dev/null +++ b/src/LogExpert.Core/Classes/FileSystemCallback.cs @@ -0,0 +1,55 @@ +using System.Globalization; + +using NLog; + +namespace LogExpert.Core.Classes; + +public class FileSystemCallback : IFileSystemCallback +{ + #region Public methods + + public ILogExpertLogger GetLogger() + { + return new NLogLogExpertWrapper(); + } + + #endregion + + private class NLogLogExpertWrapper : ILogExpertLogger + { + #region Fields + + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + + #endregion + + #region Public methods + + public void Info(string msg) + { + _logger.Info(msg); + } + + public void Info (IFormatProvider formatProvider, string msg) + { + _logger.Info(formatProvider, msg); + } + + public void Debug(string msg) + { + _logger.Debug(msg); + } + + public void LogWarn(string msg) + { + _logger.Warn(msg); + } + + public void LogError(string msg) + { + _logger.Error(msg); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Filter/Filter.cs b/src/LogExpert.Core/Classes/Filter/Filter.cs new file mode 100644 index 00000000..d7393f13 --- /dev/null +++ b/src/LogExpert.Core/Classes/Filter/Filter.cs @@ -0,0 +1,175 @@ +using LogExpert.Core.Callback; +using LogExpert.Core.Classes; + +using NLog; + +namespace LogExpert.Core.Classes.Filter; + +internal delegate void FilterFx (FilterParams filterParams, List filterResultLines, List lastFilterResultLines, List filterHitList); + +internal class Filter +{ + #region Fields + + private const int PROGRESS_BAR_MODULO = 1000; + private const int SPREAD_MAX = 50; + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + private readonly ColumnizerCallback _callback; + + #endregion + + #region cTor + + //TODO Is the callback needed? (https://github.com/LogExperts/LogExpert/issues/401) + public Filter (ColumnizerCallback callback) + { + _callback = callback; + FilterResultLines = []; + LastFilterLinesList = []; + FilterHitList = []; + } + + #endregion + + #region Properties + + public List FilterResultLines { get; } + public List LastFilterLinesList { get; } + public List FilterHitList { get; } + public bool ShouldCancel { get; set; } + + #endregion + + #region Public methods + + public int DoFilter (FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback) + { + return DoFilter(filterParams, startLine, maxCount, FilterResultLines, LastFilterLinesList, FilterHitList, progressCallback); + } + + #endregion + + #region Private Methods + + private int DoFilter (FilterParams filterParams, int startLine, int maxCount, List filterResultLines, List lastFilterLinesList, List filterHitList, ProgressCallback progressCallback) + { + var lineNum = startLine; + var count = 0; + var callbackCounter = 0; + + try + { + filterParams.Reset(); + + while ((count++ < maxCount || filterParams.IsInRange) && !ShouldCancel) + { + if (lineNum >= _callback.GetLineCount()) + { + return count; + } + + var line = _callback.GetLogLine(lineNum); + + if (line == null) + { + return count; + } + + _callback.SetLineNum(lineNum); + + if (Util.TestFilterCondition(filterParams, line, _callback)) + { + AddFilterLine(lineNum, filterParams, filterResultLines, lastFilterLinesList, filterHitList); + } + + lineNum++; + callbackCounter++; + + if (lineNum % PROGRESS_BAR_MODULO == 0) + { + progressCallback(callbackCounter); + callbackCounter = 0; + } + } + } + catch (Exception ex) + { + _logger.Error(ex, "Exception while filtering. Please report to developer"); + throw; + //TODO: This information should be handled from the LogExpert project and not from LogExpert.Core. + //MessageBox.Show(null, + // "Exception while filtering. Please report to developer: \n\n" + ex + "\n\n" + ex.StackTrace, + // "LogExpert"); + } + + return count; + } + + private void AddFilterLine (int lineNum, FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) + { + filterHitList.Add(lineNum); + var filterResult = GetAdditionalFilterResults(filterParams, lineNum, lastFilterLinesList); + + filterResultLines.AddRange(filterResult); + + lastFilterLinesList.AddRange(filterResult); + + if (lastFilterLinesList.Count > SPREAD_MAX * 2) + { + lastFilterLinesList.RemoveRange(0, lastFilterLinesList.Count - SPREAD_MAX * 2); + } + } + + /// + /// 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 = []; + + 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 < _callback.GetLineCount()) + { + if (!resultList.Contains(lineNum + i) && !checkList.Contains(lineNum + i)) + { + resultList.Add(lineNum + i); + } + } + } + + return resultList; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Filter/FilterCancelHandler.cs b/src/LogExpert.Core/Classes/Filter/FilterCancelHandler.cs new file mode 100644 index 00000000..14eea0d3 --- /dev/null +++ b/src/LogExpert.Core/Classes/Filter/FilterCancelHandler.cs @@ -0,0 +1,36 @@ +using System.Globalization; + +using LogExpert.Core.Interface; + +using NLog; + +namespace LogExpert.Core.Classes.Filter; + +public class FilterCancelHandler : IBackgroundProcessCancelHandler +{ + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + #region Fields + + private readonly FilterStarter _filterStarter; + + #endregion + + #region cTor + + public FilterCancelHandler(FilterStarter filterStarter) + { + _filterStarter = filterStarter; + } + + #endregion + + #region Public methods + + public void EscapePressed() + { + _logger.Info(CultureInfo.InvariantCulture, "FilterCancelHandler called."); + _filterStarter.CancelFilter(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Filter/FilterParams.cs b/src/LogExpert.Core/Classes/Filter/FilterParams.cs new file mode 100644 index 00000000..19b11f8e --- /dev/null +++ b/src/LogExpert.Core/Classes/Filter/FilterParams.cs @@ -0,0 +1,152 @@ +using System.Collections; +using System.Collections.ObjectModel; +using System.Drawing; +using System.Text.Json.Serialization; +using System.Text.RegularExpressions; + +namespace LogExpert.Core.Classes.Filter; + +[Serializable] +public class FilterParams : ICloneable +{ + #region Fields + //public List historyList = new List(); + //public List rangeHistoryList = new List(); + + #endregion + + #region Properties + + public string SearchText { get; set; } + + public string RangeSearchText { get; set; } + + //public bool SpreadEnabled => SpreadBefore > 0 || SpreadBehind > 0; + + public bool IsCaseSensitive { get; set; } + + public bool IsFilterTail { get; set; } + + public int FuzzyValue { get; set; } + + public bool EmptyColumnUsePrev { get; set; } + + public bool EmptyColumnHit { get; set; } + + public bool ExactColumnMatch { get; set; } + + public bool ColumnRestrict { get; set; } + + public Color Color { get; set; } = Color.Black; + + public int SpreadBefore { get; set; } + + public int SpreadBehind { get; set; } + + public bool IsInvert { get; set; } + + public bool IsRangeSearch { get; set; } + + public bool IsRegex { get; set; } + + // list of columns in which to search + public Collection ColumnList { get; } = []; + + [JsonIgnore] + [field: NonSerialized] + public ILogLineColumnizer CurrentColumnizer { get; set; } + + /// + /// false=looking for start + /// true=looking for end + /// + [field: NonSerialized] + public bool IsInRange { get; set; } + + [field: NonSerialized] + public string LastLine { get; set; } = string.Empty; + + [field: NonSerialized] + public Hashtable LastNonEmptyCols { get; set; } = []; + + [field: NonSerialized] + public bool LastResult { get; set; } + + ///Returns RangeSearchText.ToUpperInvariant + [JsonIgnore] + internal string NormalizedRangeSearchText => RangeSearchText.ToUpperInvariant(); + + ///Returns SearchText.ToUpperInvariant + [JsonIgnore] + internal string NormalizedSearchText => SearchText.ToUpperInvariant(); + + [field: NonSerialized] + public Regex RangeRex { get; set; } + + [field: NonSerialized] + public Regex Rex { get; set; } + + #endregion + + #region Public methods + + /// + /// Returns a new FilterParams object with the current columnizer set to the one used in this object. + /// + /// + public FilterParams CloneWithCurrentColumnizer () + { + FilterParams newParams = Clone(); + newParams.Init(); + // removed cloning of columnizer for filtering, because this causes issues with columnizers that hold internal states (like CsvColumnizer) + // newParams.currentColumnizer = Util.CloneColumnizer(this.currentColumnizer); + newParams.CurrentColumnizer = CurrentColumnizer; + return newParams; + } + + // call after deserialization! + public void Init () + { + LastNonEmptyCols = []; + LastLine = string.Empty; + } + + // Reset before a new search + public void Reset () + { + LastNonEmptyCols.Clear(); + IsInRange = false; + } + + public void CreateRegex () + { + if (SearchText != null) + { + Rex = new Regex(SearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + } + if (RangeSearchText != null && IsRangeSearch) + { + RangeRex = new Regex(RangeSearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + } + } + + /// + /// Shallow Copy + /// + /// + public FilterParams Clone () + { + return (FilterParams)MemberwiseClone(); + } + + /// + /// Shallow Copy + /// + /// + object ICloneable.Clone () + { + return Clone(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Filter/FilterPipe.cs b/src/LogExpert.Core/Classes/Filter/FilterPipe.cs new file mode 100644 index 00000000..895872c3 --- /dev/null +++ b/src/LogExpert.Core/Classes/Filter/FilterPipe.cs @@ -0,0 +1,212 @@ +using System.Globalization; +using System.Text; +using LogExpert.Core.Interface; +using NLog; + +namespace LogExpert.Core.Classes.Filter; + +public class FilterPipe : IDisposable +{ + #region Fields + + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + private List _lineMappingList = []; + private StreamWriter _writer; + private readonly object _fileNameLock = new(); + private bool _disposed; + + #endregion + + #region cTor + + public FilterPipe(FilterParams filterParams, ILogWindow logWindow) + { + FilterParams = filterParams; + LogWindow = logWindow; + IsStopped = false; + FileName = Path.GetTempFileName(); + _disposed = false; + + _logger.Info($"Created temp file: {FileName}"); + } + + #endregion + + #region Events + + public event EventHandler Closed; + + #endregion + + #region Properties + + public bool IsStopped { get; set; } + + public string FileName { get; } + + public FilterParams FilterParams { get; } + + public IList LastLinesHistoryList { get; } = []; + + public ILogWindow LogWindow { get; } + + public ILogWindow OwnLogWindow { get; set; } + + #endregion + + #region Public methods + + public void OpenFile () + { + FileStream fStream = new(FileName, FileMode.Append, FileAccess.Write, FileShare.Read); + _writer = new StreamWriter(fStream, new UnicodeEncoding(false, false)); + } + + public void CloseFile () + { + if (_writer != null) + { + _writer.Close(); + _writer = null; + } + } + + //TOOD: check if the callers are checking for null before calling + public bool WriteToPipe (ILogLine textLine, int orgLineNum) + { + ArgumentNullException.ThrowIfNull(textLine, nameof(textLine)); + + try + { + lock (_fileNameLock) + { + lock (_lineMappingList) + { + try + { + _writer.WriteLine(textLine.FullLine); + _lineMappingList.Add(orgLineNum); + return true; + } + catch (IOException e) + { + _logger.Error(e, "writeToPipe()"); + return false; + } + } + } + } + catch (IOException ex) + { + _logger.Error(ex, "writeToPipe(): file was closed"); + return false; + } + } + + public int GetOriginalLineNum (int lineNum) + { + lock (_lineMappingList) + { + return _lineMappingList.Count > lineNum + ? _lineMappingList[lineNum] + : -1; + } + } + + public void ShiftLineNums (int offset) + { + _logger.Debug($"FilterPipe.ShiftLineNums() offset={offset}"); + List newList = []; + lock (_lineMappingList) + { + foreach (var lineNum in _lineMappingList) + { + var line = lineNum - offset; + if (line >= 0) + { + newList.Add(line); + } + else + { + newList.Add(-1); + } + } + + _lineMappingList = newList; + } + } + + public void ClearLineNums () + { + _logger.Debug(CultureInfo.InvariantCulture, "FilterPipe.ClearLineNums()"); + lock (_lineMappingList) + { + for (var i = 0; i < _lineMappingList.Count; ++i) + { + _lineMappingList[i] = -1; + } + } + } + + public void ClearLineList () + { + lock (_lineMappingList) + { + _lineMappingList.Clear(); + } + } + + public void RecreateTempFile () + { + lock (_lineMappingList) + { + _lineMappingList = []; + } + + lock (_fileNameLock) + { + CloseFile(); + // trunc file + FileStream fStream = new(FileName, FileMode.Truncate, FileAccess.Write, FileShare.Read); + fStream.SetLength(0); + fStream.Close(); + } + } + + public void CloseAndDisconnect () + { + ClearLineList(); + OnClosed(); + } + + #endregion + + #region Private Methods + + private void OnClosed () + { + Closed?.Invoke(this, EventArgs.Empty); + } + + public void Dispose () + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose (bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _writer?.Dispose(); + } + + _disposed = true; + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Filter/FilterStarter.cs b/src/LogExpert.Core/Classes/Filter/FilterStarter.cs new file mode 100644 index 00000000..f09a881c --- /dev/null +++ b/src/LogExpert.Core/Classes/Filter/FilterStarter.cs @@ -0,0 +1,209 @@ +using System.Globalization; + +using LogExpert.Core.Callback; + +using NLog; + +namespace LogExpert.Core.Classes.Filter; + +public delegate void ProgressCallback (int lineCount); + +public class FilterStarter +{ + #region Fields + + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + + private readonly ColumnizerCallback _callback; + private readonly SortedDictionary _filterHitDict; + private readonly List _filterReadyList; + private readonly SortedDictionary _filterResultDict; + + private readonly List _filterWorkerList; + + private readonly SortedDictionary _lastFilterLinesDict; + + private ProgressCallback _progressCallback; + private int _progressLineCount; + private bool _shouldStop; + + #endregion + + #region cTor + + public FilterStarter (ColumnizerCallback callback, int minThreads) + { + _callback = callback; + FilterResultLines = []; + LastFilterLinesList = []; + FilterHitList = []; + _filterReadyList = []; + _filterWorkerList = []; + _filterHitDict = []; + _filterResultDict = []; + _lastFilterLinesDict = []; + ThreadCount = Environment.ProcessorCount * 4; + ThreadCount = minThreads; + ThreadPool.GetMinThreads(out _, out var completion); + ThreadPool.SetMinThreads(minThreads, completion); + ThreadPool.GetMaxThreads(out _, out _); + } + + #endregion + + #region Properties + + public List FilterResultLines { get; set; } + + public List LastFilterLinesList { get; set; } + + public List FilterHitList { get; set; } + + public int ThreadCount { get; set; } + + #endregion + + #region Public methods + + public async void DoFilter (FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback) + { + FilterResultLines.Clear(); + LastFilterLinesList.Clear(); + FilterHitList.Clear(); + _filterHitDict.Clear(); + _filterReadyList.Clear(); + _filterResultDict.Clear(); + _lastFilterLinesDict.Clear(); + _filterWorkerList.Clear(); + _shouldStop = false; + + var interval = maxCount / ThreadCount; + + if (interval < 1) + { + interval = 1; + } + + var workStartLine = startLine; + _progressLineCount = 0; + _progressCallback = progressCallback; + while (workStartLine < startLine + maxCount) + { + if (workStartLine + interval > maxCount) + { + interval = maxCount - workStartLine; + if (interval == 0) + { + break; + } + } + _logger.Info(CultureInfo.InvariantCulture, "FilterStarter starts worker for line {0}, lineCount {1}", workStartLine, interval); + + var filter = await Task.Run(() => DoWork(filterParams, workStartLine, interval, ThreadProgressCallback)).ConfigureAwait(false); + FilterDoneCallback(filter); + workStartLine += interval; + } + + MergeResults(); + } + + /// + /// Requests the FilterStarter to stop all filter threads. Call this from another thread (e.g. GUI). The function returns + /// immediately without waiting for filter end. + /// + public void CancelFilter () + { + _shouldStop = true; + lock (_filterWorkerList) + { + _logger.Info(CultureInfo.InvariantCulture, "Filter cancel requested. Stopping all {0} threads.", _filterWorkerList.Count); + foreach (var filter in _filterWorkerList) + { + filter.ShouldCancel = true; + } + } + } + + #endregion + + #region Private Methods + + private void ThreadProgressCallback (int lineCount) + { + var count = Interlocked.Add(ref _progressLineCount, lineCount); + _progressCallback(count); + } + + private Filter DoWork (FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback) + { + _logger.Info(CultureInfo.InvariantCulture, "Started Filter worker [{0}] for line {1}", Environment.CurrentManagedThreadId, startLine); + + // Give every thread own copies of ColumnizerCallback and FilterParams, because the state of the objects changes while filtering + var threadFilterParams = filterParams.CloneWithCurrentColumnizer(); + Filter filter = new((ColumnizerCallback)_callback.Clone()); + lock (_filterWorkerList) + { + _filterWorkerList.Add(filter); + } + + if (!_shouldStop) + { + + _ = filter.DoFilter(threadFilterParams, startLine, maxCount, progressCallback); + _logger.Info(CultureInfo.InvariantCulture, "Filter worker [{0}] for line {1} has completed.", Environment.CurrentManagedThreadId, startLine); + + lock (_filterReadyList) + { + _filterReadyList.Add(filter); + } + } + + return filter; + } + + private void FilterDoneCallback (Filter filter) + { + lock (_filterReadyList) + { + _filterReadyList.Add(filter); + } + } + + private void MergeResults () + { + _logger.Info(CultureInfo.InvariantCulture, "Merging filter results."); + foreach (var filter in _filterReadyList) + { + foreach (var lineNum in filter.FilterHitList) + { + if (!_filterHitDict.ContainsKey(lineNum)) + { + _filterHitDict.Add(lineNum, lineNum); + } + } + + foreach (var lineNum in filter.FilterResultLines) + { + if (!_filterResultDict.ContainsKey(lineNum)) + { + _filterResultDict.Add(lineNum, lineNum); + } + } + + foreach (var lineNum in filter.LastFilterLinesList) + { + if (!_lastFilterLinesDict.ContainsKey(lineNum)) + { + _lastFilterLinesDict.Add(lineNum, lineNum); + } + } + } + + FilterHitList.AddRange(_filterHitDict.Keys); + FilterResultLines.AddRange(_filterResultDict.Keys); + LastFilterLinesList.AddRange(_lastFilterLinesDict.Keys); + _logger.Info(CultureInfo.InvariantCulture, "Merging done."); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Highlight/ActionEntry.cs b/src/LogExpert.Core/Classes/Highlight/ActionEntry.cs new file mode 100644 index 00000000..7db9d052 --- /dev/null +++ b/src/LogExpert.Core/Classes/Highlight/ActionEntry.cs @@ -0,0 +1,24 @@ +namespace LogExpert.Core.Classes.Highlight; + +[Serializable] +public class ActionEntry : ICloneable +{ + #region Fields + + public string ActionParam { get; set; } + + public string PluginName { get; set; } + + public object Clone() + { + var actionEntry = new ActionEntry + { + PluginName = PluginName, + ActionParam = ActionParam + }; + + return actionEntry; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Highlight/HighlightEntry.cs b/src/LogExpert.Core/Classes/Highlight/HighlightEntry.cs new file mode 100644 index 00000000..aed89b99 --- /dev/null +++ b/src/LogExpert.Core/Classes/Highlight/HighlightEntry.cs @@ -0,0 +1,106 @@ +using Newtonsoft.Json; + +using System.Drawing; +using System.Text.RegularExpressions; + +namespace LogExpert.Core.Classes.Highlight; + +[Serializable] +[method: JsonConstructor] +public class HighlightEntry() : ICloneable +{ + #region Fields + + [NonSerialized] private Regex regex = null; + + private string _searchText = string.Empty; + + #endregion Fields + + #region Properties + + public bool IsStopTail { get; set; } + + public bool IsSetBookmark { get; set; } + + public bool IsRegEx { get; set; } + + public bool IsCaseSensitive { get; set; } + + public Color ForegroundColor { get; set; } + + public Color BackgroundColor { get; set; } + + public string SearchText + { + get => _searchText; + set + { + _searchText = value; + regex = null; + } + } + + public bool IsLedSwitch { get; set; } + + public ActionEntry ActionEntry { get; set; } + + public bool IsActionEntry { get; set; } + + public string BookmarkComment { get; set; } + + public Regex Regex + { + get + { + if (regex == null) + { + if (IsRegEx) + { + regex = new Regex(SearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + } + else + { + regex = new Regex(Regex.Escape(SearchText), IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + } + } + return regex; + } + } + + public bool IsWordMatch { get; set; } + + // highlightes search result + [field: NonSerialized] + public bool IsSearchHit { get; set; } + + public bool IsBold { get; set; } + + public bool NoBackground { get; set; } + + public object Clone() + { + var highLightEntry = new HighlightEntry + { + SearchText = SearchText, + ForegroundColor = ForegroundColor, + BackgroundColor = BackgroundColor, + IsRegEx = IsRegEx, + IsCaseSensitive = IsCaseSensitive, + IsLedSwitch = IsLedSwitch, + IsStopTail = IsStopTail, + IsSetBookmark = IsSetBookmark, + IsActionEntry = IsActionEntry, + ActionEntry = ActionEntry != null ? (ActionEntry)ActionEntry.Clone() : null, + IsWordMatch = IsWordMatch, + IsBold = IsBold, + BookmarkComment = BookmarkComment, + NoBackground = NoBackground, + IsSearchHit = IsSearchHit + }; + + return highLightEntry; + } + + #endregion Properties +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Highlight/HighlightMatchEntry.cs b/src/LogExpert.Core/Classes/Highlight/HighlightMatchEntry.cs new file mode 100644 index 00000000..91c38160 --- /dev/null +++ b/src/LogExpert.Core/Classes/Highlight/HighlightMatchEntry.cs @@ -0,0 +1,26 @@ +namespace LogExpert.Core.Classes.Highlight; + +/// +/// Class for storing word-wise highlight matches. Used for colouring different matches on one line. +/// +public class HighlightMatchEntry +{ + #region Properties + + public HighlightEntry HighlightEntry { get; set; } + + public int StartPos { get; set; } + + public int Length { get; set; } + + #endregion + + #region Public methods + + public override string ToString () + { + return $"{HighlightEntry.SearchText}/{StartPos}/{Length}"; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/IPC/IpcMessage.cs b/src/LogExpert.Core/Classes/IPC/IpcMessage.cs new file mode 100644 index 00000000..d52fd1f1 --- /dev/null +++ b/src/LogExpert.Core/Classes/IPC/IpcMessage.cs @@ -0,0 +1,12 @@ +using Newtonsoft.Json.Linq; + +namespace LogExpert.Core.Classes.IPC; + +public class IpcMessage +{ + public int Version { get; set; } + + public IpcMessageType Type { get; set; } = IpcMessageType.Load; + + public JObject Payload { get; set; } = []; +} diff --git a/src/LogExpert.Core/Classes/IPC/IpcMessageType.cs b/src/LogExpert.Core/Classes/IPC/IpcMessageType.cs new file mode 100644 index 00000000..cd22d52c --- /dev/null +++ b/src/LogExpert.Core/Classes/IPC/IpcMessageType.cs @@ -0,0 +1,8 @@ +namespace LogExpert.Core.Classes.IPC; + +public enum IpcMessageType +{ + Load, + NewWindow, + NewWindowOrLockedWindow +} diff --git a/src/LogExpert.Core/Classes/IPC/LoadPayload.cs b/src/LogExpert.Core/Classes/IPC/LoadPayload.cs new file mode 100644 index 00000000..80e3f114 --- /dev/null +++ b/src/LogExpert.Core/Classes/IPC/LoadPayload.cs @@ -0,0 +1,6 @@ +namespace LogExpert.Core.Classes.IPC; + +public class LoadPayload +{ + public List Files { get; set; } = []; +} diff --git a/src/LogExpert.Core/Classes/Log/LogBuffer.cs b/src/LogExpert.Core/Classes/Log/LogBuffer.cs new file mode 100644 index 00000000..72ee1062 --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/LogBuffer.cs @@ -0,0 +1,123 @@ +using NLog; + +namespace LogExpert.Core.Classes.Log; + +public class LogBuffer +{ + #region Fields + + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + +#if DEBUG + private readonly IList _filePositions = new List(); // file position for every line +#endif + + private readonly IList _logLines = new List(); + private int MAX_LINES = 500; + private long _size; + + #endregion + + #region cTor + + //public LogBuffer() { } + + public LogBuffer(ILogFileInfo fileInfo, int maxLines) + { + FileInfo = fileInfo; + MAX_LINES = maxLines; + } + + #endregion + + #region Properties + + public long StartPos { set; get; } + + public long Size + { + set + { + _size = value; +#if DEBUG + if (_filePositions.Count > 0) + { + if (_size < _filePositions[_filePositions.Count - 1] - StartPos) + { + _logger.Error("LogBuffer overall Size must be greater than last line file position!"); + } + } +#endif + } + get => _size; + } + + public int StartLine { set; get; } + + public int LineCount { get; private set; } + + public bool IsDisposed { get; private set; } + + public ILogFileInfo FileInfo { get; set; } + + public int DroppedLinesCount { get; set; } + + public int PrevBuffersDroppedLinesSum { get; set; } + + #endregion + + #region Public methods + + public void AddLine(ILogLine line, long filePos) + { + _logLines.Add(line); +#if DEBUG + _filePositions.Add(filePos); +#endif + LineCount++; + IsDisposed = false; + } + + public void ClearLines() + { + _logLines.Clear(); + LineCount = 0; + } + + public void DisposeContent() + { + _logLines.Clear(); + IsDisposed = true; +#if DEBUG + DisposeCount++; +#endif + } + + public ILogLine GetLineOfBlock(int num) + { + if (num < _logLines.Count && num >= 0) + { + return _logLines[num]; + } + + return null; + } + + #endregion + +#if DEBUG + public long DisposeCount { get; private set; } + + + public long GetFilePosForLineOfBlock(int line) + { + if (line >= 0 && line < _filePositions.Count) + { + return _filePositions[line]; + } + + return -1; + } + +#endif +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/LogBufferCacheEntry.cs b/src/LogExpert.Core/Classes/Log/LogBufferCacheEntry.cs new file mode 100644 index 00000000..0683012e --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/LogBufferCacheEntry.cs @@ -0,0 +1,34 @@ +namespace LogExpert.Core.Classes.Log; + +public class LogBufferCacheEntry +{ + #region Fields + + #endregion + + #region cTor + + public LogBufferCacheEntry() + { + Touch(); + } + + #endregion + + #region Properties + + public LogBuffer LogBuffer { get; set; } + + public long LastUseTimeStamp { get; private set; } + + #endregion + + #region Public methods + + public void Touch() + { + LastUseTimeStamp = Environment.TickCount & int.MaxValue; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/LogStreamReaderBase.cs b/src/LogExpert.Core/Classes/Log/LogStreamReaderBase.cs new file mode 100644 index 00000000..58b0b0bf --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/LogStreamReaderBase.cs @@ -0,0 +1,63 @@ +using System; +using System.Text; + +using LogExpert.Core.Interface; + +namespace LogExpert.Core.Classes.Log; + +public abstract class LogStreamReaderBase : ILogStreamReader +{ + #region cTor + + protected LogStreamReaderBase() + { + + } + + ~LogStreamReaderBase() + { + Dispose(false); + } + + #endregion + + #region Properties + + /// + /// Current position in the stream. + /// + public abstract long Position { get; set; } + + public abstract bool IsBufferComplete { get; } + + public abstract Encoding Encoding { get; } + + /// + /// Indicates whether or not the stream reader has already been disposed. + /// + public abstract bool IsDisposed { get; protected set; } + + #endregion + + #region Public methods + + /// + /// Destroy and release the current stream reader. + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + /// + /// Destroy and release the current stream reader. + /// + /// Specifies whether or not the managed objects should be released. + protected abstract void Dispose(bool disposing); + + public abstract int ReadChar(); + + public abstract string ReadLine(); + + #endregion +} diff --git a/src/LogExpert.Core/Classes/Log/LogfileReader.cs b/src/LogExpert.Core/Classes/Log/LogfileReader.cs new file mode 100644 index 00000000..424e1c34 --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/LogfileReader.cs @@ -0,0 +1,1857 @@ +using System.Globalization; +using System.Text; + +using LogExpert.Core.Classes.xml; +using LogExpert.Core.Entities; +using LogExpert.Core.EventArguments; +using LogExpert.Core.Interface; + +using NLog; + +namespace LogExpert.Core.Classes.Log; + +public class LogfileReader : IAutoLogLineColumnizerCallback, IDisposable +{ + #region Fields + + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + + private readonly GetLogLineFx _logLineFx; + + private readonly string _fileName; + private readonly int _max_buffers; + private readonly int _maxLinesPerBuffer; + + private readonly object _monitor = new(); + private readonly MultiFileOptions _multiFileOptions; + private readonly IPluginRegistry _pluginRegistry; + private IList _bufferList; + private ReaderWriterLock _bufferListLock; + private bool _contentDeleted; + private int _currLineCount; + private ReaderWriterLock _disposeLock; + private EncodingOptions _encodingOptions; + private long _fileLength; + + private Task _garbageCollectorTask; + private Task _monitorTask; + private readonly CancellationTokenSource _cts = new(); + + private bool _isDeleted; + private bool _isFailModeCheckCallPending; + private bool _isFastFailOnGetLogLine; + private bool _isLineCountDirty = true; + private IList _logFileInfoList = []; + private Dictionary _lruCacheDict; + + private ReaderWriterLock _lruCacheDictLock; + + private bool _shouldStop; + private bool _disposed; + private ILogFileInfo _watchedILogFileInfo; + + #endregion + + #region cTor + + public LogfileReader (string fileName, EncodingOptions encodingOptions, bool multiFile, int bufferCount, int linesPerBuffer, MultiFileOptions multiFileOptions, IPluginRegistry pluginRegistry) + { + if (fileName == null) + { + return; + } + + _fileName = fileName; + EncodingOptions = encodingOptions; + IsMultiFile = multiFile; + _max_buffers = bufferCount; + _maxLinesPerBuffer = linesPerBuffer; + _multiFileOptions = multiFileOptions; + _pluginRegistry = pluginRegistry; + _logLineFx = GetLogLineInternal; + _disposed = false; + + InitLruBuffers(); + + if (multiFile) + { + var info = GetLogFileInfo(fileName); + RolloverFilenameHandler rolloverHandler = new(info, _multiFileOptions); + var nameList = rolloverHandler.GetNameList(_pluginRegistry); + + ILogFileInfo fileInfo = null; + foreach (var name in nameList) + { + fileInfo = AddFile(name); + } + + _watchedILogFileInfo = fileInfo; // last added file in the list is the watched file + } + else + { + _watchedILogFileInfo = AddFile(fileName); + } + + StartGCThread(); + } + + public LogfileReader (string[] fileNames, EncodingOptions encodingOptions, int bufferCount, int linesPerBuffer, MultiFileOptions multiFileOptions, IPluginRegistry pluginRegistry) + { + if (fileNames == null || fileNames.Length < 1) + { + return; + } + + EncodingOptions = encodingOptions; + IsMultiFile = true; + _max_buffers = bufferCount; + _maxLinesPerBuffer = linesPerBuffer; + _multiFileOptions = multiFileOptions; + _pluginRegistry = pluginRegistry; + _logLineFx = GetLogLineInternal; + _disposed = false; + + InitLruBuffers(); + + ILogFileInfo fileInfo = null; + foreach (var name in fileNames) + { + fileInfo = AddFile(name); + } + + _watchedILogFileInfo = fileInfo; + _fileName = fileInfo.FullName; + + StartGCThread(); + } + + #endregion + + #region Delegates + + private delegate Task GetLogLineFx (int lineNum); + + #endregion + + #region Events + + public event EventHandler FileSizeChanged; + public event EventHandler LoadFile; + public event EventHandler LoadingStarted; + public event EventHandler LoadingFinished; + public event EventHandler FileNotFound; + public event EventHandler Respawned; + + #endregion + + #region Properties + + public int LineCount + { + get + { + if (_isLineCountDirty) + { + _currLineCount = 0; + AcquireBufferListReaderLock(); + foreach (var buffer in _bufferList) + { + _currLineCount += buffer.LineCount; + } + + ReleaseBufferListReaderLock(); + _isLineCountDirty = false; + } + + return _currLineCount; + } + set => _currLineCount = value; + } + + public bool IsMultiFile { get; } + + public Encoding CurrentEncoding { get; private set; } + + public long FileSize { get; private set; } + + public bool IsXmlMode { get; set; } + + public IXmlLogConfiguration XmlLogConfig { get; set; } + + public IPreProcessColumnizer PreProcessColumnizer { get; set; } + + public EncodingOptions EncodingOptions + { + get => _encodingOptions; + set + { + { + _encodingOptions = new EncodingOptions + { + DefaultEncoding = value.DefaultEncoding, + Encoding = value.Encoding + }; + } + } + } + + public bool UseNewReader { get; set; } + + #endregion + + #region Public methods + + /// + /// Public for unit test reasons + /// + public void ReadFiles () + { + FileSize = 0; + LineCount = 0; + //this.lastReturnedLine = ""; + //this.lastReturnedLineNum = -1; + //this.lastReturnedLineNumForBuffer = -1; + _isDeleted = false; + ClearLru(); + AcquireBufferListWriterLock(); + _bufferList.Clear(); + ReleaseBufferListWriterLock(); + try + { + foreach (var info in _logFileInfoList) + { + //info.OpenFile(); + ReadToBufferList(info, 0, LineCount); + } + + if (_logFileInfoList.Count > 0) + { + var info = _logFileInfoList[_logFileInfoList.Count - 1]; + _fileLength = info.Length; + _watchedILogFileInfo = info; + } + } + catch (IOException e) + { + _logger.Warn(e, "IOException"); + _fileLength = 0; + _isDeleted = true; + LineCount = 0; + } + + LogEventArgs args = new() + { + PrevFileSize = 0, + PrevLineCount = 0, + LineCount = LineCount, + FileSize = FileSize + }; + + OnFileSizeChanged(args); + } + + /// + /// Public for unit tests. + /// + /// + public int ShiftBuffers () + { + _logger.Info(CultureInfo.InvariantCulture, "ShiftBuffers() begin for {0}{1}", _fileName, IsMultiFile ? " (MultiFile)" : ""); + AcquireBufferListWriterLock(); + var offset = 0; + _isLineCountDirty = true; + lock (_monitor) + { + RolloverFilenameHandler rolloverHandler = new(_watchedILogFileInfo, _multiFileOptions); + var fileNameList = rolloverHandler.GetNameList(_pluginRegistry); + + ResetBufferCache(); + IList lostILogFileInfoList = []; + IList readNewILogFileInfoList = []; + IList newFileInfoList = []; + var enumerator = _logFileInfoList.GetEnumerator(); + while (enumerator.MoveNext()) + { + var logFileInfo = enumerator.Current; + var fileName = logFileInfo.FullName; + _logger.Debug(CultureInfo.InvariantCulture, "Testing file {0}", fileName); + var node = fileNameList.Find(fileName); + if (node == null) + { + _logger.Warn(CultureInfo.InvariantCulture, "File {0} not found", fileName); + continue; + } + + if (node.Previous != null) + { + fileName = node.Previous.Value; + var newILogFileInfo = GetLogFileInfo(fileName); + _logger.Debug(CultureInfo.InvariantCulture, "{0} exists\r\nOld size={1}, new size={2}", fileName, logFileInfo.OriginalLength, newILogFileInfo.Length); + // is the new file the same as the old buffer info? + if (newILogFileInfo.Length == logFileInfo.OriginalLength) + { + ReplaceBufferInfos(logFileInfo, newILogFileInfo); + newFileInfoList.Add(newILogFileInfo); + } + else + { + _logger.Debug(CultureInfo.InvariantCulture, "Buffer for {0} must be re-read.", fileName); + // not the same. so must read the rest of the list anew from the files + readNewILogFileInfoList.Add(newILogFileInfo); + while (enumerator.MoveNext()) + { + fileName = enumerator.Current.FullName; + node = fileNameList.Find(fileName); + if (node == null) + { + _logger.Warn(CultureInfo.InvariantCulture, "File {0} not found", fileName); + continue; + } + + if (node.Previous != null) + { + fileName = node.Previous.Value; + _logger.Debug(CultureInfo.InvariantCulture, "New name is {0}", fileName); + readNewILogFileInfoList.Add(GetLogFileInfo(fileName)); + } + else + { + _logger.Warn(CultureInfo.InvariantCulture, "No previous file for {0} found", fileName); + } + } + } + } + else + { + _logger.Info(CultureInfo.InvariantCulture, "{0} does not exist", fileName); + lostILogFileInfoList.Add(logFileInfo); +#if DEBUG // for better overview in logfile: + //ILogFileInfo newILogFileInfo = new ILogFileInfo(fileName); + //ReplaceBufferInfos(ILogFileInfo, newILogFileInfo); +#endif + } + } + + if (lostILogFileInfoList.Count > 0) + { + _logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for lost files"); + foreach (var ILogFileInfo in lostILogFileInfoList) + { + //this.ILogFileInfoList.Remove(ILogFileInfo); + var lastBuffer = DeleteBuffersForInfo(ILogFileInfo, false); + if (lastBuffer != null) + { + offset += lastBuffer.StartLine + lastBuffer.LineCount; + } + } + + _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); + _logger.Info(CultureInfo.InvariantCulture, "Adjusting StartLine values in {0} buffers by offset {1}", _bufferList.Count, offset); + foreach (var buffer in _bufferList) + { + SetNewStartLineForBuffer(buffer, buffer.StartLine - offset); + } + + _lruCacheDictLock.ReleaseWriterLock(); +#if DEBUG + if (_bufferList.Count > 0) + { + _logger.Debug(CultureInfo.InvariantCulture, "First buffer now has StartLine {0}", _bufferList[0].StartLine); + } +#endif + } + + // Read anew all buffers following a buffer info that couldn't be matched with the corresponding existing file + _logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for files that must be re-read"); + foreach (var ILogFileInfo in readNewILogFileInfoList) + { + DeleteBuffersForInfo(ILogFileInfo, true); + //this.ILogFileInfoList.Remove(ILogFileInfo); + } + + _logger.Info(CultureInfo.InvariantCulture, "Deleting buffers for the watched file"); + DeleteBuffersForInfo(_watchedILogFileInfo, true); + var startLine = LineCount - 1; + _logger.Info(CultureInfo.InvariantCulture, "Re-Reading files"); + foreach (var ILogFileInfo in readNewILogFileInfoList) + { + //ILogFileInfo.OpenFile(); + ReadToBufferList(ILogFileInfo, 0, LineCount); + //this.ILogFileInfoList.Add(ILogFileInfo); + newFileInfoList.Add(ILogFileInfo); + } + + //this.watchedILogFileInfo = this.ILogFileInfoList[this.ILogFileInfoList.Count - 1]; + _logFileInfoList = newFileInfoList; + _watchedILogFileInfo = GetLogFileInfo(_watchedILogFileInfo.FullName); + _logFileInfoList.Add(_watchedILogFileInfo); + _logger.Info(CultureInfo.InvariantCulture, "Reading watched file"); + ReadToBufferList(_watchedILogFileInfo, 0, LineCount); + } + + _logger.Info(CultureInfo.InvariantCulture, "ShiftBuffers() end. offset={0}", offset); + ReleaseBufferListWriterLock(); + return offset; + } + + public ILogLine GetLogLine (int lineNum) + { + return GetLogLineInternal(lineNum).Result; + } + + /// + /// Get the text content of the given line number. + /// The actual work is done in an async thread. This method waits for thread completion for only 1 second. If the async + /// thread has not returned, the method will return null. This is because this method is also called from GUI thread + /// (e.g. LogWindow draw events). Under some circumstances, repeated calls to this method would lead the GUI to freeze. E.g. when + /// trying to re-load content from disk but the file was deleted. Especially on network shares. + /// + /// + /// Once the method detects a timeout it will enter a kind of 'fast fail mode'. That means all following calls will be returned with + /// null immediately (without 1 second wait). A background call to GetLogLineInternal() will check if a result is available. + /// If so, the 'fast fail mode' is switched off. In most cases a fail is caused by a deleted file. But it may also be caused by slow + /// network connections. So all this effort is needed to prevent entering an endless 'fast fail mode' just because of temporary problems. + /// + /// line to retrieve + /// + public async Task GetLogLineWithWait (int lineNum) + { + const int WAIT_TIME = 1000; + + ILogLine result = null; + + if (!_isFastFailOnGetLogLine) + { + var task = Task.Run(() => _logLineFx(lineNum)); + if (task.Wait(WAIT_TIME)) + { + result = task.Result; + _isFastFailOnGetLogLine = false; + } + else + { + _isFastFailOnGetLogLine = true; + _logger.Debug(CultureInfo.InvariantCulture, "No result after {0}ms. Returning .", WAIT_TIME); + } + } + else + { + _logger.Debug(CultureInfo.InvariantCulture, "Fast failing GetLogLine()"); + if (!_isFailModeCheckCallPending) + { + _isFailModeCheckCallPending = true; + var logLine = await _logLineFx(lineNum); + GetLineFinishedCallback(logLine); + } + } + + return result; + } + + /// + /// Returns the file name of the actual file for the given line. Needed for MultiFile. + /// + /// + /// + public string GetLogFileNameForLine (int lineNum) + { + AcquireBufferListReaderLock(); + var logBuffer = GetBufferForLine(lineNum); + var fileName = logBuffer?.FileInfo.FullName; + ReleaseBufferListReaderLock(); + return fileName; + } + + /// + /// Returns the ILogFileInfo for the actual file for the given line. Needed for MultiFile. + /// + /// + /// + public ILogFileInfo GetLogFileInfoForLine (int lineNum) + { + AcquireBufferListReaderLock(); + var logBuffer = GetBufferForLine(lineNum); + var info = logBuffer?.FileInfo; + ReleaseBufferListReaderLock(); + return info; + } + + /// + /// Returns the line number (starting from the given number) where the next multi file + /// starts. + /// + /// + /// + public int GetNextMultiFileLine (int lineNum) + { + var result = -1; + AcquireBufferListReaderLock(); + var logBuffer = GetBufferForLine(lineNum); + if (logBuffer != null) + { + var index = _bufferList.IndexOf(logBuffer); + if (index != -1) + { + for (var i = index; i < _bufferList.Count; ++i) + { + if (_bufferList[i].FileInfo != logBuffer.FileInfo) + { + result = _bufferList[i].StartLine; + break; + } + } + } + } + + ReleaseBufferListReaderLock(); + return result; + } + + public int GetPrevMultiFileLine (int lineNum) + { + var result = -1; + AcquireBufferListReaderLock(); + var logBuffer = GetBufferForLine(lineNum); + if (logBuffer != null) + { + var index = _bufferList.IndexOf(logBuffer); + if (index != -1) + { + for (var i = index; i >= 0; --i) + { + if (_bufferList[i].FileInfo != logBuffer.FileInfo) + { + result = _bufferList[i].StartLine + _bufferList[i].LineCount; + break; + } + } + } + } + + ReleaseBufferListReaderLock(); + return result; + } + + /// + /// Returns the actual line number in the file for the given 'virtual line num'. + /// This is needed for multi file mode. 'Virtual' means that the given line num is a line + /// number in the collections of the files currently viewed together in multi file mode as one large virtual file. + /// This method finds the real file for the line number and maps the line number to the correct position + /// in that file. This is needed when launching external tools to provide correct line number arguments. + /// + /// + /// + public int GetRealLineNumForVirtualLineNum (int lineNum) + { + AcquireBufferListReaderLock(); + var logBuffer = GetBufferForLine(lineNum); + var result = -1; + if (logBuffer != null) + { + logBuffer = GetFirstBufferForFileByLogBuffer(logBuffer); + if (logBuffer != null) + { + result = lineNum - logBuffer.StartLine; + } + } + + ReleaseBufferListReaderLock(); + return result; + } + + public void StartMonitoring () + { + _logger.Info(CultureInfo.InvariantCulture, "startMonitoring()"); + _monitorTask = Task.Run(MonitorThreadProc, _cts.Token); + _shouldStop = false; + } + + public void StopMonitoring () + { + _logger.Info(CultureInfo.InvariantCulture, "stopMonitoring()"); + _shouldStop = true; + + Thread.Sleep(_watchedILogFileInfo.PollInterval); // leave time for the threads to stop by themselves + + if (_monitorTask != null) + { + if (_monitorTask.Status == TaskStatus.Running) // if thread has not finished, abort it + { + _cts.Cancel(); + } + } + + if (_garbageCollectorTask.IsCanceled == false) + { + if (_garbageCollectorTask.Status == TaskStatus.Running) // if thread has not finished, abort it + { + _cts.Cancel(); + } + } + + //this.loadThread = null; + //_monitorThread = null; + //_garbageCollectorThread = null; // preventive call + CloseFiles(); + } + + /// + /// calls stopMonitoring() in a background thread and returns to the caller immediately. + /// This is useful for a fast responding GUI (e.g. when closing a file tab) + /// + public void StopMonitoringAsync () + { + var task = Task.Run(StopMonitoring); + + //Thread stopperThread = new(new ThreadStart(StopMonitoring)) + //{ + // IsBackground = true + //}; + //stopperThread.Start(); + } + + /// + /// Deletes all buffer lines and disposes their content. Use only when the LogfileReader + /// is about to be closed! + /// + public void DeleteAllContent () + { + if (_contentDeleted) + { + _logger.Debug(CultureInfo.InvariantCulture, "Buffers for {0} already deleted.", Util.GetNameFromPath(_fileName)); + return; + } + + _logger.Info(CultureInfo.InvariantCulture, "Deleting all log buffers for {0}. Used mem: {1:N0}", Util.GetNameFromPath(_fileName), GC.GetTotalMemory(true)); //TODO [Z] uh GC collect calls creepy + AcquireBufferListWriterLock(); + _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); + _disposeLock.AcquireWriterLock(Timeout.Infinite); + + foreach (var logBuffer in _bufferList) + { + if (!logBuffer.IsDisposed) + { + logBuffer.DisposeContent(); + } + } + + _lruCacheDict.Clear(); + _bufferList.Clear(); + + _disposeLock.ReleaseWriterLock(); + _lruCacheDictLock.ReleaseWriterLock(); + ReleaseBufferListWriterLock(); + GC.Collect(); + _contentDeleted = true; + _logger.Info(CultureInfo.InvariantCulture, "Deleting complete. Used mem: {0:N0}", GC.GetTotalMemory(true)); //TODO [Z] uh GC collect calls creepy + } + + /// + /// Explicit change the encoding. + /// + /// + public void ChangeEncoding (Encoding encoding) + { + CurrentEncoding = encoding; + EncodingOptions.Encoding = encoding; + ResetBufferCache(); + ClearLru(); + } + + /// + /// For unit tests only. + /// + /// + public IList GetLogFileInfoList () + { + return _logFileInfoList; + } + + /// + /// For unit tests only + /// + /// + public IList GetBufferList () + { + return _bufferList; + } + + #endregion + + #region Internals + +#if DEBUG + + public void LogBufferInfoForLine (int lineNum) + { + AcquireBufferListReaderLock(); + var buffer = GetBufferForLine(lineNum); + if (buffer == null) + { + ReleaseBufferListReaderLock(); + _logger.Error("Cannot find buffer for line {0}, file: {1}{2}", lineNum, _fileName, IsMultiFile ? " (MultiFile)" : ""); + return; + } + + _logger.Info(CultureInfo.InvariantCulture, "-----------------------------------"); + _disposeLock.AcquireReaderLock(Timeout.Infinite); + _logger.Info(CultureInfo.InvariantCulture, "Buffer info for line {0}", lineNum); + DumpBufferInfos(buffer); + _logger.Info(CultureInfo.InvariantCulture, "File pos for current line: {0}", buffer.GetFilePosForLineOfBlock(lineNum - buffer.StartLine)); + _disposeLock.ReleaseReaderLock(); + _logger.Info(CultureInfo.InvariantCulture, "-----------------------------------"); + ReleaseBufferListReaderLock(); + } +#endif + +#if DEBUG + public void LogBufferDiagnostic () + { + _logger.Info(CultureInfo.InvariantCulture, "-------- Buffer diagnostics -------"); + _lruCacheDictLock.AcquireReaderLock(Timeout.Infinite); + var cacheCount = _lruCacheDict.Count; + _logger.Info(CultureInfo.InvariantCulture, "LRU entries: {0}", cacheCount); + _lruCacheDictLock.ReleaseReaderLock(); + + AcquireBufferListReaderLock(); + _logger.Info(CultureInfo.InvariantCulture, "File: {0}\r\nBuffer count: {1}\r\nDisposed buffers: {2}", _fileName, _bufferList.Count, _bufferList.Count - cacheCount); + var lineNum = 0; + long disposeSum = 0; + long maxDispose = 0; + long minDispose = int.MaxValue; + for (var i = 0; i < _bufferList.Count; ++i) + { + var buffer = _bufferList[i]; + _disposeLock.AcquireReaderLock(Timeout.Infinite); + if (buffer.StartLine != lineNum) + { + _logger.Error("Start line of buffer is: {0}, expected: {1}", buffer.StartLine, lineNum); + _logger.Info(CultureInfo.InvariantCulture, "Info of buffer follows:"); + DumpBufferInfos(buffer); + } + + lineNum += buffer.LineCount; + disposeSum += buffer.DisposeCount; + maxDispose = Math.Max(maxDispose, buffer.DisposeCount); + minDispose = Math.Min(minDispose, buffer.DisposeCount); + _disposeLock.ReleaseReaderLock(); + } + + ReleaseBufferListReaderLock(); + _logger.Info(CultureInfo.InvariantCulture, "Dispose count sum is: {0}\r\nMin dispose count is: {1}\r\nMax dispose count is: {2}\r\n-----------------------------------", disposeSum, minDispose, maxDispose); + } + +#endif + + #endregion + + #region Private Methods + + private ILogFileInfo AddFile (string fileName) + { + _logger.Info(CultureInfo.InvariantCulture, "Adding file to ILogFileInfoList: " + fileName); + var info = GetLogFileInfo(fileName); + _logFileInfoList.Add(info); + return info; + } + + private Task GetLogLineInternal (int lineNum) + { + if (_isDeleted) + { + _logger.Debug(CultureInfo.InvariantCulture, "Returning null for line {0} because file is deleted.", lineNum); + + // fast fail if dead file was detected. Prevents repeated lags in GUI thread caused by callbacks from control (e.g. repaint) + return null; + } + + AcquireBufferListReaderLock(); + var logBuffer = GetBufferForLine(lineNum); + if (logBuffer == null) + { + ReleaseBufferListReaderLock(); + _logger.Error("Cannot find buffer for line {0}, file: {1}{2}", lineNum, _fileName, IsMultiFile ? " (MultiFile)" : ""); + return null; + } + + // disposeLock prevents that the garbage collector is disposing just in the moment we use the buffer + _disposeLock.AcquireReaderLock(Timeout.Infinite); + if (logBuffer.IsDisposed) + { + var cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); + lock (logBuffer.FileInfo) + { + ReReadBuffer(logBuffer); + } + + _disposeLock.DowngradeFromWriterLock(ref cookie); + } + + var line = logBuffer.GetLineOfBlock(lineNum - logBuffer.StartLine); + _disposeLock.ReleaseReaderLock(); + ReleaseBufferListReaderLock(); + + return Task.FromResult(line); + } + + private void InitLruBuffers () + { + _bufferList = []; + //_bufferLru = new List(_max_buffers + 1); + //this.lruDict = new Dictionary(this.MAX_BUFFERS + 1); // key=startline, value = index in bufferLru + _lruCacheDict = new Dictionary(_max_buffers + 1); + _lruCacheDictLock = new ReaderWriterLock(); + _bufferListLock = new ReaderWriterLock(); + _disposeLock = new ReaderWriterLock(); + } + + private void StartGCThread () + { + _garbageCollectorTask = Task.Run(GarbageCollectorThreadProc, _cts.Token); + //_garbageCollectorThread = new Thread(new ThreadStart(GarbageCollectorThreadProc)); + //_garbageCollectorThread.IsBackground = true; + //_garbageCollectorThread.Start(); + } + + private void ResetBufferCache () + { + FileSize = 0; + LineCount = 0; + //this.lastReturnedLine = ""; + //this.lastReturnedLineNum = -1; + //this.lastReturnedLineNumForBuffer = -1; + } + + private void CloseFiles () + { + //foreach (ILogFileInfo info in this.ILogFileInfoList) + //{ + // info.CloseFile(); + //} + FileSize = 0; + LineCount = 0; + //this.lastReturnedLine = ""; + //this.lastReturnedLineNum = -1; + //this.lastReturnedLineNumForBuffer = -1; + } + + private ILogFileInfo GetLogFileInfo (string fileNameOrUri) //TODO: I changed to static + { + //TODO this must be fixed and should be given to the logfilereader not just called (https://github.com/LogExperts/LogExpert/issues/402) + var fs = _pluginRegistry.FindFileSystemForUri(fileNameOrUri) ?? throw new LogFileException("No file system plugin found for " + fileNameOrUri); + var logFileInfo = fs.GetLogfileInfo(fileNameOrUri); + return logFileInfo ?? throw new LogFileException("Cannot find " + fileNameOrUri); + } + + private void ReplaceBufferInfos (ILogFileInfo oldLogFileInfo, ILogFileInfo newLogFileInfo) + { + _logger.Debug(CultureInfo.InvariantCulture, "ReplaceBufferInfos() " + oldLogFileInfo.FullName + " -> " + newLogFileInfo.FullName); + AcquireBufferListReaderLock(); + foreach (var buffer in _bufferList) + { + if (buffer.FileInfo == oldLogFileInfo) + { + _logger.Debug($"Buffer with startLine={buffer.StartLine}, lineCount={buffer.LineCount}, filePos={buffer.StartPos}, size={buffer.Size} gets new filename {newLogFileInfo.FullName}"); + buffer.FileInfo = newLogFileInfo; + } + } + + ReleaseBufferListReaderLock(); + } + + private LogBuffer DeleteBuffersForInfo (ILogFileInfo ILogFileInfo, bool matchNamesOnly) + { + _logger.Info($"Deleting buffers for file {ILogFileInfo.FullName}"); + LogBuffer lastRemovedBuffer = null; + IList deleteList = []; + AcquireBufferListWriterLock(); + _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); + if (matchNamesOnly) + { + foreach (var buffer in _bufferList) + { + if (buffer.FileInfo.FullName.Equals(ILogFileInfo.FullName, StringComparison.Ordinal)) + { + lastRemovedBuffer = buffer; + deleteList.Add(buffer); + } + } + } + else + { + foreach (var buffer in _bufferList) + { + if (buffer.FileInfo == ILogFileInfo) + { + lastRemovedBuffer = buffer; + deleteList.Add(buffer); + } + } + } + + foreach (var buffer in deleteList) + { + RemoveFromBufferList(buffer); + } + + _lruCacheDictLock.ReleaseWriterLock(); + ReleaseBufferListWriterLock(); + if (lastRemovedBuffer == null) + { + _logger.Info(CultureInfo.InvariantCulture, "lastRemovedBuffer is null"); + } + else + { + _logger.Info(CultureInfo.InvariantCulture, "lastRemovedBuffer: startLine={0}", lastRemovedBuffer.StartLine); + } + + return lastRemovedBuffer; + } + + /// + /// The caller must have _writer locks for lruCache and buffer list! + /// + /// + private void RemoveFromBufferList (LogBuffer buffer) + { + Util.AssertTrue(_lruCacheDictLock.IsWriterLockHeld, "No _writer lock for lru cache"); + Util.AssertTrue(_bufferListLock.IsWriterLockHeld, "No _writer lock for buffer list"); + _lruCacheDict.Remove(buffer.StartLine); + _bufferList.Remove(buffer); + } + + private void ReadToBufferList (ILogFileInfo logFileInfo, long filePos, int startLine) + { + try + { + using var fileStream = logFileInfo.OpenStream(); + try + { + using var reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); + reader.Position = filePos; + _fileLength = logFileInfo.Length; + + var lineNum = startLine; + LogBuffer logBuffer; + AcquireBufferListReaderLock(); + if (_bufferList.Count == 0) + { + logBuffer = new LogBuffer(logFileInfo, _maxLinesPerBuffer) + { + StartLine = startLine, + StartPos = filePos + }; + var cookie = UpgradeBufferListLockToWriter(); + AddBufferToList(logBuffer); + DowngradeBufferListLockFromWriter(ref cookie); + } + else + { + logBuffer = _bufferList[_bufferList.Count - 1]; + + if (!logBuffer.FileInfo.FullName.Equals(logFileInfo.FullName, StringComparison.Ordinal)) + { + logBuffer = new LogBuffer(logFileInfo, _maxLinesPerBuffer) + { + StartLine = startLine, + StartPos = filePos + }; + var cookie = UpgradeBufferListLockToWriter(); + AddBufferToList(logBuffer); + DowngradeBufferListLockFromWriter(ref cookie); + } + + _disposeLock.AcquireReaderLock(Timeout.Infinite); + if (logBuffer.IsDisposed) + { + var cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); + ReReadBuffer(logBuffer); + _disposeLock.DowngradeFromWriterLock(ref cookie); + } + + _disposeLock.ReleaseReaderLock(); + } + + Monitor.Enter(logBuffer); // Lock the buffer + ReleaseBufferListReaderLock(); + var lineCount = logBuffer.LineCount; + var droppedLines = logBuffer.PrevBuffersDroppedLinesSum; + filePos = reader.Position; + + while (ReadLine(reader, logBuffer.StartLine + logBuffer.LineCount, logBuffer.StartLine + logBuffer.LineCount + droppedLines, out var line)) + { + LogLine logLine = new(); + if (_shouldStop) + { + Monitor.Exit(logBuffer); + return; + } + + if (line == null) + { + logBuffer.DroppedLinesCount += 1; + droppedLines++; + continue; + } + + lineCount++; + if (lineCount > _maxLinesPerBuffer && reader.IsBufferComplete) + { + OnLoadFile(new LoadFileEventArgs(logFileInfo.FullName, filePos, false, logFileInfo.Length, false)); + + Monitor.Exit(logBuffer); + logBuffer = new LogBuffer(logFileInfo, _maxLinesPerBuffer); + Monitor.Enter(logBuffer); + logBuffer.StartLine = lineNum; + logBuffer.StartPos = filePos; + logBuffer.PrevBuffersDroppedLinesSum = droppedLines; + AcquireBufferListWriterLock(); + AddBufferToList(logBuffer); + ReleaseBufferListWriterLock(); + lineCount = 1; + } + + logLine.FullLine = line; + logLine.LineNumber = logBuffer.StartLine + logBuffer.LineCount; + + logBuffer.AddLine(logLine, filePos); + filePos = reader.Position; + lineNum++; + } + + logBuffer.Size = filePos - logBuffer.StartPos; + Monitor.Exit(logBuffer); + _isLineCountDirty = true; + FileSize = reader.Position; + CurrentEncoding = reader.Encoding; // Reader may have detected another encoding + if (!_shouldStop) + { + OnLoadFile(new LoadFileEventArgs(logFileInfo.FullName, filePos, true, _fileLength, false)); + // Fire "Ready" Event + } + } + catch (IOException ioex) + { + _logger.Warn(ioex); + } + } + catch (IOException fe) + { + _logger.Warn(fe, "IOException: "); + _isDeleted = true; + LineCount = 0; + FileSize = 0; + OnFileNotFound(); // notify LogWindow + } + } + + private void AddBufferToList (LogBuffer logBuffer) + { +#if DEBUG + _logger.Debug(CultureInfo.InvariantCulture, "AddBufferToList(): {0}/{1}/{2}", logBuffer.StartLine, logBuffer.LineCount, logBuffer.FileInfo.FullName); +#endif + _bufferList.Add(logBuffer); + //UpdateLru(logBuffer); + UpdateLruCache(logBuffer); + } + + private void UpdateLruCache (LogBuffer logBuffer) + { + _lruCacheDictLock.AcquireReaderLock(Timeout.Infinite); + if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out var cacheEntry)) + { + cacheEntry.Touch(); + } + else + { + var cookie = _lruCacheDictLock.UpgradeToWriterLock(Timeout.Infinite); + if (!_lruCacheDict.TryGetValue(logBuffer.StartLine, out cacheEntry) + ) // #536: re-test, because multiple threads may have been waiting for _writer lock + { + cacheEntry = new LogBufferCacheEntry(); + cacheEntry.LogBuffer = logBuffer; + try + { + _lruCacheDict.Add(logBuffer.StartLine, cacheEntry); + } + catch (ArgumentException e) + { + _logger.Error(e, "Error in LRU cache: " + e.Message); +#if DEBUG // there seems to be a bug with double added key + + _logger.Info(CultureInfo.InvariantCulture, "Added buffer:"); + DumpBufferInfos(logBuffer); + if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out var existingEntry)) + { + _logger.Info(CultureInfo.InvariantCulture, "Existing buffer: "); + DumpBufferInfos(existingEntry.LogBuffer); + } + else + { + _logger.Warn(CultureInfo.InvariantCulture, "Ooops? Cannot find the already existing entry in LRU."); + } +#endif + _lruCacheDictLock.ReleaseLock(); + throw; + } + } + + _lruCacheDictLock.DowngradeFromWriterLock(ref cookie); + } + + _lruCacheDictLock.ReleaseReaderLock(); + } + + /// + /// Sets a new start line in the given buffer and updates the LRU cache, if the buffer + /// is present in the cache. The caller must have write lock for 'lruCacheDictLock'; + /// + /// + /// + private void SetNewStartLineForBuffer (LogBuffer logBuffer, int newLineNum) + { + Util.AssertTrue(_lruCacheDictLock.IsWriterLockHeld, "No _writer lock for lru cache"); + if (_lruCacheDict.ContainsKey(logBuffer.StartLine)) + { + _lruCacheDict.Remove(logBuffer.StartLine); + logBuffer.StartLine = newLineNum; + LogBufferCacheEntry cacheEntry = new(); + cacheEntry.LogBuffer = logBuffer; + _lruCacheDict.Add(logBuffer.StartLine, cacheEntry); + } + else + { + logBuffer.StartLine = newLineNum; + } + } + + private void GarbageCollectLruCache () + { +#if DEBUG + long startTime = Environment.TickCount; +#endif + _logger.Debug(CultureInfo.InvariantCulture, "Starting garbage collection"); + var threshold = 10; + _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); + var diff = 0; + if (_lruCacheDict.Count - (_max_buffers + threshold) > 0) + { + diff = _lruCacheDict.Count - _max_buffers; +#if DEBUG + if (diff > 0) + { + _logger.Info(CultureInfo.InvariantCulture, "Removing {0} entries from LRU cache for {1}", diff, Util.GetNameFromPath(_fileName)); + } +#endif + SortedList useSorterList = []; + // sort by usage counter + foreach (var entry in _lruCacheDict.Values) + { + if (!useSorterList.ContainsKey(entry.LastUseTimeStamp)) + { + useSorterList.Add(entry.LastUseTimeStamp, entry.LogBuffer.StartLine); + } + } + + // remove first entries (least usage) + _disposeLock.AcquireWriterLock(Timeout.Infinite); + for (var i = 0; i < diff; ++i) + { + if (i >= useSorterList.Count) + { + break; + } + + var startLine = useSorterList.Values[i]; + var entry = _lruCacheDict[startLine]; + _lruCacheDict.Remove(startLine); + entry.LogBuffer.DisposeContent(); + } + + _disposeLock.ReleaseWriterLock(); + } + + _lruCacheDictLock.ReleaseWriterLock(); +#if DEBUG + if (diff > 0) + { + long endTime = Environment.TickCount; + _logger.Info(CultureInfo.InvariantCulture, "Garbage collector time: " + (endTime - startTime) + " ms."); + } +#endif + } + + private void GarbageCollectorThreadProc () + { + while (!_shouldStop) + { + try + { + Thread.Sleep(10000); + } + catch (Exception) + { + } + + GarbageCollectLruCache(); + } + } + + // private void UpdateLru(LogBuffer logBuffer) + // { + // lock (this.monitor) + // { + // int index; + // if (this.lruDict.TryGetValue(logBuffer.StartLine, out index)) + // { + // RemoveBufferFromLru(logBuffer, index); + // AddBufferToLru(logBuffer); + // } + // else + // { + // if (this.bufferLru.Count > MAX_BUFFERS - 1) + // { + // LogBuffer looser = this.bufferLru[0]; + // if (looser != null) + // { + //#if DEBUG + // _logger.logDebug("Disposing buffer: " + looser.StartLine + "/" + looser.LineCount + "/" + looser.FileInfo.FileName); + //#endif + // looser.DisposeContent(); + // RemoveBufferFromLru(looser); + // } + // } + // AddBufferToLru(logBuffer); + // } + // } + // } + + ///// + ///// Removes a LogBuffer from the LRU. Note that the LogBuffer is searched in the lruDict + ///// via StartLine. So this property must have a consistent value. + ///// + ///// + //private void RemoveBufferFromLru(LogBuffer buffer) + //{ + // int index; + // lock (this.monitor) + // { + // if (this.lruDict.TryGetValue(buffer.StartLine, out index)) + // { + // RemoveBufferFromLru(buffer, index); + // } + // } + //} + + ///// + ///// Removes a LogBuffer from the LRU with known index. Note that the LogBuffer is searched in the lruDict + ///// via StartLine. So this property must have a consistent value. + ///// + ///// + ///// + //private void RemoveBufferFromLru(LogBuffer buffer, int index) + //{ + // lock (this.monitor) + // { + // this.bufferLru.RemoveAt(index); + // this.lruDict.Remove(buffer.StartLine); + // // adjust indizes, they have changed because of the remove + // for (int i = index; i < this.bufferLru.Count; ++i) + // { + // this.lruDict[this.bufferLru[i].StartLine] = this.lruDict[this.bufferLru[i].StartLine] - 1; + // } + // } + //} + + //private void AddBufferToLru(LogBuffer logBuffer) + //{ + // lock (this.monitor) + // { + // this.bufferLru.Add(logBuffer); + // int newIndex = this.bufferLru.Count - 1; + // this.lruDict[logBuffer.StartLine] = newIndex; + // } + //} + + private void ClearLru () + { + //lock (this.monitor) + //{ + // foreach (LogBuffer buffer in this.bufferLru) + // { + // buffer.DisposeContent(); + // } + // this.bufferLru.Clear(); + // this.lruDict.Clear(); + //} + _logger.Info(CultureInfo.InvariantCulture, "Clearing LRU cache."); + _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); + _disposeLock.AcquireWriterLock(Timeout.Infinite); + foreach (var entry in _lruCacheDict.Values) + { + entry.LogBuffer.DisposeContent(); + } + + _lruCacheDict.Clear(); + _disposeLock.ReleaseWriterLock(); + _lruCacheDictLock.ReleaseWriterLock(); + _logger.Info(CultureInfo.InvariantCulture, "Clearing done."); + } + + private void ReReadBuffer (LogBuffer logBuffer) + { +#if DEBUG + _logger.Info(CultureInfo.InvariantCulture, "re-reading buffer: {0}/{1}/{2}", logBuffer.StartLine, logBuffer.LineCount, logBuffer.FileInfo.FullName); +#endif + try + { + Monitor.Enter(logBuffer); + Stream fileStream = null; + try + { + fileStream = logBuffer.FileInfo.OpenStream(); + } + catch (IOException e) + { + _logger.Warn(e); + return; + } + + try + { + var reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); + + var filePos = logBuffer.StartPos; + reader.Position = logBuffer.StartPos; + var maxLinesCount = logBuffer.LineCount; + var lineCount = 0; + var dropCount = logBuffer.PrevBuffersDroppedLinesSum; + logBuffer.ClearLines(); + + while (ReadLine(reader, logBuffer.StartLine + logBuffer.LineCount, logBuffer.StartLine + logBuffer.LineCount + dropCount, out var line)) + { + if (lineCount >= maxLinesCount) + { + break; + } + + if (line == null) + { + dropCount++; + continue; + } + + LogLine logLine = new() + { + FullLine = line, + LineNumber = logBuffer.StartLine + logBuffer.LineCount + }; + + logBuffer.AddLine(logLine, filePos); + filePos = reader.Position; + lineCount++; + } + + if (maxLinesCount != logBuffer.LineCount) + { + _logger.Warn(CultureInfo.InvariantCulture, "LineCount in buffer differs after re-reading. old={0}, new={1}", maxLinesCount, logBuffer.LineCount); + } + + if (dropCount - logBuffer.PrevBuffersDroppedLinesSum != logBuffer.DroppedLinesCount) + { + _logger.Warn(CultureInfo.InvariantCulture, "DroppedLinesCount in buffer differs after re-reading. old={0}, new={1}", logBuffer.DroppedLinesCount, dropCount); + logBuffer.DroppedLinesCount = dropCount - logBuffer.PrevBuffersDroppedLinesSum; + } + + GC.KeepAlive(fileStream); + } + catch (IOException e) + { + _logger.Warn(e); + } + finally + { + fileStream.Close(); + } + } + finally + { + Monitor.Exit(logBuffer); + } + } + + private LogBuffer GetBufferForLine (int lineNum) + { +#if DEBUG + long startTime = Environment.TickCount; +#endif + LogBuffer logBuffer = null; + AcquireBufferListReaderLock(); + //if (lineNum == this.lastReturnedLineNumForBuffer) + //{ + // return this.lastReturnedBuffer; + //} + + //int startIndex = lineNum / LogBuffer.MAX_LINES; // doesn't work anymore since XML buffer may contain more lines than MAX_LINES + var startIndex = 0; + var count = _bufferList.Count; + for (var i = startIndex; i < count; ++i) + { + logBuffer = _bufferList[i]; + if (lineNum >= logBuffer.StartLine && lineNum < logBuffer.StartLine + logBuffer.LineCount) + { + //UpdateLru(logBuffer); + UpdateLruCache(logBuffer); + //this.lastReturnedLineNumForBuffer = lineNum; + //this.lastReturnedBuffer = logBuffer; + break; + } + } +#if DEBUG + long endTime = Environment.TickCount; + //_logger.logDebug("getBufferForLine(" + lineNum + ") duration: " + ((endTime - startTime)) + " ms. Buffer start line: " + logBuffer.StartLine); +#endif + ReleaseBufferListReaderLock(); + return logBuffer; + } + + /// + /// Async callback used to check if the GetLogLine() call is succeeding again after a detected timeout. + /// + private void GetLineFinishedCallback (ILogLine line) + { + _isFailModeCheckCallPending = false; + if (line != null) + { + _logger.Debug(CultureInfo.InvariantCulture, "'isFastFailOnGetLogLine' flag was reset"); + _isFastFailOnGetLogLine = false; + } + + _logger.Debug(CultureInfo.InvariantCulture, "'isLogLineCallPending' flag was reset."); + } + + private LogBuffer GetFirstBufferForFileByLogBuffer (LogBuffer logBuffer) + { + var info = logBuffer.FileInfo; + AcquireBufferListReaderLock(); + var index = _bufferList.IndexOf(logBuffer); + if (index == -1) + { + ReleaseBufferListReaderLock(); + return null; + } + + var resultBuffer = logBuffer; + while (true) + { + index--; + if (index < 0 || _bufferList[index].FileInfo != info) + { + break; + } + + resultBuffer = _bufferList[index]; + } + + ReleaseBufferListReaderLock(); + return resultBuffer; + } + + private void MonitorThreadProc () + { + Thread.CurrentThread.Name = "MonitorThread"; + //IFileSystemPlugin fs = PluginRegistry.GetInstance().FindFileSystemForUri(this.watchedILogFileInfo.FullName); + _logger.Info(CultureInfo.InvariantCulture, "MonitorThreadProc() for file {0}", _watchedILogFileInfo.FullName); + + long oldSize; + try + { + OnLoadingStarted(new LoadFileEventArgs(_fileName, 0, false, 0, false)); + ReadFiles(); + if (!_isDeleted) + { + oldSize = _fileLength; + OnLoadingFinished(); + } + } + catch (Exception e) + { + _logger.Error(e); + } + + while (!_shouldStop) + { + try + { + var pollInterval = _watchedILogFileInfo.PollInterval; + //#if DEBUG + // if (_logger.IsDebug) + // { + // _logger.logDebug("Poll interval for " + this.fileName + ": " + pollInterval); + // } + //#endif + Thread.Sleep(pollInterval); + } + catch (Exception e) + { + _logger.Error(e); + } + + if (_shouldStop) + { + return; + } + + try + { + if (_watchedILogFileInfo.FileHasChanged()) + { + _fileLength = _watchedILogFileInfo.Length; + if (_fileLength == -1) + { + MonitoredFileNotFound(); + } + else + { + oldSize = _fileLength; + FileChanged(); + } + } + } + catch (FileNotFoundException) + { + MonitoredFileNotFound(); + } + } + } + + private void MonitoredFileNotFound () + { + long oldSize; + if (!_isDeleted) + { + _logger.Debug(CultureInfo.InvariantCulture, "File not FileNotFoundException catched. Switching to 'deleted' mode."); + _isDeleted = true; + oldSize = _fileLength = -1; + FileSize = 0; + OnFileNotFound(); // notify LogWindow + } +#if DEBUG + else + { + _logger.Debug(CultureInfo.InvariantCulture, "File not FileNotFoundException catched. Already in deleted mode."); + } +#endif + } + + private void FileChanged () + { + if (_isDeleted) + { + OnRespawned(); + // prevent size update events. The window should reload the complete file. + FileSize = _fileLength; + } + + var newSize = _fileLength; + //if (this.currFileSize != newSize) + { + _logger.Info(CultureInfo.InvariantCulture, "file size changed. new size={0}, file: {1}", newSize, _fileName); + FireChangeEvent(); + } + } + + private void FireChangeEvent () + { + LogEventArgs args = new(); + args.PrevFileSize = FileSize; + args.PrevLineCount = LineCount; + var newSize = _fileLength; + if (newSize < FileSize || _isDeleted) + { + _logger.Info(CultureInfo.InvariantCulture, "File was created anew: new size={0}, oldSize={1}", newSize, FileSize); + // Fire "New File" event + FileSize = 0; + LineCount = 0; + try + { + if (IsMultiFile) + { + var offset = ShiftBuffers(); + //this.currFileSize = newSize; // removed because ShiftBuffers() calls ReadToBuffer() which will set the actual read size + args.FileSize = newSize; + args.LineCount = LineCount; + args.IsRollover = true; + args.RolloverOffset = offset; + _isDeleted = false; + if (!_shouldStop) + { + OnFileSizeChanged(args); + } + } + else + { + // ReloadBufferList(); // removed because reloading is triggered by owning LogWindow + // Trigger "new file" handling (reload) + OnLoadFile(new LoadFileEventArgs(_fileName, 0, true, _fileLength, true)); + + if (_isDeleted) + { + args.FileSize = newSize; + args.LineCount = LineCount; + if (args.PrevLineCount != args.LineCount && !_shouldStop) + { + OnFileSizeChanged(args); + } + } + + _isDeleted = false; + } + } + catch (FileNotFoundException e) + { + // trying anew in next poll intervall. So let currFileSize untouched. + _logger.Warn(e); + } + } + else + { + ReadToBufferList(_watchedILogFileInfo, FileSize, LineCount); + args.FileSize = newSize; + args.LineCount = LineCount; + //if (args.PrevLineCount != args.LineCount && !this.shouldStop) + OnFileSizeChanged(args); + } + } + + private ILogStreamReader GetLogStreamReader (Stream stream, EncodingOptions encodingOptions, bool useNewReader) + { + var reader = CreateLogStreamReader(stream, encodingOptions, useNewReader); + + return IsXmlMode ? new XmlBlockSplitter(new XmlLogReader(reader), XmlLogConfig) : reader; + } + + private ILogStreamReader CreateLogStreamReader (Stream stream, EncodingOptions encodingOptions, bool useSystemReader) + { + if (useSystemReader) + { + return new PositionAwareStreamReaderSystem(stream, encodingOptions); + } + + return new PositionAwareStreamReaderLegacy(stream, encodingOptions); + } + + private bool ReadLine (ILogStreamReader reader, int lineNum, int realLineNum, out string outLine) + { + string line = null; + try + { + line = reader.ReadLine(); + } + catch (IOException e) + { + _logger.Warn(e); + } + catch (NotSupportedException e) + { + // Bug#11: "Reading operations are not supported by the stream" + // Currently not reproducible. Probably happens at an unlucky time interval (after opening the file) + // when the file is being deleted (rolling) + // This will be handled as EOF. + _logger.Warn(e); + } + + if (line == null) // EOF or catched Exception + { + outLine = null; + return false; + } + + if (PreProcessColumnizer != null) + { + line = PreProcessColumnizer.PreProcessLine(line, lineNum, realLineNum); + } + + outLine = line; + return true; + } + + private void AcquireBufferListReaderLock () + { + try + { + _bufferListLock.AcquireReaderLock(10000); +#if DEBUG && TRACE_LOCKS + StackTrace st = new StackTrace(true); + StackFrame callerFrame = st.GetFrame(2); + this.bufferListLockInfo = +"Read lock from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); +#endif + } + catch (ApplicationException e) + { + _logger.Warn(e, "Reader lock wait for bufferList timed out. Now trying infinite."); +#if DEBUG && TRACE_LOCKS + _logger.logInfo(this.bufferListLockInfo); +#endif + _bufferListLock.AcquireReaderLock(Timeout.Infinite); + } + } + + private void ReleaseBufferListReaderLock () + { + _bufferListLock.ReleaseReaderLock(); + } + + private void AcquireBufferListWriterLock () + { + try + { + _bufferListLock.AcquireWriterLock(10000); +#if DEBUG && TRACE_LOCKS + StackTrace st = new StackTrace(true); + StackFrame callerFrame = st.GetFrame(1); + this.bufferListLockInfo = +"Write lock from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); + callerFrame.GetFileName(); +#endif + } + catch (ApplicationException e) + { + _logger.Warn(e, "Writer lock wait for bufferList timed out. Now trying infinite."); +#if DEBUG && TRACE_LOCKS + _logger.logInfo(this.bufferListLockInfo); +#endif + _bufferListLock.AcquireWriterLock(Timeout.Infinite); + } + } + + private void ReleaseBufferListWriterLock () + { + _bufferListLock.ReleaseWriterLock(); + } + + private LockCookie UpgradeBufferListLockToWriter () + { + try + { + var cookie = _bufferListLock.UpgradeToWriterLock(10000); +#if DEBUG && TRACE_LOCKS + StackTrace st = new StackTrace(true); + StackFrame callerFrame = st.GetFrame(2); + this.bufferListLockInfo += +", upgraded to writer from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); +#endif + return cookie; + } + catch (ApplicationException e) + { + _logger.Warn(e, "Writer lock update wait for bufferList timed out. Now trying infinite."); +#if DEBUG && TRACE_LOCKS + _logger.logInfo(this.bufferListLockInfo); +#endif + return _bufferListLock.UpgradeToWriterLock(Timeout.Infinite); + } + } + + private void DowngradeBufferListLockFromWriter (ref LockCookie cookie) + { + _bufferListLock.DowngradeFromWriterLock(ref cookie); +#if DEBUG && TRACE_LOCKS + StackTrace st = new StackTrace(true); + StackFrame callerFrame = st.GetFrame(2); + this.bufferListLockInfo += +", downgraded to reader from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); +#endif + } + +#if DEBUG + private void DumpBufferInfos (LogBuffer buffer) + { + if (_logger.IsTraceEnabled) + { + _logger.Trace(CultureInfo.InvariantCulture, "StartLine: {0}\r\nLineCount: {1}\r\nStartPos: {2}\r\nSize: {3}\r\nDisposed: {4}\r\nDisposeCount: {5}\r\nFile: {6}", + buffer.StartLine, + buffer.LineCount, + buffer.StartPos, + buffer.Size, + buffer.IsDisposed ? "yes" : "no", + buffer.DisposeCount, + buffer.FileInfo.FullName); + } + } + +#endif + + #endregion + + public void Dispose () + { + Dispose(true); + GC.SuppressFinalize(this); // Suppress finalization (not needed but best practice) + } + + protected virtual void Dispose (bool disposing) + { + if (!_disposed) + { + if (disposing) + { + DeleteAllContent(); + _cts.Dispose(); // Dispose managed resources + } + + _disposed = true; + } + } + + //TODO: Seems that this can be deleted. Need to verify. + ~LogfileReader () + { + Dispose(false); + } + + protected virtual void OnFileSizeChanged (LogEventArgs e) + { + FileSizeChanged?.Invoke(this, e); + } + + protected virtual void OnLoadFile (LoadFileEventArgs e) + { + LoadFile?.Invoke(this, e); + } + + protected virtual void OnLoadingStarted (LoadFileEventArgs e) + { + LoadingStarted?.Invoke(this, e); + } + + protected virtual void OnLoadingFinished () + { + LoadingFinished?.Invoke(this, EventArgs.Empty); + } + + protected virtual void OnFileNotFound () + { + FileNotFound?.Invoke(this, EventArgs.Empty); + } + + protected virtual void OnRespawned () + { + _logger.Info(CultureInfo.InvariantCulture, "OnRespawned()"); + Respawned?.Invoke(this, EventArgs.Empty); + } + + private class LogLine : ILogLine + { + #region Properties + + public string FullLine { get; set; } + + public int LineNumber { get; set; } + + string ITextValue.Text => FullLine; + + #endregion + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs new file mode 100644 index 00000000..5f072c27 --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderBase.cs @@ -0,0 +1,224 @@ +using System.Text; + +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Classes.Log; + +public abstract class PositionAwareStreamReaderBase : LogStreamReaderBase +{ + #region Fields + + private const int MAX_LINE_LEN = 20000; + + private static readonly Encoding[] _preambleEncodings = [Encoding.UTF8, Encoding.Unicode, Encoding.BigEndianUnicode, Encoding.UTF32]; + + private readonly BufferedStream _stream; + private readonly StreamReader _reader; + + private readonly int _preambleLength; + private readonly int _posIncPrecomputed; + + private long _position; + + #endregion + + #region cTor + + protected PositionAwareStreamReaderBase (Stream stream, EncodingOptions encodingOptions) + { + _stream = new BufferedStream(stream); + + _preambleLength = DetectPreambleLengthAndEncoding(out Encoding detectedEncoding); + + Encoding usedEncoding = GetUsedEncoding(encodingOptions, detectedEncoding); + _posIncPrecomputed = GetPosIncPrecomputed(usedEncoding); + + _reader = new StreamReader(_stream, usedEncoding, true); + + Position = 0; + } + + #endregion + + #region Properties + + /// + /// Current position in the stream. + /// + public sealed override long Position + { + get => _position; + set + { + /* + * 1: Sometime commented (+Encoding.GetPreamble().Length) + * 2: Date 1.1 3207 + * 3: Error Message from Piet because of Unicode-Bugs. + * No Idea, if this is OK. + * 4: 27.07.09: Preamble-Length is now calculated in CT, because Encoding.GetPreamble().Length + * always delivers a fixed length (does not mater what kind of data) + */ + _position = value; // +Encoding.GetPreamble().Length; // 1 + //stream.Seek(pos, SeekOrigin.Begin); // 2 + //stream.Seek(pos + Encoding.GetPreamble().Length, SeekOrigin.Begin); // 3 + _stream.Seek(_position + _preambleLength, SeekOrigin.Begin); // 4 + + ResetReader(); + } + } + + public sealed override Encoding Encoding => _reader.CurrentEncoding; + + public sealed override bool IsBufferComplete => true; + + //Refactor this needs to be given and should not be added like this + protected static int MaxLineLen => 500;//ConfigManager.Settings.Preferences.MaxLineLength; + + #endregion + + #region Public methods + + /// + /// Destroy and release the current stream reader. + /// + /// Specifies whether or not the managed objects should be released. + protected override void Dispose (bool disposing) + { + if (disposing) + { + _stream.Dispose(); + _reader.Dispose(); + IsDisposed = true; +} + } + + //TODO This is unsafe and should be refactored + public override unsafe int ReadChar () + { + ObjectDisposedException.ThrowIf(IsDisposed, GetType()); + + try + { + var readInt = _reader.Read(); + if (readInt != -1) + { + var readChar = (char)readInt; + if (_posIncPrecomputed != 0) + { + _position += _posIncPrecomputed; + } + else + { + _position += _reader.CurrentEncoding.GetByteCount(&readChar, 1); + } + } + return readInt; + } + catch (IOException) + { + return -1; + } + } + + protected virtual void ResetReader () + { + _reader.DiscardBufferedData(); + } + + protected StreamReader GetStreamReader () + { + ObjectDisposedException.ThrowIf(IsDisposed, GetType()); + return _reader; + } + + protected void MovePosition (int offset) + { + _position += offset; + } + + #endregion + + #region Private Methods + + /// + /// Determines the actual number of preamble bytes in the file. + /// + /// Number of preamble bytes in the file + private int DetectPreambleLengthAndEncoding (out Encoding detectedEncoding) + { + /* + UTF-8: EF BB BF + UTF-16-Big-Endian-Byteorder: FE FF + UTF-16-Little-Endian-Byteorder: FF FE + UTF-32-Big-Endian-Byteorder: 00 00 FE FF + UTF-32-Little-Endian-Byteorder: FF FE 00 00 + */ + + var readPreamble = new byte[4]; + + var readLen = _stream.Read(readPreamble, 0, 4); + + if (readLen >= 2) + { + foreach (Encoding encoding in _preambleEncodings) + { + var preamble = encoding.GetPreamble(); + var fail = false; + for (var i = 0; i < readLen && i < preamble.Length; ++i) + { + if (readPreamble[i] != preamble[i]) + { + fail = true; + break; + } + } + + if (!fail) + { + detectedEncoding = encoding; + return preamble.Length; + } + } + } + + // not found or less than 2 byte read + detectedEncoding = null; + + return 0; + } + + private Encoding GetUsedEncoding (EncodingOptions encodingOptions, Encoding detectedEncoding) + { + if (encodingOptions.Encoding != null) + { + return encodingOptions.Encoding; + } + + if (detectedEncoding != null) + { + return detectedEncoding; + } + + return encodingOptions.DefaultEncoding ?? Encoding.Default; + } + private int GetPosIncPrecomputed (Encoding usedEncoding) + { + switch (usedEncoding) + { + case UTF8Encoding: + { + return 0; + } + case UnicodeEncoding: + { + return 2; + } + default: + { + return 1; + } + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderLegacy.cs b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderLegacy.cs new file mode 100644 index 00000000..a47eaa0d --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderLegacy.cs @@ -0,0 +1,111 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Classes.Log; + +public class PositionAwareStreamReaderLegacy : PositionAwareStreamReaderBase +{ + #region Fields + + private readonly char[] _charBuffer = new char[MaxLineLen]; + + private int _charBufferPos; + private bool _crDetect; + + public override bool IsDisposed { get; protected set; } + + #endregion + + #region cTor + + public PositionAwareStreamReaderLegacy(Stream stream, EncodingOptions encodingOptions) : base(stream, encodingOptions) + { + + } + + #endregion + + #region Public methods + + public override string ReadLine() + { + int readInt; + + while (-1 != (readInt = ReadChar())) + { + var readChar = (char)readInt; + + switch (readChar) + { + case '\n': + { + _crDetect = false; + return GetLineAndResetCharBufferPos(); + } + case '\r': + { + if (_crDetect) + { + return GetLineAndResetCharBufferPos(); + } + + _crDetect = true; + break; + } + default: + { + if (_crDetect) + { + _crDetect = false; + var line = GetLineAndResetCharBufferPos(); + AppendToCharBuffer(readChar); + return line; + } + + AppendToCharBuffer(readChar); + break; + } + } + } + + var result = GetLineAndResetCharBufferPos(); + if (readInt == -1 && result.Length == 0 && !_crDetect) + { + return null; // EOF + } + _crDetect = false; + return result; + } + + protected override void ResetReader() + { + ResetCharBufferPos(); + + base.ResetReader(); + } + + #endregion + + #region Private Methods + + private string GetLineAndResetCharBufferPos() + { + string result = new(_charBuffer, 0, _charBufferPos); + ResetCharBufferPos(); + return result; + } + + private void AppendToCharBuffer(char readChar) + { + if (_charBufferPos < MaxLineLen) + { + _charBuffer[_charBufferPos++] = readChar; + } + } + + private void ResetCharBufferPos() + { + _charBufferPos = 0; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderSystem.cs b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderSystem.cs new file mode 100644 index 00000000..a4f8b4a0 --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/PositionAwareStreamReaderSystem.cs @@ -0,0 +1,96 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Classes.Log; + +/// +/// This class is responsible for reading line from the log file. It also decodes characters with the appropriate charset encoding. +/// PositionAwareStreamReaderSystem tries a BOM detection to determine correct file offsets when directly seeking into the file (on re-loading flushed buffers). +/// UTF-8 handling is a bit slower, because after reading a character the byte length of the character must be determined. +/// Lines are read char-by-char. StreamReader.ReadLine() is not used because StreamReader cannot tell a file position. +/// +public class PositionAwareStreamReaderSystem : PositionAwareStreamReaderBase +{ + #region Fields + + private const int CHAR_CR = 0x0D; + private const int CHAR_LF = 0x0A; + + private int _newLineSequenceLength; + + public override bool IsDisposed { get; protected set; } + + #endregion + + #region cTor + + public PositionAwareStreamReaderSystem(Stream stream, EncodingOptions encodingOptions) : base(stream, encodingOptions) + { + + } + + #endregion + + #region Public methods + + public override string ReadLine() + { + StreamReader reader = GetStreamReader(); + + if (_newLineSequenceLength == 0) + { + _newLineSequenceLength = GuessNewLineSequenceLength(reader); + } + + var line = reader.ReadLine(); + + if (line != null) + { + MovePosition(Encoding.GetByteCount(line) + _newLineSequenceLength); + + if (line.Length > MaxLineLen) + { + line = line.Remove(MaxLineLen); + } + } + + return line; + } + + #endregion + + #region Private Methods + + private int GuessNewLineSequenceLength(StreamReader reader) + { + var currentPos = Position; + + try + { + var line = reader.ReadLine(); + + if (line != null) + { + Position += Encoding.GetByteCount(line); + + var firstChar = reader.Read(); + if (firstChar == CHAR_CR) // check \r + { + var secondChar = reader.Read(); + if (secondChar == CHAR_LF) // check \n + { + return Encoding.GetByteCount("\r\n"); + } + } + return Encoding.GetByteCount(((char)firstChar).ToString()); + } + + return 0; + } + finally + { + Position = currentPos; + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs new file mode 100644 index 00000000..3d43806f --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/RolloverFilenameBuilder.cs @@ -0,0 +1,246 @@ +using System.Globalization; +using System.Text; +using System.Text.RegularExpressions; + +namespace LogExpert.Core.Classes.Log; + +/* Needed info: + * - Date/time mask + * - index counters + * - counter direction (up/down) + * - counter limit + * - whether the files are shifted or not + * - whether the indexes start with zero (or n/a) on a new date period + * + * Format: + * *$D(yyyy-MM-dd)$I + * *$J(.) + * + * *(yyyy-MM-dd)[I] + * + */ + +/// +/// This class is responsible for building file names for multifile. +/// +public class RolloverFilenameBuilder +{ + #region Fields + + private string _condContent; + private Group _condGroup; + private string _currentFileName; + + private Group _dateGroup; + + //private Regex regexCond; + private DateTime _dateTime; + + //private DateTimeFormatInfo dateFormat; + private string _dateTimeFormat; + + private bool _hideZeroIndex; + private Group _indexGroup; + private Regex _regex; + + #endregion + + #region cTor + + public RolloverFilenameBuilder (string formatString) + { + ParseFormatString(formatString); + } + + #endregion + + #region Properties + + public int Index { get; set; } + + public bool IsDatePattern => _dateGroup != null && _dateGroup.Success; + + public bool IsIndexPattern => _indexGroup != null && _indexGroup.Success; + + #endregion + + #region Public methods + + public void SetFileName (string fileName) + { + _currentFileName = fileName; + Match match = _regex.Match(fileName); + if (match.Success) + { + _dateGroup = match.Groups["date"]; + if (_dateGroup.Success) + { + var date = fileName.Substring(_dateGroup.Index, _dateGroup.Length); + if (DateTime.TryParseExact(date, _dateTimeFormat, DateTimeFormatInfo.InvariantInfo, + DateTimeStyles.None, + out _dateTime)) + { + } + } + + _indexGroup = match.Groups["index"]; + if (_indexGroup.Success) + { + Index = _indexGroup.Value.Length > 0 ? int.Parse(_indexGroup.Value) : 0; + } + + _condGroup = match.Groups["cond"]; + } + } + + public void IncrementDate () + { + _dateTime = _dateTime.AddDays(1); + } + + public void DecrementDate () + { + _dateTime = _dateTime.AddDays(-1); + } + + + public string BuildFileName () + { + var fileName = _currentFileName; + if (_dateGroup != null && _dateGroup.Success) + { + var newDate = _dateTime.ToString(_dateTimeFormat, DateTimeFormatInfo.InvariantInfo); + fileName = fileName.Remove(_dateGroup.Index, _dateGroup.Length); + fileName = fileName.Insert(_dateGroup.Index, newDate); + } + + if (_indexGroup != null && _indexGroup.Success) + { + fileName = fileName.Remove(_indexGroup.Index, _indexGroup.Length); + + if (!_hideZeroIndex || Index > 0) + { + var format = "D" + _indexGroup.Length; + fileName = fileName.Insert(_indexGroup.Index, Index.ToString(format)); + if (_hideZeroIndex && _condContent != null) + { + fileName = fileName.Insert(_indexGroup.Index, _condContent); + } + } + } + + // this.currentFileName = fileName; + // SetFileName(fileName); + return fileName; + } + + #endregion + + #region Private Methods + + private void ParseFormatString (string formatString) + { + var fmt = EscapeNonvarRegions(formatString); + var datePos = formatString.IndexOf("$D(", StringComparison.Ordinal); + + if (datePos != -1) + { + var endPos = formatString.IndexOf(')', datePos); + if (endPos != -1) + { + _dateTimeFormat = formatString.Substring(datePos + 3, endPos - datePos - 3) + .ToUpperInvariant() + .Replace('D', 'd') + .Replace('Y', 'y'); + + var dtf = _dateTimeFormat.ToUpper(CultureInfo.InvariantCulture) + .Replace("D", "\\d", StringComparison.Ordinal) + .Replace("Y", "\\d", StringComparison.Ordinal) + .Replace("M", "\\d", StringComparison.Ordinal); + + fmt = fmt.Remove(datePos, 2) // remove $D + .Remove(datePos + 1, _dateTimeFormat.Length) // replace with regex version of format + .Insert(datePos + 1, dtf) + .Insert(datePos + 1, "?'date'"); // name the regex group + } + } + + var condPos = fmt.IndexOf("$J(", StringComparison.Ordinal); + if (condPos != -1) + { + var endPos = fmt.IndexOf(')', condPos); + if (endPos != -1) + { + _condContent = fmt.Substring(condPos + 3, endPos - condPos - 3); + fmt = fmt.Remove(condPos + 2, endPos - condPos - 1); + } + } + + fmt = fmt.Replace("*", ".*", StringComparison.Ordinal); + _hideZeroIndex = fmt.Contains("$J", StringComparison.Ordinal); + fmt = fmt.Replace("$I", "(?'index'[\\d]+)", StringComparison.Ordinal); + fmt = fmt.Replace("$J", "(?'index'[\\d]*)", StringComparison.Ordinal); + + _regex = new Regex(fmt); + } + + private string EscapeNonvarRegions (string formatString) + { + var fmt = formatString.Replace('*', '\xFFFD'); + var state = 0; + + StringBuilder result = new(); + StringBuilder segment = new(); + + for (var i = 0; i < fmt.Length; ++i) + { + switch (state) + { + case 0: // looking for $ + if (fmt[i] == '$') + { + _ = result.Append(Regex.Escape(segment.ToString())); + segment = new StringBuilder(); + state = 1; + } + + _ = segment.Append(fmt[i]); + break; + case 1: // the char behind $ + _ = segment.Append(fmt[i]); + _ = result.Append(segment); + segment = new StringBuilder(); + state = 2; + break; + case 2: // checking if ( or other char + if (fmt[i] == '(') + { + _ = segment.Append(fmt[i]); + state = 3; + } + else + { + _ = segment.Append(fmt[i]); + state = 0; + } + + break; + case 3: // looking for ) + _ = segment.Append(fmt[i]); + if (fmt[i] == ')') + { + _ = result.Append(segment); + segment = new StringBuilder(); + state = 0; + } + + break; + } + } + + fmt = result.ToString().Replace('\xFFFD', '*'); + return fmt; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Log/RolloverFilenameHandler.cs b/src/LogExpert.Core/Classes/Log/RolloverFilenameHandler.cs new file mode 100644 index 00000000..673eebfe --- /dev/null +++ b/src/LogExpert.Core/Classes/Log/RolloverFilenameHandler.cs @@ -0,0 +1,109 @@ +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; +using System.Collections.Generic; + +namespace LogExpert.Core.Classes.Log; + +/// +/// Handles rollover naming. The names built by the RolloverFilenameBuilder will be used +/// to check if the file exist. Names will be built by incrmenting an index and decrementing a date. +/// A configurable number of days in the past will be checked (date gaps may occur on days without log file activity). +/// Date checking is only performed if the format pattern contains a date format. Index checking +/// is only performed of the format pattern contains an index placeholder. +/// +public class RolloverFilenameHandler +{ + #region Fields + + private readonly RolloverFilenameBuilder _filenameBuilder; + private readonly ILogFileInfo _logFileInfo; + private readonly MultiFileOptions _options; + + #endregion + + #region cTor + + /// + /// Constructor. + /// + /// The complete path of the logfile + /// Multifile option (e.g. format pattern) + public RolloverFilenameHandler(ILogFileInfo logFileInfo, MultiFileOptions options) + { + _options = options; + _logFileInfo = logFileInfo; + _filenameBuilder = new RolloverFilenameBuilder(_options.FormatPattern); + _filenameBuilder.SetFileName(logFileInfo.FileName); + } + + #endregion + + #region Public methods + + /// + /// Returns a list of the built file names (complete path) which also exists on disk. + /// The list is created by using the RolloverFilenameBuilder and checking for file existence. + /// The first entry in the list contains the oldest file. The last entry contains the file given + /// in the contructor. + /// + /// + public LinkedList GetNameList(IPluginRegistry pluginRegistry) + { + LinkedList fileList = new(); + var fileName = _filenameBuilder.BuildFileName(); + var filePath = _logFileInfo.DirectoryName + _logFileInfo.DirectorySeparatorChar + fileName; + fileList.AddFirst(filePath); + var found = true; + while (found) + { + found = false; + // increment index and check if file exists + if (_filenameBuilder.IsIndexPattern) + { + _filenameBuilder.Index += 1; + fileName = _filenameBuilder.BuildFileName(); + filePath = _logFileInfo.DirectoryName + _logFileInfo.DirectorySeparatorChar + fileName;//TODO: Change to Directory.Combine + if (FileExists(filePath, pluginRegistry)) + { + fileList.AddFirst(filePath); + found = true; + continue; + } + } + // if file with index isn't found or no index is in format pattern, decrement the current date + if (_filenameBuilder.IsDatePattern) + { + var tryCounter = 0; + _filenameBuilder.Index = 0; + while (tryCounter < _options.MaxDayTry) + { + _filenameBuilder.DecrementDate(); + fileName = _filenameBuilder.BuildFileName(); + filePath = _logFileInfo.DirectoryName + _logFileInfo.DirectorySeparatorChar + fileName;//TODO: Change to Directory.Combine + if (FileExists(filePath, pluginRegistry)) + { + fileList.AddFirst(filePath); + found = true; + break; + } + + tryCounter++; + } + } + } + return fileList; + } + + #endregion + + #region Private Methods + + private bool FileExists(string filePath, IPluginRegistry pluginRegistry) + { + IFileSystemPlugin fs = pluginRegistry.FindFileSystemForUri(filePath); + ILogFileInfo info = fs.GetLogfileInfo(filePath); + return info.FileExists; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/ObjectClone.cs b/src/LogExpert.Core/Classes/ObjectClone.cs new file mode 100644 index 00000000..9c6a352b --- /dev/null +++ b/src/LogExpert.Core/Classes/ObjectClone.cs @@ -0,0 +1,20 @@ +using System.IO; +using System.Text.Json; + +namespace LogExpert.Core.Classes; + +public static class ObjectClone +{ + #region Public methods + + public static T Clone(T RealObject) + { + using MemoryStream objectStream = new(); + + JsonSerializer.Serialize(objectStream, RealObject); + objectStream.Seek(0, SeekOrigin.Begin); + return JsonSerializer.Deserialize(objectStream); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/ParamParser.cs b/src/LogExpert.Core/Classes/ParamParser.cs new file mode 100644 index 00000000..6ca9731f --- /dev/null +++ b/src/LogExpert.Core/Classes/ParamParser.cs @@ -0,0 +1,103 @@ +using System.Text; +using System.Text.RegularExpressions; + +namespace LogExpert.Core.Classes; + +public class ParamParser (string argTemplate) +{ + #region Public methods + + public string ReplaceParams (ILogLine logLine, int lineNum, string fileName) + { + FileInfo fileInfo = new(fileName); + StringBuilder builder = new(argTemplate); + _ = builder.Replace("%L", "" + lineNum); + _ = builder.Replace("%P", fileInfo.DirectoryName.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.DirectoryName + "\"" + : fileInfo.DirectoryName); + _ = builder.Replace("%N", fileInfo.Name.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.Name + "\"" + : fileInfo.Name); + _ = builder.Replace("%F", + fileInfo.FullName.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.FullName + "\"" + : fileInfo.FullName); + _ = builder.Replace("%E", fileInfo.Extension.Contains(' ', StringComparison.Ordinal) + ? "\"" + fileInfo.Extension + "\"" + : fileInfo.Extension); + var stripped = StripExtension(fileInfo.Name); + _ = builder.Replace("%M", stripped.Contains(' ', StringComparison.Ordinal) + ? "\"" + stripped + "\"" + : stripped); + var sPos = 0; + string reg; + string replace; + do + { + reg = GetNextGroup(builder, ref sPos); + replace = GetNextGroup(builder, ref sPos); + if (reg != null && replace != null) + { + var result = Regex.Replace(logLine.FullLine, reg, replace); + builder.Insert(sPos, result); + } + } while (replace != null); + return builder.ToString(); + } + + public static string StripExtension (string fileName) + { + var i = fileName.LastIndexOf('.'); + + if (i < 0) + { + i = fileName.Length - 1; + } + + return fileName[..i]; + } + + #endregion + + #region Private Methods + + private string GetNextGroup (StringBuilder builder, ref int sPos) + { + int ePos; + while (sPos < builder.Length) + { + if (builder[sPos] == '{') + { + ePos = sPos + 1; + var count = 1; + while (ePos < builder.Length) + { + if (builder[ePos] == '{') + { + count++; + } + + if (builder[ePos] == '}') + { + count--; + } + + if (count == 0) + { + var reg = builder.ToString(sPos + 1, ePos - sPos - 1); + _ = builder.Remove(sPos, ePos - sPos + 1); + return reg; + } + + ePos++; + } + } + + sPos++; + } + + return null; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/PatternBlock.cs b/src/LogExpert.Core/Classes/PatternBlock.cs new file mode 100644 index 00000000..41d23bc1 --- /dev/null +++ b/src/LogExpert.Core/Classes/PatternBlock.cs @@ -0,0 +1,32 @@ +namespace LogExpert.Core.Classes; + +public class PatternBlock +{ + public int BlockId { get; set; } + + public int EndLine { get; set; } + + // key: line num + public Dictionary QualityInfoList { get; set; } = []; + + public SortedDictionary SrcLines { get; set; } = []; + + public int StartLine { get; set; } + + public int TargetEnd { get; set; } + + public SortedDictionary TargetLines { get; set; } = []; + + public int TargetStart { get; set; } + + public int Weigth { get; set; } + + #region Public methods + + public override string ToString () + { + return $"srcStart={StartLine}, srcEnd={EndLine}, targetStart={TargetStart}, targetEnd={TargetEnd}, weight={Weigth}"; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Persister/FilterTabData.cs b/src/LogExpert.Core/Classes/Persister/FilterTabData.cs new file mode 100644 index 00000000..f1fc8fc6 --- /dev/null +++ b/src/LogExpert.Core/Classes/Persister/FilterTabData.cs @@ -0,0 +1,10 @@ +using LogExpert.Core.Classes.Filter; + +namespace LogExpert.Core.Classes.Persister; + +public class FilterTabData +{ + public FilterParams FilterParams { get; set; } = new(); + + public PersistenceData PersistenceData { get; set; } = new(); +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Persister/PersistenceData.cs b/src/LogExpert.Core/Classes/Persister/PersistenceData.cs new file mode 100644 index 00000000..eefe1a34 --- /dev/null +++ b/src/LogExpert.Core/Classes/Persister/PersistenceData.cs @@ -0,0 +1,61 @@ +using System.Text; + +using LogExpert.Core.Classes.Filter; +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Classes.Persister; + +public class PersistenceData +{ + public SortedList BookmarkList { get; set; } = []; + + public int BookmarkListPosition { get; set; } = 300; + + public bool BookmarkListVisible { get; set; } + + public string ColumnizerName { get; set; } + + public int CurrentLine { get; set; } = -1; + + public Encoding Encoding { get; set; } + + public string FileName { get; set; } + + public bool FilterAdvanced { get; set; } + + public List FilterParamsList { get; set; } = []; + + public int FilterPosition { get; set; } = 222; + + public bool FilterSaveListVisible { get; set; } + + public List FilterTabDataList { get; set; } = []; + + public int FirstDisplayedLine { get; set; } = -1; + + public bool FollowTail { get; set; } = true; + + public string HighlightGroupName { get; set; } + + public bool FilterVisible { get; set; } + + public int LineCount { get; set; } + + public bool MultiFile { get; set; } + + public int MultiFileMaxDays { get; set; } + + public List MultiFileNames { get; set; } = []; + + public string MultiFilePattern { get; set; } + + public SortedList RowHeightList { get; set; } = []; + + public string SessionFileName { get; set; } + + public bool ShowBookmarkCommentColumn { get; set; } + + public string TabName { get; set; } + + public string SettingsSaveLoadLocation { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Persister/Persister.cs b/src/LogExpert.Core/Classes/Persister/Persister.cs new file mode 100644 index 00000000..8ae747b9 --- /dev/null +++ b/src/LogExpert.Core/Classes/Persister/Persister.cs @@ -0,0 +1,661 @@ +using System.Drawing; +using System.Text; +using System.Text.Json; +using System.Xml; + +using LogExpert.Core.Classes.Filter; +using LogExpert.Core.Config; +using LogExpert.Core.Entities; + +using NLog; + +namespace LogExpert.Core.Classes.Persister; + +//TODO Rewrite as json Persister, xml is outdated and difficult to parse and write +public static class Persister +{ + #region Fields + + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + #endregion + + #region Public methods + + public static string SavePersistenceData (string logFileName, PersistenceData persistenceData, Preferences preferences) + { + var fileName = persistenceData.SessionFileName ?? BuildPersisterFileName(logFileName, preferences); + + if (preferences.SaveLocation == SessionSaveLocation.SameDir) + { + // make to log file in .lxp file relative + var filePart = Path.GetFileName(persistenceData.FileName); + persistenceData.FileName = filePart; + } + + Save(fileName, persistenceData); + return fileName; + } + + public static string SavePersistenceDataWithFixedName (string persistenceFileName, + PersistenceData persistenceData) + { + Save(persistenceFileName, persistenceData); + return persistenceFileName; + } + + + public static PersistenceData LoadPersistenceData (string logFileName, Preferences preferences) + { + var fileName = BuildPersisterFileName(logFileName, preferences); + return Load(fileName); + } + + public static PersistenceData LoadPersistenceDataOptionsOnly (string logFileName, Preferences preferences) + { + var fileName = BuildPersisterFileName(logFileName, preferences); + return LoadOptionsOnly(fileName); + } + + public static PersistenceData LoadPersistenceDataOptionsOnlyFromFixedFile (string persistenceFile) + { + return LoadOptionsOnly(persistenceFile); + } + + public static PersistenceData LoadPersistenceDataFromFixedFile (string persistenceFile) + { + return Load(persistenceFile); + } + + + /// + /// Loads the persistence options out of the given persistence file name. + /// + /// + /// + public static PersistenceData LoadOptionsOnly (string fileName) + { + PersistenceData persistenceData = new(); + XmlDocument xmlDoc = new(); + try + { + xmlDoc.Load(fileName); + } + catch (IOException) + { + return null; + } + + XmlNode fileNode = xmlDoc.SelectSingleNode("logexpert/file"); + if (fileNode != null) + { + var fileElement = fileNode as XmlElement; + ReadOptions(fileElement, persistenceData); + persistenceData.FileName = fileElement.GetAttribute("fileName"); + persistenceData.Encoding = ReadEncoding(fileElement); + } + return persistenceData; + } + + #endregion + + #region Private Methods + + private static string BuildPersisterFileName (string logFileName, Preferences preferences) + { + string dir; + string file; + + switch (preferences.SaveLocation) + { + case SessionSaveLocation.SameDir: + default: + { + FileInfo fileInfo = new(logFileName); + dir = fileInfo.DirectoryName; + file = fileInfo.DirectoryName + Path.DirectorySeparatorChar + fileInfo.Name + ".lxp"; + break; + } + case SessionSaveLocation.DocumentsDir: + { + dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + + Path.DirectorySeparatorChar + + "LogExpert"; + file = dir + Path.DirectorySeparatorChar + BuildSessionFileNameFromPath(logFileName); + break; + } + case SessionSaveLocation.OwnDir: + { + dir = preferences.SessionSaveDirectory; + file = dir + Path.DirectorySeparatorChar + BuildSessionFileNameFromPath(logFileName); + break; + } + case SessionSaveLocation.ApplicationStartupDir: + { + //TODO Add Application.StartupPath as Variable + dir = string.Empty;// Application.StartupPath + Path.DirectorySeparatorChar + "sessionfiles"; + file = dir + Path.DirectorySeparatorChar + BuildSessionFileNameFromPath(logFileName); + break; + } + } + + if (string.IsNullOrWhiteSpace(dir) == false && Directory.Exists(dir) == false) + { + try + { + Directory.CreateDirectory(dir); + } + catch (Exception e) + { + //TODO this needs to be handled differently + //MessageBox.Show(e.Message, "LogExpert"); + } + } + + return file; + } + + private static string BuildSessionFileNameFromPath (string logFileName) + { + var result = logFileName; + result = result.Replace(Path.DirectorySeparatorChar, '_'); + result = result.Replace(Path.AltDirectorySeparatorChar, '_'); + result = result.Replace(Path.VolumeSeparatorChar, '_'); + result += ".lxp"; + return result; + } + + private static void Save (string fileName, PersistenceData persistenceData) + { + XmlDocument xmlDoc = new(); + XmlElement rootElement = xmlDoc.CreateElement("logexpert"); + xmlDoc.AppendChild(rootElement); + XmlElement fileElement = xmlDoc.CreateElement("file"); + rootElement.AppendChild(fileElement); + fileElement.SetAttribute("fileName", persistenceData.FileName); + fileElement.SetAttribute("lineCount", "" + persistenceData.LineCount); + WriteBookmarks(xmlDoc, fileElement, persistenceData.BookmarkList); + WriteRowHeightList(xmlDoc, fileElement, persistenceData.RowHeightList); + WriteOptions(xmlDoc, fileElement, persistenceData); + WriteFilter(xmlDoc, fileElement, persistenceData.FilterParamsList); + WriteFilterTabs(xmlDoc, fileElement, persistenceData.FilterTabDataList); + WriteEncoding(xmlDoc, fileElement, persistenceData.Encoding); + if (xmlDoc.HasChildNodes) + { + xmlDoc.Save(fileName); + } + } + + private static void WriteEncoding (XmlDocument xmlDoc, XmlElement rootElement, Encoding encoding) + { + if (encoding != null) + { + XmlElement encodingElement = xmlDoc.CreateElement("encoding"); + rootElement.AppendChild(encodingElement); + encodingElement.SetAttribute("name", encoding.WebName); + } + } + + private static void WriteFilterTabs (XmlDocument xmlDoc, XmlElement rootElement, List dataList) + { + if (dataList.Count > 0) + { + XmlElement filterTabsElement = xmlDoc.CreateElement("filterTabs"); + rootElement.AppendChild(filterTabsElement); + foreach (FilterTabData data in dataList) + { + PersistenceData persistenceData = data.PersistenceData; + XmlElement filterTabElement = xmlDoc.CreateElement("filterTab"); + filterTabsElement.AppendChild(filterTabElement); + WriteBookmarks(xmlDoc, filterTabElement, persistenceData.BookmarkList); + WriteRowHeightList(xmlDoc, filterTabElement, persistenceData.RowHeightList); + WriteOptions(xmlDoc, filterTabElement, persistenceData); + WriteFilter(xmlDoc, filterTabElement, persistenceData.FilterParamsList); + WriteFilterTabs(xmlDoc, filterTabElement, persistenceData.FilterTabDataList); + XmlElement filterElement = xmlDoc.CreateElement("tabFilter"); + filterTabElement.AppendChild(filterElement); + List filterList = [data.FilterParams]; + WriteFilter(xmlDoc, filterElement, filterList); + } + } + } + + private static List ReadFilterTabs (XmlElement startNode) + { + List dataList = []; + XmlNode filterTabsNode = startNode.SelectSingleNode("filterTabs"); + if (filterTabsNode != null) + { + XmlNodeList filterTabNodeList = filterTabsNode.ChildNodes; // all "filterTab" nodes + + foreach (XmlNode node in filterTabNodeList) + { + PersistenceData persistenceData = ReadPersistenceDataFromNode(node); + XmlNode filterNode = node.SelectSingleNode("tabFilter"); + + if (filterNode != null) + { + List filterList = ReadFilter(filterNode as XmlElement); + FilterTabData data = new() + { + PersistenceData = persistenceData, + FilterParams = filterList[0] // there's only 1 + }; + + dataList.Add(data); + } + } + } + return dataList; + } + + + private static void WriteFilter (XmlDocument xmlDoc, XmlElement rootElement, List filterList) + { + XmlElement filtersElement = xmlDoc.CreateElement("filters"); + rootElement.AppendChild(filtersElement); + foreach (FilterParams filterParams in filterList) + { + XmlElement filterElement = xmlDoc.CreateElement("filter"); + XmlElement paramsElement = xmlDoc.CreateElement("params"); + + MemoryStream stream = new(capacity: 200); + JsonSerializer.Serialize(stream, filterParams); + var base64Data = Convert.ToBase64String(stream.ToArray()); + paramsElement.InnerText = base64Data; + filterElement.AppendChild(paramsElement); + filtersElement.AppendChild(filterElement); + } + } + + + private static List ReadFilter (XmlElement startNode) + { + List filterList = []; + XmlNode filtersNode = startNode.SelectSingleNode("filters"); + if (filtersNode != null) + { + XmlNodeList filterNodeList = filtersNode.ChildNodes; // all "filter" nodes + foreach (XmlNode node in filterNodeList) + { + foreach (XmlNode subNode in node.ChildNodes) + { + if (subNode.Name.Equals("params", StringComparison.OrdinalIgnoreCase)) + { + var base64Text = subNode.InnerText; + var data = Convert.FromBase64String(base64Text); + MemoryStream stream = new(data); + + try + { + FilterParams filterParams = JsonSerializer.Deserialize(stream); + filterParams.Init(); + filterList.Add(filterParams); + } + catch (JsonException ex) + { + _logger.Error($"Error while deserializing filter params. Exception Message: {ex.Message}"); + } + } + } + } + } + return filterList; + } + + + private static void WriteBookmarks (XmlDocument xmlDoc, XmlElement rootElement, + SortedList bookmarkList) + { + XmlElement bookmarksElement = xmlDoc.CreateElement("bookmarks"); + rootElement.AppendChild(bookmarksElement); + foreach (Entities.Bookmark bookmark in bookmarkList.Values) + { + XmlElement bookmarkElement = xmlDoc.CreateElement("bookmark"); + bookmarkElement.SetAttribute("line", "" + bookmark.LineNum); + XmlElement textElement = xmlDoc.CreateElement("text"); + textElement.InnerText = bookmark.Text; + XmlElement posXElement = xmlDoc.CreateElement("posX"); + XmlElement posYElement = xmlDoc.CreateElement("posY"); + posXElement.InnerText = "" + bookmark.OverlayOffset.Width; + posYElement.InnerText = "" + bookmark.OverlayOffset.Height; + bookmarkElement.AppendChild(textElement); + bookmarkElement.AppendChild(posXElement); + bookmarkElement.AppendChild(posYElement); + bookmarksElement.AppendChild(bookmarkElement); + } + } + + + private static PersistenceData Load (string fileName) + { + XmlDocument xmlDoc = new(); + xmlDoc.Load(fileName); + XmlNode fileNode = xmlDoc.SelectSingleNode("logexpert/file"); + PersistenceData persistenceData = new(); + if (fileNode != null) + { + persistenceData = ReadPersistenceDataFromNode(fileNode); + } + return persistenceData; + } + + private static PersistenceData ReadPersistenceDataFromNode (XmlNode node) + { + PersistenceData persistenceData = new(); + var fileElement = node as XmlElement; + persistenceData.BookmarkList = ReadBookmarks(fileElement); + persistenceData.RowHeightList = ReadRowHeightList(fileElement); + ReadOptions(fileElement, persistenceData); + persistenceData.FileName = fileElement.GetAttribute("fileName"); + var sLineCount = fileElement.GetAttribute("lineCount"); + if (sLineCount != null && sLineCount.Length > 0) + { + persistenceData.LineCount = int.Parse(sLineCount); + } + persistenceData.FilterParamsList = ReadFilter(fileElement); + persistenceData.FilterTabDataList = ReadFilterTabs(fileElement); + persistenceData.Encoding = ReadEncoding(fileElement); + return persistenceData; + } + + + private static Encoding ReadEncoding (XmlElement fileElement) + { + XmlNode encodingNode = fileElement.SelectSingleNode("encoding"); + if (encodingNode != null) + { + XmlAttribute encAttr = encodingNode.Attributes["name"]; + try + { + return encAttr == null ? null : Encoding.GetEncoding(encAttr.Value); + } + catch (ArgumentException e) + { + _logger.Error(e); + return Encoding.Default; + } + catch (NotSupportedException e) + { + _logger.Error(e); + return Encoding.Default; + } + } + return null; + } + + + private static SortedList ReadBookmarks (XmlElement startNode) + { + SortedList bookmarkList = []; + XmlNode boomarksNode = startNode.SelectSingleNode("bookmarks"); + if (boomarksNode != null) + { + XmlNodeList bookmarkNodeList = boomarksNode.ChildNodes; // all "bookmark" nodes + foreach (XmlNode node in bookmarkNodeList) + { + string text = null; + string posX = null; + string posY = null; + string line = null; + + foreach (XmlAttribute attr in node.Attributes) + { + if (attr.Name.Equals("line", StringComparison.OrdinalIgnoreCase)) + { + line = attr.InnerText; + } + } + foreach (XmlNode subNode in node.ChildNodes) + { + if (subNode.Name.Equals("text", StringComparison.OrdinalIgnoreCase)) + { + text = subNode.InnerText; + } + else if (subNode.Name.Equals("posX", StringComparison.OrdinalIgnoreCase)) + { + posX = subNode.InnerText; + } + else if (subNode.Name.Equals("posY", StringComparison.OrdinalIgnoreCase)) + { + posY = subNode.InnerText; + } + } + if (line == null || posX == null || posY == null) + { + _logger.Error($"Invalid XML format for bookmark: {node.InnerText}"); + continue; + } + var lineNum = int.Parse(line); + + Entities.Bookmark bookmark = new(lineNum) + { + OverlayOffset = new Size(int.Parse(posX), int.Parse(posY)) + }; + + if (text != null) + { + bookmark.Text = text; + } + bookmarkList.Add(lineNum, bookmark); + } + } + return bookmarkList; + } + + private static void WriteRowHeightList (XmlDocument xmlDoc, XmlElement rootElement, SortedList rowHeightList) + { + XmlElement rowheightElement = xmlDoc.CreateElement("rowheights"); + rootElement.AppendChild(rowheightElement); + foreach (RowHeightEntry entry in rowHeightList.Values) + { + XmlElement entryElement = xmlDoc.CreateElement("rowheight"); + entryElement.SetAttribute("line", "" + entry.LineNum); + entryElement.SetAttribute("height", "" + entry.Height); + rowheightElement.AppendChild(entryElement); + } + } + + private static SortedList ReadRowHeightList (XmlElement startNode) + { + SortedList rowHeightList = []; + XmlNode rowHeightsNode = startNode.SelectSingleNode("rowheights"); + if (rowHeightsNode != null) + { + XmlNodeList rowHeightNodeList = rowHeightsNode.ChildNodes; // all "rowheight" nodes + foreach (XmlNode node in rowHeightNodeList) + { + string height = null; + string line = null; + foreach (XmlAttribute attr in node.Attributes) + { + if (attr.Name.Equals("line", StringComparison.OrdinalIgnoreCase)) + { + line = attr.InnerText; + } + else if (attr.Name.Equals("height", StringComparison.OrdinalIgnoreCase)) + { + height = attr.InnerText; + } + } + var lineNum = int.Parse(line); + var heightValue = int.Parse(height); + rowHeightList.Add(lineNum, new RowHeightEntry(lineNum, heightValue)); + } + } + return rowHeightList; + } + + + private static void WriteOptions (XmlDocument xmlDoc, XmlElement rootElement, PersistenceData persistenceData) + { + XmlElement optionsElement = xmlDoc.CreateElement("options"); + rootElement.AppendChild(optionsElement); + + XmlElement element = xmlDoc.CreateElement("multifile"); + element.SetAttribute("enabled", persistenceData.MultiFile ? "1" : "0"); + element.SetAttribute("pattern", persistenceData.MultiFilePattern); + element.SetAttribute("maxDays", "" + persistenceData.MultiFileMaxDays); + foreach (var fileName in persistenceData.MultiFileNames) + { + XmlElement entryElement = xmlDoc.CreateElement("fileEntry"); + entryElement.SetAttribute("fileName", "" + fileName); + element.AppendChild(entryElement); + } + optionsElement.AppendChild(element); + + element = xmlDoc.CreateElement("currentline"); + element.SetAttribute("line", "" + persistenceData.CurrentLine); + optionsElement.AppendChild(element); + + element = xmlDoc.CreateElement("firstDisplayedLine"); + element.SetAttribute("line", "" + persistenceData.FirstDisplayedLine); + optionsElement.AppendChild(element); + + element = xmlDoc.CreateElement("filter"); + element.SetAttribute("visible", persistenceData.FilterVisible ? "1" : "0"); + element.SetAttribute("advanced", persistenceData.FilterAdvanced ? "1" : "0"); + element.SetAttribute("position", "" + persistenceData.FilterPosition); + optionsElement.AppendChild(element); + + element = xmlDoc.CreateElement("bookmarklist"); + element.SetAttribute("visible", persistenceData.BookmarkListVisible ? "1" : "0"); + element.SetAttribute("position", "" + persistenceData.BookmarkListPosition); + optionsElement.AppendChild(element); + + element = xmlDoc.CreateElement("followTail"); + element.SetAttribute("enabled", persistenceData.FollowTail ? "1" : "0"); + optionsElement.AppendChild(element); + + element = xmlDoc.CreateElement("tab"); + element.SetAttribute("name", persistenceData.TabName); + rootElement.AppendChild(element); + + element = xmlDoc.CreateElement("columnizer"); + element.SetAttribute("name", persistenceData.ColumnizerName); + rootElement.AppendChild(element); + + element = xmlDoc.CreateElement("highlightGroup"); + element.SetAttribute("name", persistenceData.HighlightGroupName); + rootElement.AppendChild(element); + + element = xmlDoc.CreateElement("bookmarkCommentColumn"); + element.SetAttribute("visible", persistenceData.ShowBookmarkCommentColumn ? "1" : "0"); + optionsElement.AppendChild(element); + + element = xmlDoc.CreateElement("filterSaveList"); + element.SetAttribute("visible", persistenceData.FilterSaveListVisible ? "1" : "0"); + optionsElement.AppendChild(element); + } + + + private static void ReadOptions (XmlElement startNode, PersistenceData persistenceData) + { + XmlNode optionsNode = startNode.SelectSingleNode("options"); + var value = GetOptionsAttribute(optionsNode, "multifile", "enabled"); + persistenceData.MultiFile = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + persistenceData.MultiFilePattern = GetOptionsAttribute(optionsNode, "multifile", "pattern"); + value = GetOptionsAttribute(optionsNode, "multifile", "maxDays"); + try + { + persistenceData.MultiFileMaxDays = value != null ? short.Parse(value) : 0; + } + catch (Exception) + { + persistenceData.MultiFileMaxDays = 0; + } + + XmlNode multiFileNode = optionsNode.SelectSingleNode("multifile"); + if (multiFileNode != null) + { + XmlNodeList multiFileNodeList = multiFileNode.ChildNodes; // all "fileEntry" nodes + foreach (XmlNode node in multiFileNodeList) + { + string fileName = null; + foreach (XmlAttribute attr in node.Attributes) + { + if (attr.Name.Equals("fileName", StringComparison.OrdinalIgnoreCase)) + { + fileName = attr.InnerText; + } + } + persistenceData.MultiFileNames.Add(fileName); + } + } + + value = GetOptionsAttribute(optionsNode, "currentline", "line"); + if (value != null) + { + persistenceData.CurrentLine = int.Parse(value); + } + value = GetOptionsAttribute(optionsNode, "firstDisplayedLine", "line"); + if (value != null) + { + persistenceData.FirstDisplayedLine = int.Parse(value); + } + + value = GetOptionsAttribute(optionsNode, "filter", "visible"); + persistenceData.FilterVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + value = GetOptionsAttribute(optionsNode, "filter", "advanced"); + persistenceData.FilterAdvanced = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + value = GetOptionsAttribute(optionsNode, "filter", "position"); + if (value != null) + { + persistenceData.FilterPosition = int.Parse(value); + } + + value = GetOptionsAttribute(optionsNode, "bookmarklist", "visible"); + persistenceData.BookmarkListVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + value = GetOptionsAttribute(optionsNode, "bookmarklist", "position"); + if (value != null) + { + persistenceData.BookmarkListPosition = int.Parse(value); + } + + value = GetOptionsAttribute(optionsNode, "followTail", "enabled"); + persistenceData.FollowTail = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + + value = GetOptionsAttribute(optionsNode, "bookmarkCommentColumn", "visible"); + persistenceData.ShowBookmarkCommentColumn = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + + value = GetOptionsAttribute(optionsNode, "filterSaveList", "visible"); + persistenceData.FilterSaveListVisible = value != null && value.Equals("1", StringComparison.OrdinalIgnoreCase); + + XmlNode tabNode = startNode.SelectSingleNode("tab"); + if (tabNode != null) + { + persistenceData.TabName = (tabNode as XmlElement).GetAttribute("name"); + } + XmlNode columnizerNode = startNode.SelectSingleNode("columnizer"); + if (columnizerNode != null) + { + persistenceData.ColumnizerName = (columnizerNode as XmlElement).GetAttribute("name"); + } + XmlNode highlightGroupNode = startNode.SelectSingleNode("highlightGroup"); + if (highlightGroupNode != null) + { + persistenceData.HighlightGroupName = (highlightGroupNode as XmlElement).GetAttribute("name"); + } + } + + + private static string GetOptionsAttribute (XmlNode optionsNode, string elementName, string attrName) + { + XmlNode node = optionsNode.SelectSingleNode(elementName); + if (node == null) + { + return null; + } + if (node is XmlElement) + { + var value = (node as XmlElement).GetAttribute(attrName); + return value; + } + else + { + return null; + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Persister/ProjectData.cs b/src/LogExpert.Core/Classes/Persister/ProjectData.cs new file mode 100644 index 00000000..8b9dcaf3 --- /dev/null +++ b/src/LogExpert.Core/Classes/Persister/ProjectData.cs @@ -0,0 +1,12 @@ +namespace LogExpert.Core.Classes.Persister; + +public class ProjectData +{ + #region Fields + + public List MemberList { get; set; } = []; + + public string TabLayoutXml { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/Persister/ProjectPersister.cs b/src/LogExpert.Core/Classes/Persister/ProjectPersister.cs new file mode 100644 index 00000000..12963b28 --- /dev/null +++ b/src/LogExpert.Core/Classes/Persister/ProjectPersister.cs @@ -0,0 +1,67 @@ +using System.Collections.Generic; +using System.Xml; + +namespace LogExpert.Core.Classes.Persister; + +public static class ProjectPersister +{ + #region Public methods + + public static ProjectData LoadProjectData(string projectFileName) + { + ProjectData projectData = new(); + XmlDocument xmlDoc = new(); + xmlDoc.Load(projectFileName); + XmlNodeList fileList = xmlDoc.GetElementsByTagName("member"); + foreach (XmlNode fileNode in fileList) + { + var fileElement = fileNode as XmlElement; + var fileName = fileElement.GetAttribute("fileName"); + projectData.MemberList.Add(fileName); + } + XmlNodeList layoutElements = xmlDoc.GetElementsByTagName("layout"); + if (layoutElements.Count > 0) + { + projectData.TabLayoutXml = layoutElements[0].InnerXml; + } + return projectData; + } + + + public static void SaveProjectData(string projectFileName, ProjectData projectData) + { + XmlDocument xmlDoc = new(); + XmlElement rootElement = xmlDoc.CreateElement("logexpert"); + xmlDoc.AppendChild(rootElement); + XmlElement projectElement = xmlDoc.CreateElement("project"); + rootElement.AppendChild(projectElement); + XmlElement membersElement = xmlDoc.CreateElement("members"); + projectElement.AppendChild(membersElement); + SaveProjectMembers(xmlDoc, membersElement, projectData.MemberList); + + if (projectData.TabLayoutXml != null) + { + XmlElement layoutElement = xmlDoc.CreateElement("layout"); + layoutElement.InnerXml = projectData.TabLayoutXml; + rootElement.AppendChild(layoutElement); + } + + xmlDoc.Save(projectFileName); + } + + #endregion + + #region Private Methods + + private static void SaveProjectMembers(XmlDocument xmlDoc, XmlNode membersNode, List memberList) + { + foreach (var fileName in memberList) + { + XmlElement memberElement = xmlDoc.CreateElement("member"); + membersNode.AppendChild(memberElement); + memberElement.SetAttribute("fileName", fileName); + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/QualityInfo.cs b/src/LogExpert.Core/Classes/QualityInfo.cs new file mode 100644 index 00000000..7e150c3d --- /dev/null +++ b/src/LogExpert.Core/Classes/QualityInfo.cs @@ -0,0 +1,6 @@ +namespace LogExpert.Core.Classes; + +public class QualityInfo +{ + public int Quality { get; set; } +} diff --git a/src/LogExpert.Core/Classes/SpreadEntry.cs b/src/LogExpert.Core/Classes/SpreadEntry.cs new file mode 100644 index 00000000..c6fce9d8 --- /dev/null +++ b/src/LogExpert.Core/Classes/SpreadEntry.cs @@ -0,0 +1,27 @@ +namespace LogExpert.Core.Classes; + +public class SpreadEntry +{ + #region Fields + + public int Diff { get; set; } + + public DateTime Timestamp { get; set; } + + public int LineNum { get; set; } + + public int Value { get; set; } + + #endregion + + #region cTor + + public SpreadEntry (int lineNum, int diff, DateTime timestamp) + { + LineNum = lineNum; + Diff = diff; + Timestamp = timestamp; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/SysoutPipe.cs b/src/LogExpert.Core/Classes/SysoutPipe.cs new file mode 100644 index 00000000..4068cf1c --- /dev/null +++ b/src/LogExpert.Core/Classes/SysoutPipe.cs @@ -0,0 +1,117 @@ +using NLog; + +using System.Diagnostics; +using System.Globalization; +using System.Text; + +namespace LogExpert.Core.Classes; + +public class SysoutPipe : IDisposable +{ + #region Fields + + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + private readonly StreamReader _sysout; + private StreamWriter _writer; + private bool _disposed; + + #endregion + + #region cTor + + public SysoutPipe(StreamReader sysout) + { + _disposed = false; + this._sysout = sysout; + FileName = Path.GetTempFileName(); + _logger.Info(CultureInfo.InvariantCulture, "sysoutPipe created temp file: {0}", FileName); + + FileStream fStream = new(FileName, FileMode.Append, FileAccess.Write, FileShare.Read); + _writer = new StreamWriter(fStream, Encoding.Unicode); + + Thread thread = new(new ThreadStart(ReaderThread)) + { + IsBackground = true + }; + thread.Start(); + } + + #endregion + + #region Properties + + public string FileName { get; } + + #endregion + + #region Public methods + + public void ClosePipe() + { + _writer.Close(); + _writer = null; + } + + + public void DataReceivedEventHandler(object sender, DataReceivedEventArgs e) + { + _writer.WriteLine(e.Data); + } + + public void ProcessExitedEventHandler(object sender, System.EventArgs e) + { + //ClosePipe(); + if (sender.GetType() == typeof(Process)) + { + ((Process)sender).Exited -= ProcessExitedEventHandler; + ((Process)sender).OutputDataReceived -= DataReceivedEventHandler; + } + } + + #endregion + + protected void ReaderThread() + { + var buff = new char[256]; + + while (true) + { + try + { + var read = _sysout.Read(buff, 0, 256); + if (read == 0) + { + break; + } + _writer.Write(buff, 0, read); + } + catch (IOException e) + { + _logger.Error(e); + break; + } + } + + ClosePipe(); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); // Suppress finalization (not needed but best practice) + } + + protected virtual void Dispose(bool disposing) + { + if (!_disposed) + { + if (disposing) + { + _writer.Dispose(); // Dispose managed resources + } + + _disposed = true; + } + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/UsedComponents.cs b/src/LogExpert.Core/Classes/UsedComponents.cs new file mode 100644 index 00000000..6f62b6cd --- /dev/null +++ b/src/LogExpert.Core/Classes/UsedComponents.cs @@ -0,0 +1,19 @@ +namespace LogExpert.Core.Classes; + +[Serializable] +public class UsedComponents +{ + public string PackageId { get; set; } + + public string PackageVersion { get; set; } + + public string PackageProjectUrl { get; set; } + + public string Copyright { get; set; } + + public string Authors { get; set; } + + public string License { get; set; } + + public string LicenseUrl { get; set; } +} diff --git a/src/LogExpert.Core/Classes/Util.cs b/src/LogExpert.Core/Classes/Util.cs new file mode 100644 index 00000000..17c317ba --- /dev/null +++ b/src/LogExpert.Core/Classes/Util.cs @@ -0,0 +1,635 @@ +using System.Diagnostics; +using System.Drawing; +using System.Runtime.Versioning; +using System.Text.RegularExpressions; + +using LogExpert.Core.Classes.Filter; + +namespace LogExpert.Core.Classes; + +public class Util +{ + #region Public methods + + public static string GetNameFromPath (string fileName) + { + var i = fileName.LastIndexOf('\\'); + + if (i < 0) + { + i = fileName.LastIndexOf('/'); + } + + if (i < 0) + { + i = -1; + } + + return fileName[(i + 1)..]; + } + + //TODO Add Null Check (https://github.com/LogExperts/LogExpert/issues/403) + public static string StripExtension (string fileName) + { + var i = fileName.LastIndexOf('.'); + + if (i < 0) + { + i = fileName.Length - 1; + } + + return fileName[..i]; + } + + //TODO Add Null Check (https://github.com/LogExperts/LogExpert/issues/403) + public static string GetExtension (string fileName) + { + var i = fileName.LastIndexOf('.'); + + return i < 0 || i >= fileName.Length - 1 + ? string.Empty + : fileName[(i + 1)..]; + } + + + public static string GetFileSizeAsText (long size) + { + return size < 1024 + ? string.Empty + size + " bytes" + : size < 1024 * 1024 + ? string.Empty + (size / 1024) + " KB" + : string.Empty + $"{size / 1048576.0:0.00}" + " MB"; + } + + //TOOD: check if the callers are checking for null before calling + public static bool TestFilterCondition (FilterParams filterParams, ILogLine line, ILogLineColumnizerCallback columnizerCallback) + { + ArgumentNullException.ThrowIfNull(filterParams, nameof(filterParams)); + ArgumentNullException.ThrowIfNull(line, nameof(line)); + + if (filterParams.LastLine.Equals(line.FullLine, StringComparison.OrdinalIgnoreCase)) + { + return filterParams.LastResult; + } + + var match = TestFilterMatch(filterParams, line, columnizerCallback); + filterParams.LastLine = line.FullLine; + + if (filterParams.IsRangeSearch) + { + if (!filterParams.IsInRange) + { + if (match) + { + filterParams.IsInRange = true; + } + } + else + { + if (!match) + { + match = true; + } + else + { + filterParams.IsInRange = false; + } + } + } + + if (filterParams.IsInvert) + { + match = !match; + } + + filterParams.LastResult = match; + return match; + } + + //TODO Add Null Checks (https://github.com/LogExperts/LogExpert/issues/403) + public static int DamerauLevenshteinDistance (string src, string dest) + { + var d = new int[src.Length + 1, dest.Length + 1]; + int i, j, cost; + var str1 = src.ToCharArray(); + var str2 = dest.ToCharArray(); + + for (i = 0; i <= str1.Length; i++) + { + d[i, 0] = i; + } + + for (j = 0; j <= str2.Length; j++) + { + d[0, j] = j; + } + + for (i = 1; i <= str1.Length; i++) + { + for (j = 1; j <= str2.Length; j++) + { + cost = str1[i - 1] == str2[j - 1] + ? 0 + : 1; + + d[i, j] = + Math.Min(d[i - 1, j] + 1, // Deletion + Math.Min(d[i, j - 1] + 1, // Insertion + d[i - 1, j - 1] + cost)); // Substitution + + if (i > 1 && j > 1 && str1[i - 1] == str2[j - 2] && str1[i - 2] == str2[j - 1]) + { + d[i, j] = Math.Min(d[i, j], d[i - 2, j - 2] + cost); + } + } + } + return d[str1.Length, str2.Length]; + } + + //TODO Add Null Checks (https://github.com/LogExperts/LogExpert/issues/403) + public static unsafe int YetiLevenshtein (string s1, string s2) + { + fixed (char* p1 = s1) + fixed (char* p2 = s2) + { + return YetiLevenshtein(p1, s1.Length, p2, s2.Length, 0); // substitutionCost = 1 + } + } + + public static unsafe int YetiLevenshtein (string s1, string s2, int substitionCost) + { + var xc = substitionCost - 1; + + if (xc is < 0 or > 1) + { + throw new ArgumentException("", nameof(substitionCost)); + } + + fixed (char* p1 = s1) + fixed (char* p2 = s2) + { + return YetiLevenshtein(p1, s1.Length, p2, s2.Length, xc); + } + } + + /// + /// Cetin Sert, David Necas + /// Source Code + /// + /// + /// + /// + /// + /// + /// + public static unsafe int YetiLevenshtein (char* s1, int l1, char* s2, int l2, int xcost) + { + int i; + //int *row; /* we only need to keep one row of costs */ + int* end; + int half; + + /* strip common prefix */ + while (l1 > 0 && l2 > 0 && *s1 == *s2) + { + l1--; + l2--; + s1++; + s2++; + } + + /* strip common suffix */ + while (l1 > 0 && l2 > 0 && s1[l1 - 1] == s2[l2 - 1]) + { + l1--; + l2--; + } + + /* catch trivial cases */ + if (l1 == 0) + { + return l2; + } + + if (l2 == 0) + { + return l1; + } + + /* make the inner cycle (i.e. string2) the longer one */ + if (l1 > l2) + { + var nx = l1; + var sx = s1; + l1 = l2; + l2 = nx; + s1 = s2; + s2 = sx; + } + + //check len1 == 1 separately + if (l1 == 1) + { + //throw new NotImplementedException(); + return xcost > 0 + ? l2 + 1 - (2 * MemchrRPLC(s2, *s1, l2)) + : l2 - MemchrRPLC(s2, *s1, l2); + } + + l1++; + l2++; + half = l1 >> 1; + + /* initalize first row */ + //row = (int*)malloc(l2*sizeof(int)); + var row = stackalloc int[l2]; + + if (l2 < 0) + //if (!row) + { + return -1; + } + + end = row + l2 - 1; + + for (i = 0; i < l2 - (xcost > 0 ? 0 : half); i++) + { + row[i] = i; + } + + /* go through the matrix and compute the costs. yes, this is an extremely + * obfuscated version, but also extremely memory-conservative and + * relatively fast. + */ + if (xcost > 0) + { + for (i = 1; i < l1; i++) + { + var p = row + 1; + var char1 = s1[i - 1]; + var char2p = s2; + var D = i; + var x = i; + + while (p <= end) + { + if (char1 == *char2p++) + { + x = --D; + } + else + { + x++; + } + + D = *p; + D++; + + if (x > D) + { + x = D; + } + + *p++ = x; + } + } + } + else + { + /* in this case we don't have to scan two corner triangles (of size len1/2) + * in the matrix because no best path can go throught them. note this + * breaks when len1 == len2 == 2 so the memchr() special case above is + * necessary */ + row[0] = l1 - half - 1; + for (i = 1; i < l1; i++) + { + int* p; + var char1 = s1[i - 1]; + char* char2p; + int D, x; + + /* skip the upper triangle */ + if (i >= l1 - half) + { + var offset = i - (l1 - half); + int c3; + + char2p = s2 + offset; + p = row + offset; + c3 = *p++ + (char1 != *char2p++ ? 1 : 0); + x = *p; + x++; + D = x; + + if (x > c3) + { + x = c3; + } + + *p++ = x; + } + else + { + p = row + 1; + char2p = s2; + D = x = i; + } + + /* skip the lower triangle */ + if (i <= half + 1) + { + end = row + l2 + i - half - 2; + } + + /* main */ + while (p <= end) + { + var c3 = --D + (char1 != *char2p++ ? 1 : 0); + x++; + + if (x > c3) + { + x = c3; + } + + D = *p; + D++; + + if (x > D) + { + x = D; + } + + *p++ = x; + } + + /* lower triangle sentinel */ + if (i <= half) + { + var c3 = --D + (char1 != *char2p ? 1 : 0); + x++; + if (x > c3) + { + x = c3; + } + + *p = x; + } + } + } + + i = *end; + return i; + } + + /// + /// Returns true, if the given string is null or empty + /// + /// + /// + public static bool IsNull (string toTest) + { + return toTest == null || toTest.Length == 0; + } + + /// + /// Returns true, if the given string is null or empty or contains only spaces + /// + /// + /// + public static bool IsNullOrSpaces (string toTest) + { + return toTest == null || toTest.Trim().Length == 0; + } + + [Conditional("DEBUG")] + public static void AssertTrue (bool condition, string msg) + { + if (!condition) + { + //Todo this should be done differently + //MessageBox.Show("Assertion: " + msg); + throw new Exception(msg); + } + } + + //TODO Add Null Check (https://github.com/LogExperts/LogExpert/issues/403) + [SupportedOSPlatform("windows")] + public string? GetWordFromPos (int xPos, string text, Graphics g, Font font) + { + var words = text.Split([' ', '.', ':', ';']); + + var index = 0; + + List crList = []; + + for (var i = 0; i < words.Length; ++i) + { + crList.Add(new CharacterRange(index, words[i].Length)); + index += words[i].Length; + } + + CharacterRange[] crArray = [.. crList]; + + StringFormat stringFormat = new(StringFormat.GenericTypographic) + { + Trimming = StringTrimming.None, + FormatFlags = StringFormatFlags.NoClip + }; + + stringFormat.SetMeasurableCharacterRanges(crArray); + + RectangleF rect = new(0, 0, 3000, 20); + Region[] stringRegions = g.MeasureCharacterRanges(text, font, rect, stringFormat); + + var found = false; + + var y = 0; + + foreach (Region regio in stringRegions) + { + if (regio.IsVisible(xPos, 3, g)) + { + found = true; + break; + } + + y++; + } + + return found + ? words[y] + : null; + } + + #endregion + + #region Private Methods + + private static bool TestFilterMatch (FilterParams filterParams, ILogLine line, ILogLineColumnizerCallback columnizerCallback) + { + string normalizedSearchText; + string searchText; + Regex rex; + + if (filterParams.IsInRange) + { + normalizedSearchText = filterParams.NormalizedRangeSearchText; + searchText = filterParams.RangeSearchText; + rex = filterParams.RangeRex; + } + else + { + normalizedSearchText = filterParams.NormalizedSearchText; + searchText = filterParams.SearchText; + rex = filterParams.Rex; + } + + if (string.IsNullOrEmpty(searchText)) + { + return false; + } + + if (filterParams.ColumnRestrict) + { + IColumnizedLogLine columns = filterParams.CurrentColumnizer.SplitLine(columnizerCallback, line); + var found = false; + foreach (var colIndex in filterParams.ColumnList) + { + if (colIndex < columns.ColumnValues.Length + ) // just to be sure, maybe the columnizer has changed anyhow + { + if (columns.ColumnValues[colIndex].FullValue.Trim().Length == 0) + { + if (filterParams.EmptyColumnUsePrev) + { + var prevValue = (string)filterParams.LastNonEmptyCols[colIndex]; + if (prevValue != null) + { + if (TestMatchSub(filterParams, prevValue, normalizedSearchText, searchText, rex, + filterParams.ExactColumnMatch)) + { + found = true; + } + } + } + else if (filterParams.EmptyColumnHit) + { + return true; + } + } + else + { + filterParams.LastNonEmptyCols[colIndex] = columns.ColumnValues[colIndex].FullValue; + if (TestMatchSub(filterParams, columns.ColumnValues[colIndex].FullValue, normalizedSearchText, + searchText, rex, + filterParams.ExactColumnMatch)) + { + found = true; + } + } + } + } + + return found; + } + else + { + return TestMatchSub(filterParams, line.FullLine, normalizedSearchText, searchText, rex, false); + } + } + + private static bool TestMatchSub (FilterParams filterParams, string line, string lowerSearchText, string searchText, Regex rex, bool exactMatch) + { + if (filterParams.IsRegex) + { + if (rex.IsMatch(line)) + { + return true; + } + } + else + { + if (!filterParams.IsCaseSensitive) + { + if (exactMatch) + { + if (line.ToUpperInvariant().Trim().Equals(lowerSearchText, StringComparison.Ordinal)) + { + return true; + } + } + else + { + if (line.Contains(lowerSearchText, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + else + { + if (exactMatch) + { + if (line.Equals(searchText, StringComparison.Ordinal)) + { + return true; + } + } + else + { + if (line.Contains(searchText, StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + + if (filterParams.FuzzyValue > 0) + { + var range = line.Length - searchText.Length; + if (range > 0) + { + for (var i = 0; i < range; ++i) + { + var src = line.Substring(i, searchText.Length); + + if (!filterParams.IsCaseSensitive) + { + src = src.ToLowerInvariant(); + } + + var dist = DamerauLevenshteinDistance(src, searchText); + + if ((searchText.Length + 1) / (float)(dist + 1) >= 11F / (float)(filterParams.FuzzyValue + 1F)) + { + return true; + } + } + } + + return false; + } + } + + return false; + } + + private static unsafe int MemchrRPLC (char* buffer, char c, int count) + { + var p = buffer; + var e = buffer + count; + + while (p++ < e) + { + if (*p == c) + { + return 1; + } + } + + return 0; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/xml/XmlBlockSplitter.cs b/src/LogExpert.Core/Classes/xml/XmlBlockSplitter.cs new file mode 100644 index 00000000..1188c203 --- /dev/null +++ b/src/LogExpert.Core/Classes/xml/XmlBlockSplitter.cs @@ -0,0 +1,173 @@ +using LogExpert.Core.Classes.Log; + +using System.Text; +using System.Xml; +using System.Xml.Xsl; + +namespace LogExpert.Core.Classes.xml; + +public class XmlBlockSplitter : LogStreamReaderBase +{ + #region Fields + + private static readonly string[] _splitStrings = ["\r\n", "\n", "\r"]; + + private static readonly char[] _newLineChar = ['\n']; + + private readonly XmlLogReader _reader; + + private readonly XmlParserContext _context; + private readonly XmlReaderSettings _settings; + + private readonly Queue _lineList = new(); + + private string _stylesheet; + private XslCompiledTransform _xslt; + + public override bool IsDisposed { get; protected set; } + + #endregion + + #region cTor + + public XmlBlockSplitter(XmlLogReader reader, IXmlLogConfiguration xmlLogConfig) + { + _reader = reader; + _reader.StartTag = xmlLogConfig.XmlStartTag; + _reader.EndTag = xmlLogConfig.XmlEndTag; + + Stylesheet = xmlLogConfig.Stylesheet; + + // Create the XmlNamespaceManager. + NameTable nt = new(); + XmlNamespaceManager nsmgr = new(nt); + var namespaceDeclaration = xmlLogConfig.GetNamespaceDeclaration(); + if (namespaceDeclaration != null) + { + nsmgr.AddNamespace(namespaceDeclaration[0], namespaceDeclaration[1]); + } + // Create the XmlParserContext. + _context = new XmlParserContext(nt, nsmgr, null, XmlSpace.None); + _settings = new XmlReaderSettings(); + _settings.ConformanceLevel = ConformanceLevel.Fragment; + } + + #endregion + + #region Properties + + public override long Position + { + get => _reader.Position; + set => _reader.Position = value; + } + + public override Encoding Encoding => _reader.Encoding; + + public override bool IsBufferComplete => _lineList.Count == 0; + + public string Stylesheet + { + get => _stylesheet; + set + { + _stylesheet = value; + if (_stylesheet != null) + { + var stylesheetReader = XmlReader.Create(new StringReader(_stylesheet)); + + _xslt = new XslCompiledTransform(); + _xslt.Load(stylesheetReader); + } + else + { + _xslt = null; + } + } + } + + #endregion + + #region Private Methods + + private void ParseXmlBlock(string block) + { + if (_stylesheet != null) + { + var xmlReader = XmlReader.Create(new StringReader(block), _settings, _context); + + xmlReader.Read(); + xmlReader.MoveToContent(); + //xmlReader.MoveToContent(); + StringWriter textWriter = new(); + + _xslt.Transform(xmlReader, null, textWriter); + var message = textWriter.ToString(); + SplitToLinesList(message); + } + else + { + SplitToLinesList(block); + //this.lineList.Add(block); // TODO: make configurable, if block has to be splitted + } + } + + private void SplitToLinesList(string message) + { + const int MAX_LEN = 3000; + var lines = message.Split(_splitStrings, StringSplitOptions.None); + foreach (var theLine in lines) + { + var line = theLine.Trim(_newLineChar); + while (line.Length > MAX_LEN) + { + var part = line.Substring(0, MAX_LEN); + line = line.Substring(MAX_LEN); + _lineList.Enqueue(part); + } + _lineList.Enqueue(line); + } + } + + #endregion + + #region Public Methods + + protected override void Dispose(bool disposing) + { + if (disposing) + { + _reader.Dispose(); + IsDisposed = true; + } + } + + public override int ReadChar() + { + return _reader.ReadChar(); + } + + public override string ReadLine() + { + if (_lineList.Count == 0) + { + var block = _reader.ReadLine(); + if (block == null) + { + return null; + } + + try + { + ParseXmlBlock(block); + } + catch (XmlException) + { + _lineList.Enqueue("[XML Parser error] " + block); + } + } + return _lineList.Dequeue(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Classes/xml/XmlLogReader.cs b/src/LogExpert.Core/Classes/xml/XmlLogReader.cs new file mode 100644 index 00000000..43c4e2c7 --- /dev/null +++ b/src/LogExpert.Core/Classes/xml/XmlLogReader.cs @@ -0,0 +1,170 @@ +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Interface; + +using System.Text; + +namespace LogExpert.Core.Classes.xml; + +public class XmlLogReader : LogStreamReaderBase +{ + #region Fields + + private readonly ILogStreamReader reader; + public override bool IsDisposed { get; protected set; } + + #endregion + + #region cTor + + public XmlLogReader(ILogStreamReader reader) + { + this.reader = reader; + } + + #endregion + + #region Properties + + public override long Position + { + get => reader.Position; + set => reader.Position = value; + } + + public override Encoding Encoding => reader.Encoding; + + public override bool IsBufferComplete => reader.IsBufferComplete; + + public string StartTag { get; set; } = " 0) + { + Thread.Sleep(100); + continue; + } + else + { + break; + } + } + else + { + break; + } + } + + var readChar = (char)readInt; + // state: + // 0 = looking for tag start + // 1 = reading into buffer as long as the read data matches the start tag + // 2 = reading into buffer while waiting for the begin of the end tag + // 3 = reading into buffer as long as data matches the end tag. stopping when tag complete + switch (state) + { + case 0: + if (readChar == StartTag[0]) + { + //_logger.logInfo("state = 1"); + state = 1; + tagIndex = 1; + builder.Append(readChar); + } + //else + //{ + // _logger.logInfo("char: " + readChar); + //} + break; + case 1: + if (readChar == StartTag[tagIndex]) + { + builder.Append(readChar); + + if (++tagIndex >= StartTag.Length) + { + //_logger.logInfo("state = 2"); + state = 2; // start Tag complete + tagIndex = 0; + } + } + else + { + // tag doesn't match anymore + //_logger.logInfo("state = 0 [" + buffer.ToString() + readChar + "]"); + state = 0; + builder.Clear(); + } + break; + case 2: + builder.Append(readChar); + + if (readChar == EndTag[0]) + { + //_logger.logInfo("state = 3"); + state = 3; + tagIndex = 1; + } + break; + case 3: + builder.Append(readChar); + + if (readChar == EndTag[tagIndex]) + { + tagIndex++; + if (tagIndex >= EndTag.Length) + { + blockComplete = true; + break; + } + } + else + { + //_logger.logInfo("state = 2"); + state = 2; + } + break; + } + } + + return blockComplete ? builder.ToString() : null; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/ColorEntry.cs b/src/LogExpert.Core/Config/ColorEntry.cs new file mode 100644 index 00000000..022f98a2 --- /dev/null +++ b/src/LogExpert.Core/Config/ColorEntry.cs @@ -0,0 +1,15 @@ +#region + +using System.Drawing; + +#endregion + +namespace LogExpert.Core.Config; + +[Serializable] +public class ColorEntry (string FileName, Color Color) +{ + public Color Color { get; } = Color; + + public string FileName { get; } = FileName; +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/ColumnizerHistoryEntry.cs b/src/LogExpert.Core/Config/ColumnizerHistoryEntry.cs new file mode 100644 index 00000000..88948893 --- /dev/null +++ b/src/LogExpert.Core/Config/ColumnizerHistoryEntry.cs @@ -0,0 +1,29 @@ +#region + +using System; + +#endregion + +namespace LogExpert.Core.Config; + +[Serializable] +public class ColumnizerHistoryEntry +{ + #region cTor + + public ColumnizerHistoryEntry(string fileName, string columnizerName) + { + FileName = fileName; + ColumnizerName = columnizerName; + } + + #endregion + + #region Fields + + public string FileName { get; } + + #endregion + + public string ColumnizerName { get; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/ColumnizerMaskEntry.cs b/src/LogExpert.Core/Config/ColumnizerMaskEntry.cs new file mode 100644 index 00000000..9e11b1de --- /dev/null +++ b/src/LogExpert.Core/Config/ColumnizerMaskEntry.cs @@ -0,0 +1,9 @@ +namespace LogExpert.Core.Config; + +[Serializable] +public class ColumnizerMaskEntry +{ + public string ColumnizerName { get; set; } + + public string Mask { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/ExportImportFlags.cs b/src/LogExpert.Core/Config/ExportImportFlags.cs new file mode 100644 index 00000000..1e3326e5 --- /dev/null +++ b/src/LogExpert.Core/Config/ExportImportFlags.cs @@ -0,0 +1,15 @@ +namespace LogExpert.Core.Config; + +[Flags] +public enum ExportImportFlags : long +{ + None = 0, + HighlightSettings = 1, + ColumnizerMasks = 2, + HighlightMasks = 4, + ToolEntries = 8, + Other = 16, + KeepExisting = 32, + All = HighlightSettings | ColumnizerMasks | HighlightMasks | ToolEntries | Other, + AllKeepExisting = All | KeepExisting +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/HighlightMaskEntry.cs b/src/LogExpert.Core/Config/HighlightMaskEntry.cs new file mode 100644 index 00000000..8f5fb108 --- /dev/null +++ b/src/LogExpert.Core/Config/HighlightMaskEntry.cs @@ -0,0 +1,9 @@ +namespace LogExpert.Core.Config; + +[Serializable] +public class HighlightMaskEntry +{ + public string HighlightGroupName { get; set; } + + public string Mask { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/MultiFileOption.cs b/src/LogExpert.Core/Config/MultiFileOption.cs new file mode 100644 index 00000000..7dce5106 --- /dev/null +++ b/src/LogExpert.Core/Config/MultiFileOption.cs @@ -0,0 +1,11 @@ +using System; + +namespace LogExpert.Core.Config; + +[Serializable] +public enum MultiFileOption +{ + SingleFiles, + MultiFile, + Ask +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/Preferences.cs b/src/LogExpert.Core/Config/Preferences.cs new file mode 100644 index 00000000..779e6fb8 --- /dev/null +++ b/src/LogExpert.Core/Config/Preferences.cs @@ -0,0 +1,107 @@ +using System.Drawing; + +using LogExpert.Core.Entities; +using LogExpert.Core.Enums; + +namespace LogExpert.Core.Config; + +[Serializable] +public class Preferences +{ + public List HighlightGroupList { get; set; } = []; + + public bool PortableMode { get; set; } + + public bool ShowErrorMessageAllowOnlyOneInstances { get; set; } + + public int MaxLineLength { get; set; } = 20000; + + public bool AllowOnlyOneInstance { get; set; } + + public bool AskForClose { get; set; } + + public bool DarkMode { get; set; } + + public bool UseLegacyReader { get; set; } + + public List ToolEntries { get; set; } = []; + + public DragOrientationsEnum TimestampControlDragOrientation { get; set; } = DragOrientationsEnum.Horizontal; + + public bool TimestampControl { get; set; } + + public bool TimeSpreadTimeMode { get; set; } + + /// + /// Save Directory of the last logfile + /// + public string SessionSaveDirectory { get; set; } + + public bool SaveFilters { get; set; } = true; + + public SessionSaveLocation SaveLocation { get; set; } = SessionSaveLocation.DocumentsDir; + + public bool SaveSessions { get; set; } = true; + + public bool SetLastColumnWidth { get; set; } + + public bool ShowBubbles { get; set; } = true; + + public bool ShowColumnFinder { get; set; } + + public Color ShowTailColor { get; set; } = Color.FromKnownColor(KnownColor.Blue); + + public bool ShowTailState { get; set; } = true; + + public bool ShowTimeSpread { get; set; } + + public Color TimeSpreadColor { get; set; } = Color.FromKnownColor(KnownColor.Gray); + + public bool IsAutoHideFilterList { get; set; } + + public bool IsFilterOnLoad { get; set; } + + public int LastColumnWidth { get; set; } = 2000; + + public int LinesPerBuffer { get; set; } = 500; + + public int MaximumFilterEntries { get; set; } = 30; + + public int MaximumFilterEntriesDisplayed { get; set; } = 20; + + public bool MaskPrio { get; set; } + + public bool AutoPick { get; set; } + + //TODO Refactor Enum + public MultiFileOption MultiFileOption { get; set; } + + //TODO Refactor Class + public MultiFileOptions MultiFileOptions { get; set; } + + public bool MultiThreadFilter { get; set; } = true; + + public bool OpenLastFiles { get; set; } = true; + + public int PollingInterval { get; set; } = 250; + + public bool ReverseAlpha { get; set; } + + public int BufferCount { get; set; } = 100; + + public List ColumnizerMaskList { get; set; } = []; + + public string DefaultEncoding { get; set; } + + public bool FilterSync { get; set; } = true; + + public bool FilterTail { get; set; } = true; + + public bool FollowTail { get; set; } = true; + + public string FontName { get; set; } = "Courier New"; + + public float FontSize { get; set; } = 9; + + public List HighlightMaskList { get; set; } = []; +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/RegexHistory.cs b/src/LogExpert.Core/Config/RegexHistory.cs new file mode 100644 index 00000000..994b21b5 --- /dev/null +++ b/src/LogExpert.Core/Config/RegexHistory.cs @@ -0,0 +1,12 @@ +using System; +using System.Collections.Generic; + +namespace LogExpert.Core.Config; + +[Serializable] +public class RegexHistory +{ + public List ExpressionHistoryList { get; set; } = []; + + public List TesttextHistoryList { get; set; } = []; +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/SessionSaveLocation.cs b/src/LogExpert.Core/Config/SessionSaveLocation.cs new file mode 100644 index 00000000..2759cb19 --- /dev/null +++ b/src/LogExpert.Core/Config/SessionSaveLocation.cs @@ -0,0 +1,25 @@ +using System; + +namespace LogExpert.Core.Config; + +[Serializable] +public enum SessionSaveLocation +{ + //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "LogExpert" + /// + /// + /// + DocumentsDir, + //same directory as the logfile + SameDir, + //uses configured folder to save the session files + /// + /// + /// + OwnDir, + /// + /// + /// + ApplicationStartupDir, + LoadedSessionFile +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/Settings.cs b/src/LogExpert.Core/Config/Settings.cs new file mode 100644 index 00000000..7ba088cf --- /dev/null +++ b/src/LogExpert.Core/Config/Settings.cs @@ -0,0 +1,50 @@ +using System.Drawing; + +using LogExpert.Core.Classes.Filter; +using LogExpert.Entities; + +namespace LogExpert.Core.Config; + +[Serializable] +public class Settings +{ + public Preferences Preferences { get; set; } = new(); + + public RegexHistory RegexHistory { get; set; } = new(); + + public bool AlwaysOnTop { get; set; } + + public Rectangle AppBounds { get; set; } + + public Rectangle AppBoundsFullscreen { get; set; } + + public IList ColumnizerHistoryList { get; set; } = []; + + public List FileColors { get; set; } = []; + + public List FileHistoryList { get; set; } = []; + + public List FilterHistoryList { get; set; } = []; + + public List FilterList { get; set; } = []; + + public FilterParams FilterParams { get; set; } = new(); + + public List FilterRangeHistoryList { get; set; } = []; + + public bool HideLineColumn { get; set; } + + public bool IsMaximized { get; set; } + + public string LastDirectory { get; set; } + + public List LastOpenFilesList { get; set; } = []; + + public List SearchHistoryList { get; set; } = []; + + public SearchParams SearchParams { get; set; } = new(); + + public IList UriHistoryList { get; set; } = []; + + public int VersionBuild { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/SettingsFlags.cs b/src/LogExpert.Core/Config/SettingsFlags.cs new file mode 100644 index 00000000..36299106 --- /dev/null +++ b/src/LogExpert.Core/Config/SettingsFlags.cs @@ -0,0 +1,23 @@ +using System; + +namespace LogExpert.Core.Config; + +[Flags] +public enum SettingsFlags : long +{ + None = 0, + WindowPosition = 1, + FileHistory = 2, + HighlightSettings = 4, + FilterList = 8, + RegexHistory = 16, + ToolSettings = 32, + GuiOrColors = 64, + FilterHistory = 128, + + All = WindowPosition | FileHistory | HighlightSettings | + FilterList | RegexHistory | ToolSettings | GuiOrColors | + FilterHistory, + + Settings = All & ~WindowPosition & ~FileHistory, +} \ No newline at end of file diff --git a/src/LogExpert.Core/Config/ToolEntry.cs b/src/LogExpert.Core/Config/ToolEntry.cs new file mode 100644 index 00000000..107ed1d3 --- /dev/null +++ b/src/LogExpert.Core/Config/ToolEntry.cs @@ -0,0 +1,51 @@ +using LogExpert.Core.Classes; + +namespace LogExpert.Core.Config; + +[Serializable] +public class ToolEntry +{ + public string Args { get; set; } = string.Empty; + + public string Cmd { get; set; } = string.Empty; + + public string ColumnizerName { get; set; } = string.Empty; + + public string IconFile { get; set; } + + public int IconIndex { get; set; } + + public bool IsFavourite { get; set; } + + public string Name { get; set; } + + public bool Sysout { get; set; } + + public string WorkingDir { get; set; } = string.Empty; + + #region Public methods + + public override string ToString () + { + return Util.IsNull(Name) ? Cmd : Name; + } + + public ToolEntry Clone () + { + ToolEntry clone = new() + { + Cmd = Cmd, + Args = Args, + Name = Name, + Sysout = Sysout, + ColumnizerName = ColumnizerName, + IsFavourite = IsFavourite, + IconFile = IconFile, + IconIndex = IconIndex, + WorkingDir = WorkingDir + }; + return clone; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/Bookmark.cs b/src/LogExpert.Core/Entities/Bookmark.cs new file mode 100644 index 00000000..4ebb1e80 --- /dev/null +++ b/src/LogExpert.Core/Entities/Bookmark.cs @@ -0,0 +1,39 @@ +using System.Drawing; + +namespace LogExpert.Core.Entities; + +public class Bookmark +{ + #region cTor + + public Bookmark(int lineNum) + { + LineNum = lineNum; + Text = string.Empty; + Overlay = new BookmarkOverlay(); + } + + public Bookmark(int lineNum, string comment) + { + LineNum = lineNum; + Text = comment; + Overlay = new BookmarkOverlay(); + } + + #endregion + + #region Properties + + public int LineNum { get; set; } + + public string Text { get; set; } + + public BookmarkOverlay Overlay { get; set; } + + /// + /// Position offset of the overlay as set by the user by dragging the overlay with the mouse. + /// + public Size OverlayOffset { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/BookmarkCollection.cs b/src/LogExpert.Core/Entities/BookmarkCollection.cs new file mode 100644 index 00000000..0cc0917c --- /dev/null +++ b/src/LogExpert.Core/Entities/BookmarkCollection.cs @@ -0,0 +1,22 @@ +using System.Collections.ObjectModel; + +namespace LogExpert.Core.Entities; + +public class BookmarkCollection : ReadOnlyCollection +{ + #region Fields + + private SortedList bookmarkList; + + #endregion + + #region cTor + + internal BookmarkCollection(SortedList bookmarkList) + : base(bookmarkList.Values) + { + this.bookmarkList = bookmarkList; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/BookmarkOverlay.cs b/src/LogExpert.Core/Entities/BookmarkOverlay.cs new file mode 100644 index 00000000..805ee15d --- /dev/null +++ b/src/LogExpert.Core/Entities/BookmarkOverlay.cs @@ -0,0 +1,16 @@ +using System.Drawing; + +namespace LogExpert.Core.Entities; + +public class BookmarkOverlay +{ + #region Properties + + public Bookmark Bookmark { get; set; } + + public Point Position { get; set; } + + public Rectangle BubbleRect { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/DebugOptions.cs b/src/LogExpert.Core/Entities/DebugOptions.cs new file mode 100644 index 00000000..fbd4b084 --- /dev/null +++ b/src/LogExpert.Core/Entities/DebugOptions.cs @@ -0,0 +1,6 @@ +namespace LogExpert.Core.Entities; + +public static class DebugOptions +{ + public static bool DisableWordHighlight { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/DefaultLogfileColumnizer.cs b/src/LogExpert.Core/Entities/DefaultLogfileColumnizer.cs new file mode 100644 index 00000000..ab955862 --- /dev/null +++ b/src/LogExpert.Core/Entities/DefaultLogfileColumnizer.cs @@ -0,0 +1,82 @@ +namespace LogExpert.Core.Entities; + +public class DefaultLogfileColumnizer : ILogLineColumnizer +{ + #region ILogLineColumnizer Members + + public string GetName() + { + return "Default (single line)"; + } + + public string GetDescription() + { + return "No column splitting. The whole line is displayed in a single column."; + } + + public int GetColumnCount() + { + return 1; + } + + public string[] GetColumnNames() + { + return ["Text"]; + } + + public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + { + ColumnizedLogLine cLogLine = new() + { + LogLine = line + }; + + cLogLine.ColumnValues = + [ + new Column + { + FullValue = line.FullLine, + Parent = cLogLine + } + ]; + + + return cLogLine; + } + + public string Text => GetName(); + + public Priority GetPriority(string fileName, IEnumerable samples) + { + return Priority.CanSupport; + } + #endregion + + #region ILogLineColumnizer Not implemented Members + + public bool IsTimeshiftImplemented() + { + return false; + } + + public void SetTimeOffset(int msecOffset) + { + throw new NotImplementedException(); + } + + public int GetTimeOffset() + { + throw new NotImplementedException(); + } + + public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + { + throw new NotImplementedException(); + } + + public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/EncodingOptions.cs b/src/LogExpert.Core/Entities/EncodingOptions.cs new file mode 100644 index 00000000..dae7e680 --- /dev/null +++ b/src/LogExpert.Core/Entities/EncodingOptions.cs @@ -0,0 +1,23 @@ +using System.Text; + +namespace LogExpert.Core.Entities; + +/// +/// Holds some encoding options. +/// +public class EncodingOptions +{ + #region Properties + + /// + /// Sets or gets the Encoding which shall be used when reading a file. A value of null means 'please autodetect' via BOM. + /// + public Encoding Encoding { get; set; } + + /// + /// The Encoding to be used when autodetect cannot be applied (missing BOM). Only used when Encoding is set to null. + /// + public Encoding DefaultEncoding { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/FileViewContext.cs b/src/LogExpert.Core/Entities/FileViewContext.cs new file mode 100644 index 00000000..8cc0a27a --- /dev/null +++ b/src/LogExpert.Core/Entities/FileViewContext.cs @@ -0,0 +1,14 @@ +using LogExpert.Core.Interface; + +namespace LogExpert.Core.Entities; + +public class FileViewContext(ILogPaintContext logPaintContext, ILogView logView) : IFileViewContext, ILogPaintContext +{ + #region Properties + + public ILogPaintContext LogPaintContext { get; } = logPaintContext; + + public ILogView LogView { get; } = logView; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/HighlightGroup.cs b/src/LogExpert.Core/Entities/HighlightGroup.cs new file mode 100644 index 00000000..a599d198 --- /dev/null +++ b/src/LogExpert.Core/Entities/HighlightGroup.cs @@ -0,0 +1,30 @@ +using LogExpert.Core.Classes.Highlight; + +namespace LogExpert.Core.Entities; + +[Serializable] +public class HighlightGroup : ICloneable +{ + #region Properties + + public string GroupName { get; set; } = string.Empty; + + public List HighlightEntryList { get; set; } = []; + + public object Clone() + { + HighlightGroup clone = new() + { + GroupName = GroupName + }; + + foreach (HighlightEntry entry in HighlightEntryList) + { + clone.HighlightEntryList.Add((HighlightEntry)entry.Clone()); + } + + return clone; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/LogEventData.cs b/src/LogExpert.Core/Entities/LogEventData.cs new file mode 100644 index 00000000..70b368b5 --- /dev/null +++ b/src/LogExpert.Core/Entities/LogEventData.cs @@ -0,0 +1,24 @@ +namespace LogExpert.Core.Entities; + +public class LogEventArgs : System.EventArgs +{ + #region Fields + + #endregion + + #region Properties + + public int RolloverOffset { get; set; } + + public bool IsRollover { get; set; } + + public long FileSize { get; set; } + + public int LineCount { get; set; } + + public int PrevLineCount { get; set; } + + public long PrevFileSize { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/LogFileException.cs b/src/LogExpert.Core/Entities/LogFileException.cs new file mode 100644 index 00000000..08384374 --- /dev/null +++ b/src/LogExpert.Core/Entities/LogFileException.cs @@ -0,0 +1,22 @@ +namespace LogExpert.Core.Entities; + +public class LogFileException : Exception +{ + #region cTor + + public LogFileException (string msg) + : base(msg) + { + } + + public LogFileException (string msg, Exception inner) + : base(msg, inner) + { + } + + public LogFileException () + { + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/MultifileOptions.cs b/src/LogExpert.Core/Entities/MultifileOptions.cs new file mode 100644 index 00000000..b9ab6d78 --- /dev/null +++ b/src/LogExpert.Core/Entities/MultifileOptions.cs @@ -0,0 +1,13 @@ +namespace LogExpert.Core.Entities; + +[Serializable] +public class MultiFileOptions +{ + #region Properties + + public int MaxDayTry { get; set; } = 3; + + public string FormatPattern { get; set; } = "*$J(.)"; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/Range.cs b/src/LogExpert.Core/Entities/Range.cs new file mode 100644 index 00000000..e9d40540 --- /dev/null +++ b/src/LogExpert.Core/Entities/Range.cs @@ -0,0 +1,30 @@ +namespace LogExpert.Core.Entities; + +public class Range +{ + #region Fields + + #endregion + + #region cTor + + public Range() + { + } + + public Range(int startLine, int endLine) + { + StartLine = startLine; + EndLine = endLine; + } + + #endregion + + #region Properties + + public int StartLine { get; set; } + + public int EndLine { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/ReloadMemento.cs b/src/LogExpert.Core/Entities/ReloadMemento.cs new file mode 100644 index 00000000..bbb82015 --- /dev/null +++ b/src/LogExpert.Core/Entities/ReloadMemento.cs @@ -0,0 +1,8 @@ +namespace LogExpert.Core.Entities; + +public class ReloadMemento +{ + public int CurrentLine { get; set; } + + public int FirstDisplayedLine { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/RowHeightEntry.cs b/src/LogExpert.Core/Entities/RowHeightEntry.cs new file mode 100644 index 00000000..00c79bc7 --- /dev/null +++ b/src/LogExpert.Core/Entities/RowHeightEntry.cs @@ -0,0 +1,28 @@ +namespace LogExpert.Core.Entities; + +public class RowHeightEntry +{ + #region cTor + + public RowHeightEntry() + { + LineNum = 0; + Height = 0; + } + + public RowHeightEntry(int lineNum, int height) + { + LineNum = lineNum; + Height = height; + } + + #endregion + + #region Properties + + public int LineNum { get; set; } + + public int Height { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Entities/SearchParams.cs b/src/LogExpert.Core/Entities/SearchParams.cs new file mode 100644 index 00000000..2a5167db --- /dev/null +++ b/src/LogExpert.Core/Entities/SearchParams.cs @@ -0,0 +1,24 @@ +namespace LogExpert.Entities; + +[Serializable] +public class SearchParams +{ + public int CurrentLine { get; set; } + + public List HistoryList { get; set; } = []; + + public bool IsCaseSensitive { get; set; } + + public bool IsFindNext { get; set; } + + public bool IsForward { get; set; } = true; + + public bool IsFromTop { get; set; } + + public bool IsRegex { get; set; } + + public string SearchText { get; set; } = string.Empty; + + [field: NonSerialized] + public bool IsShiftF3Pressed { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Enums/DragOrientationsEnum.cs b/src/LogExpert.Core/Enums/DragOrientationsEnum.cs new file mode 100644 index 00000000..fb6465c4 --- /dev/null +++ b/src/LogExpert.Core/Enums/DragOrientationsEnum.cs @@ -0,0 +1,8 @@ +namespace LogExpert.Core.Enums; + +public enum DragOrientationsEnum +{ + Horizontal, + Vertical, + InvertedVertical +} diff --git a/src/LogExpert.Core/Enums/ProjectLoadDlgResult.cs b/src/LogExpert.Core/Enums/ProjectLoadDlgResult.cs new file mode 100644 index 00000000..c32b6c2c --- /dev/null +++ b/src/LogExpert.Core/Enums/ProjectLoadDlgResult.cs @@ -0,0 +1,9 @@ +namespace LogExpert.Core.Enums; + +public enum ProjectLoadDlgResult +{ + Cancel, + CloseTabs, + NewWindow, + IgnoreLayout +} \ No newline at end of file diff --git a/src/LogExpert.Core/Enums/WindowTypes.cs b/src/LogExpert.Core/Enums/WindowTypes.cs new file mode 100644 index 00000000..6a726c9c --- /dev/null +++ b/src/LogExpert.Core/Enums/WindowTypes.cs @@ -0,0 +1,7 @@ +namespace LogExpert.Core.Enums; + +public enum WindowTypes +{ + BookmarkWindow, + LogWindow, +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs new file mode 100644 index 00000000..d2156111 --- /dev/null +++ b/src/LogExpert.Core/EventArguments/BookmarkEventArgs.cs @@ -0,0 +1,12 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.Core.EventArguments; + +public class BookmarkEventArgs (Bookmark bookmark) : EventArgs +{ + #region Properties + + public Bookmark Bookmark { get; } = bookmark; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/ColumnizerEventArgs.cs b/src/LogExpert.Core/EventArguments/ColumnizerEventArgs.cs new file mode 100644 index 00000000..9e8bb006 --- /dev/null +++ b/src/LogExpert.Core/EventArguments/ColumnizerEventArgs.cs @@ -0,0 +1,10 @@ +namespace LogExpert.Core.EventArguments; + +public class ColumnizerEventArgs(ILogLineColumnizer columnizer) : System.EventArgs +{ + #region Properties + + public ILogLineColumnizer Columnizer { get; } = columnizer; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/ConfigChangedEventArgs.cs b/src/LogExpert.Core/EventArguments/ConfigChangedEventArgs.cs new file mode 100644 index 00000000..c931dccf --- /dev/null +++ b/src/LogExpert.Core/EventArguments/ConfigChangedEventArgs.cs @@ -0,0 +1,12 @@ +using LogExpert.Core.Config; + +namespace LogExpert.Core.EventArguments; + +public class ConfigChangedEventArgs(SettingsFlags changeFlags) : System.EventArgs +{ + #region Properties + + public SettingsFlags Flags { get; } = changeFlags; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/ContextMenuPluginEventArgs.cs b/src/LogExpert.Core/EventArguments/ContextMenuPluginEventArgs.cs new file mode 100644 index 00000000..76d129cc --- /dev/null +++ b/src/LogExpert.Core/EventArguments/ContextMenuPluginEventArgs.cs @@ -0,0 +1,18 @@ +namespace LogExpert.Core.EventArguments; + +public class ContextMenuPluginEventArgs(IContextMenuEntry entry, IList logLines, ILogLineColumnizer columnizer, + ILogExpertCallback callback) : System.EventArgs +{ + + #region Properties + + public IContextMenuEntry Entry { get; } = entry; + + public IList LogLines { get; } = logLines; + + public ILogLineColumnizer Columnizer { get; } = columnizer; + + public ILogExpertCallback Callback { get; } = callback; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/CurrentHighlightGroupChangedEventArgs.cs b/src/LogExpert.Core/EventArguments/CurrentHighlightGroupChangedEventArgs.cs new file mode 100644 index 00000000..7633e06c --- /dev/null +++ b/src/LogExpert.Core/EventArguments/CurrentHighlightGroupChangedEventArgs.cs @@ -0,0 +1,15 @@ +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; + +namespace LogExpert.Core.EventArguments; + +public class CurrentHighlightGroupChangedEventArgs(ILogWindow logWindow, HighlightGroup currentGroup) +{ + #region Properties + + public ILogWindow LogWindow { get; } = logWindow; + + public HighlightGroup CurrentGroup { get; } = currentGroup; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/FilterListChangedEventArgs.cs b/src/LogExpert.Core/EventArguments/FilterListChangedEventArgs.cs new file mode 100644 index 00000000..0512997a --- /dev/null +++ b/src/LogExpert.Core/EventArguments/FilterListChangedEventArgs.cs @@ -0,0 +1,10 @@ + +using LogExpert.Core.Interface; + +namespace LogExpert.Core.EventArguments; + +//TODO: Move to UI +public class FilterListChangedEventArgs (ILogWindow logWindow) : EventArgs +{ + public ILogWindow LogWindow { get; } = logWindow; +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/GuiStateArgs.cs b/src/LogExpert.Core/EventArguments/GuiStateArgs.cs new file mode 100644 index 00000000..82ccc963 --- /dev/null +++ b/src/LogExpert.Core/EventArguments/GuiStateArgs.cs @@ -0,0 +1,44 @@ +using System.Text; + +namespace LogExpert.Core.EventArguments; + +public class GuiStateArgs : System.EventArgs +{ + #region Properties + + public bool TimeshiftEnabled { get; set; } + + public bool FollowTail { get; set; } + + public bool MenuEnabled { get; set; } = true; + + public string TimeshiftText { get; set; } = string.Empty; + + public bool TimeshiftPossible { get; set; } + + public bool MultiFileEnabled { get; set; } = true; + + public bool FilterEnabled { get; set; } = true; + + public bool CellSelectMode { get; set; } + + public Encoding CurrentEncoding { get; set; } + + public DateTime Timestamp { get; set; } + + public DateTime MinTimestamp { get; set; } + + public DateTime MaxTimestamp { get; set; } + + public bool ShowBookmarkBubbles { get; set; } + + public bool IsMultiFileActive { get; set; } + + public bool ShowHiddenLines { get; set; } = true; + + public string HighlightGroupName { get; set; } = string.Empty; + + public bool ColumnFinderVisible { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/LoadFileEventArgs.cs b/src/LogExpert.Core/EventArguments/LoadFileEventArgs.cs new file mode 100644 index 00000000..b7daa31a --- /dev/null +++ b/src/LogExpert.Core/EventArguments/LoadFileEventArgs.cs @@ -0,0 +1,3 @@ +namespace LogExpert.Core.EventArguments; + +public record LoadFileEventArgs(string FileName, long ReadPos, bool Finished, long FileSize, bool NewFile); \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/OverlayEventArgs.cs b/src/LogExpert.Core/EventArguments/OverlayEventArgs.cs new file mode 100644 index 00000000..91faf48b --- /dev/null +++ b/src/LogExpert.Core/EventArguments/OverlayEventArgs.cs @@ -0,0 +1,12 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.Core.EventArguments; + +public class OverlayEventArgs(BookmarkOverlay overlay) : System.EventArgs +{ + #region Properties + + public BookmarkOverlay BookmarkOverlay { get; set; } = overlay; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/PatternArgs.cs b/src/LogExpert.Core/EventArguments/PatternArgs.cs new file mode 100644 index 00000000..3cfe2e69 --- /dev/null +++ b/src/LogExpert.Core/EventArguments/PatternArgs.cs @@ -0,0 +1,20 @@ +namespace LogExpert.Core.EventArguments; + +public class PatternArgs +{ + #region Properties + + public int EndLine { get; set; } + + public int Fuzzy { get; set; } = 6; + + public int MaxDiffInBlock { get; set; } = 5; + + public int MaxMisses { get; set; } = 5; + + public int MinWeight { get; set; } = 15; + + public int StartLine { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/ProgressEventArgs.cs b/src/LogExpert.Core/EventArguments/ProgressEventArgs.cs new file mode 100644 index 00000000..58db9efb --- /dev/null +++ b/src/LogExpert.Core/EventArguments/ProgressEventArgs.cs @@ -0,0 +1,16 @@ +namespace LogExpert.Core.EventArguments; + +public class ProgressEventArgs : System.EventArgs +{ + #region Properties + + public int Value { get; set; } + + public int MinValue { get; set; } + + public int MaxValue { get; set; } + + public bool Visible { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/SelectLineEventArgs.cs b/src/LogExpert.Core/EventArguments/SelectLineEventArgs.cs new file mode 100644 index 00000000..ac94ccfc --- /dev/null +++ b/src/LogExpert.Core/EventArguments/SelectLineEventArgs.cs @@ -0,0 +1,10 @@ +namespace LogExpert.Core.EventArguments; + +public class SelectLineEventArgs(int line) : System.EventArgs +{ + #region Properties + + public int Line { get; } = line; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/StatusEventArgs.cs b/src/LogExpert.Core/EventArguments/StatusEventArgs.cs new file mode 100644 index 00000000..21786a3b --- /dev/null +++ b/src/LogExpert.Core/EventArguments/StatusEventArgs.cs @@ -0,0 +1,32 @@ +namespace LogExpert.Core.EventArguments; + +public class StatusLineEventArgs : System.EventArgs +{ + #region Properties + + public long FileSize { get; set; } + + public string StatusText { get; set; } = string.Empty; + + public int LineCount { get; set; } + + public int CurrentLineNum { get; set; } + + #endregion + + #region Public methods + + public StatusLineEventArgs Clone() + { + StatusLineEventArgs e = new() + { + StatusText = StatusText, + CurrentLineNum = CurrentLineNum, + LineCount = LineCount, + FileSize = FileSize + }; + return e; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/EventArguments/SyncModeEventArgs.cs b/src/LogExpert.Core/EventArguments/SyncModeEventArgs.cs new file mode 100644 index 00000000..97378d4c --- /dev/null +++ b/src/LogExpert.Core/EventArguments/SyncModeEventArgs.cs @@ -0,0 +1,10 @@ +namespace LogExpert.Core.EventArguments; + +public class SyncModeEventArgs(bool isSynced) : System.EventArgs +{ + #region Properties + + public bool IsTimeSynced { get; } = isSynced; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Extensions/IEnumerable.cs b/src/LogExpert.Core/Extensions/IEnumerable.cs new file mode 100644 index 00000000..d8357fb4 --- /dev/null +++ b/src/LogExpert.Core/Extensions/IEnumerable.cs @@ -0,0 +1,24 @@ +namespace LogExpert.Core.Extensions; + +public static class Extensions +{ + public static bool IsEmpty(this IEnumerable collection) + { + if (collection == null) + { + return true; + } + + return !collection.Any(); + } + + public static bool IsEmpty(this IList list) + { + if (list == null) + { + return true; + } + + return list.Count == 0; + } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/IBackgroundProcessCancelHandler.cs b/src/LogExpert.Core/Interface/IBackgroundProcessCancelHandler.cs new file mode 100644 index 00000000..b1a0ce37 --- /dev/null +++ b/src/LogExpert.Core/Interface/IBackgroundProcessCancelHandler.cs @@ -0,0 +1,17 @@ +namespace LogExpert.Core.Interface; + +/// +/// Interface which can register at the LogWindow to be informed of pressing ESC. +/// Used e.g. for cancelling a filter. +/// +public interface IBackgroundProcessCancelHandler +{ + #region Public methods + + /// + /// Called when ESC was pressed. + /// + void EscapePressed(); + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/IBookmarkData.cs b/src/LogExpert.Core/Interface/IBookmarkData.cs new file mode 100644 index 00000000..7abcedb7 --- /dev/null +++ b/src/LogExpert.Core/Interface/IBookmarkData.cs @@ -0,0 +1,26 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Interface; + +public interface IBookmarkData +{ + #region Properties + + BookmarkCollection Bookmarks { get; } + + #endregion + + #region Public methods + + void ToggleBookmark (int lineNum); + + bool IsBookmarkAtLine (int lineNum); + + int GetBookmarkIndexForLine (int lineNum); + + Bookmark GetBookmarkForLine (int lineNum); + + void SetBookmarks (SortedList bookmarkList); + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/IBookmarkView.cs b/src/LogExpert.Core/Interface/IBookmarkView.cs new file mode 100644 index 00000000..963c7c41 --- /dev/null +++ b/src/LogExpert.Core/Interface/IBookmarkView.cs @@ -0,0 +1,28 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Interface; + +/// +/// To be implemented by the bookmark window. Will be informed from LogWindow about changes in bookmarks. +/// +public interface IBookmarkView +{ + #region Properties + + //TODO: After all refactoring is done, take care of this warning. + bool LineColumnVisible { set; } + + #endregion + + #region Public methods + + void UpdateView (); + + void BookmarkTextChanged (Bookmark bookmark); + + void SelectBookmark (int lineNum); + + void SetBookmarkData (IBookmarkData bookmarkData); + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/IConfigManager.cs b/src/LogExpert.Core/Interface/IConfigManager.cs new file mode 100644 index 00000000..93a079dd --- /dev/null +++ b/src/LogExpert.Core/Interface/IConfigManager.cs @@ -0,0 +1,30 @@ +using LogExpert.Core.Config; +using LogExpert.Core.EventArguments; + +namespace LogExpert.Core.Interface; + +//TODO: Add documentation +public interface IConfigManager +{ + Settings Settings { get; } + + string PortableModeDir { get; } + + string ConfigDir { get; } + + IConfigManager Instance { get; } + + string PortableModeSettingsFileName { get; } + + void Export (FileInfo fileInfo, SettingsFlags highlightSettings); + + void Export (FileInfo fileInfo); + + void Import (FileInfo fileInfo, ExportImportFlags importFlags); + + void ImportHighlightSettings (FileInfo fileInfo, ExportImportFlags importFlags); + + event EventHandler ConfigChanged; //TODO: All handlers that are public shoulld be in Core + + void Save (SettingsFlags flags); +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/IFileViewContext.cs b/src/LogExpert.Core/Interface/IFileViewContext.cs new file mode 100644 index 00000000..15ae41b2 --- /dev/null +++ b/src/LogExpert.Core/Interface/IFileViewContext.cs @@ -0,0 +1,9 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.Core.Interface; + +public interface IFileViewContext +{ + ILogView LogView { get; } + ILogPaintContext LogPaintContext { get; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/ILogExpertProxy.cs b/src/LogExpert.Core/Interface/ILogExpertProxy.cs new file mode 100644 index 00000000..be0ed347 --- /dev/null +++ b/src/LogExpert.Core/Interface/ILogExpertProxy.cs @@ -0,0 +1,37 @@ +namespace LogExpert.Core.Interface; + +public interface ILogExpertProxy +{ + #region Public methods + + /// + /// Load the given files into the existing window. + /// + /// + void LoadFiles(string[] fileNames); + + /// + /// Open a new LogExpert window and load the given files. + /// + /// + void NewWindow(string[] fileNames); + + /// + /// load given files into the locked window or open a new window if no window is locked. + /// + /// + void NewWindowOrLockedWindow(string[] fileNames); + + + /// + /// Called from LogTabWindow when the window is about to be closed. + /// + /// + void WindowClosed(ILogTabWindow logWin); + + int GetLogWindowCount(); + + #endregion + + //void BroadcastSettingsChanged(Object cookie); +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/ILogPaintContext.cs b/src/LogExpert.Core/Interface/ILogPaintContext.cs new file mode 100644 index 00000000..2cf7ad03 --- /dev/null +++ b/src/LogExpert.Core/Interface/ILogPaintContext.cs @@ -0,0 +1,5 @@ +namespace LogExpert.Core.Interface; + +public interface ILogPaintContext +{ +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/ILogStreamReader.cs b/src/LogExpert.Core/Interface/ILogStreamReader.cs new file mode 100644 index 00000000..cfe4af05 --- /dev/null +++ b/src/LogExpert.Core/Interface/ILogStreamReader.cs @@ -0,0 +1,23 @@ +using System.Text; + +namespace LogExpert.Core.Interface; + +public interface ILogStreamReader : IDisposable +{ + #region Properties + + long Position { get; set; } + + bool IsBufferComplete { get; } + + Encoding Encoding { get; } + + #endregion + + #region Public methods + + int ReadChar(); + string ReadLine(); + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/ILogTabWindow.cs b/src/LogExpert.Core/Interface/ILogTabWindow.cs new file mode 100644 index 00000000..822d464d --- /dev/null +++ b/src/LogExpert.Core/Interface/ILogTabWindow.cs @@ -0,0 +1,14 @@ +namespace LogExpert.Core.Interface; + +//TODO: Add documentation +public interface ILogTabWindow +{ + ILogExpertProxy LogExpertProxy { get; set; } + bool IsDisposed { get; } + + void Activate (); + object Invoke (Delegate method, params object?[]? objects); + void LoadFiles (string[] fileNames); + void SetForeground (); + void Show (); +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/ILogView.cs b/src/LogExpert.Core/Interface/ILogView.cs new file mode 100644 index 00000000..d56bc759 --- /dev/null +++ b/src/LogExpert.Core/Interface/ILogView.cs @@ -0,0 +1,23 @@ +namespace LogExpert.Core.Interface; + +/// +/// Methods to control the LogWindow from other views. +/// +public interface ILogView +{ + #region Properties + + ILogLineColumnizer CurrentColumnizer { get; } + string FileName { get; } + + #endregion + + #region Public methods + + void SelectLogLine(int lineNumber); + void SelectAndEnsureVisible(int line, bool triggerSyncCall); + void RefreshLogView(); + void DeleteBookmarks(List lineNumList); + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/ILogWindow.cs b/src/LogExpert.Core/Interface/ILogWindow.cs new file mode 100644 index 00000000..c165b347 --- /dev/null +++ b/src/LogExpert.Core/Interface/ILogWindow.cs @@ -0,0 +1,43 @@ +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Classes.Persister; + +namespace LogExpert.Core.Interface; + +//TODO: Add documentation +public interface ILogWindow +{ + string GetCurrentFileName (int lineNum); + + ILogLine GetLine (int lineNum); + + ILogLine GetLogLineWithWait (int lineNum); + + //TODO Find a way to not use a referenced int (https://github.com/LogExperts/LogExpert/issues/404) + DateTime GetTimestampForLineForward (ref int lineNum, bool roundToSeconds); + + //TODO Find a way to not use a referenced int (https://github.com/LogExperts/LogExpert/issues/404) + DateTime GetTimestampForLine (ref int lastLineNum, bool roundToSeconds); + + int FindTimestampLineInternal (int lineNum, int rangeStart, int rangeEnd, DateTime timestamp, bool roundToSeconds); + + void SelectLine (int lineNum, bool triggerSyncCall, bool shouldScroll); + + PersistenceData GetPersistenceData (); + + void AddTempFileTab (string fileName, string title); + + void WritePipeTab (IList lineEntryList, string title); + + void Activate (); + + LogfileReader LogFileReader { get; } + + string Text { get; } + + string FileName { get; } + + //event EventHandler FileSizeChanged; //TODO: All handlers should be moved to Core + + //event EventHandler TailFollowed; + //LogExpert.UI.Controls.LogTabWindow.LogTabWindow.LogWindowData Tag { get; } +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/IPluginRegistry.cs b/src/LogExpert.Core/Interface/IPluginRegistry.cs new file mode 100644 index 00000000..bca099ff --- /dev/null +++ b/src/LogExpert.Core/Interface/IPluginRegistry.cs @@ -0,0 +1,9 @@ +namespace LogExpert.Core.Interface; + +//TODO: Add documentation +public interface IPluginRegistry +{ + IList RegisteredColumnizers { get; } + + IFileSystemPlugin FindFileSystemForUri (string fileNameOrUri); +} \ No newline at end of file diff --git a/src/LogExpert.Core/Interface/ISharedToolWindow.cs b/src/LogExpert.Core/Interface/ISharedToolWindow.cs new file mode 100644 index 00000000..6c091cae --- /dev/null +++ b/src/LogExpert.Core/Interface/ISharedToolWindow.cs @@ -0,0 +1,30 @@ +using LogExpert.Core.Config; + +namespace LogExpert.Core.Interface; + +/// +/// Interface to be implemented by tools windows that are shared across multiple log files. +/// The implementor will be called whenever the current log file changes. So it can draw new content +/// according to the current active log file. +/// +public interface ISharedToolWindow +{ + #region Public methods + + /// + /// Called when a file becomes the active file (e.g. when user selects a tab). + /// + /// + void SetCurrentFile (IFileViewContext ctx); + + /// + /// Called whenever the current file has been changed. + /// + void FileChanged (); + + void SetColumnizer (ILogLineColumnizer columnizer); + + void PreferencesChanged (string fontName, float fontSize, bool setLastColumnWidth, int lastColumnWidth, SettingsFlags flags); + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.Core/LogExpert.Core.csproj b/src/LogExpert.Core/LogExpert.Core.csproj new file mode 100644 index 00000000..094d3861 --- /dev/null +++ b/src/LogExpert.Core/LogExpert.Core.csproj @@ -0,0 +1,18 @@ + + + + net8.0 + true + + + + + + + + + + + + + diff --git a/src/LogExpert.Core/Properties/AssemblyInfo.cs b/src/LogExpert.Core/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..1af21449 --- /dev/null +++ b/src/LogExpert.Core/Properties/AssemblyInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("LogExpert.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100619e9beea345a3bb5e15f55b29ddf40d96e9bb473ae58304fc63dfb3e9c94d8944bb7e45324ee0bef3e345dccba79b0bf64b85a128a7f261861899add639218ddaeb2acc6fcc746d6acb5bb212d375a0967756af192cfdb6cf0bff666a0fe535600abda860d3eafaff4ef1c9b5710181f72d996ca9c29ed64bae4a5fd916dea5")] \ No newline at end of file diff --git a/src/LogExpert.Core/Structs/ActEntry.cs b/src/LogExpert.Core/Structs/ActEntry.cs new file mode 100644 index 00000000..1328fc1a --- /dev/null +++ b/src/LogExpert.Core/Structs/ActEntry.cs @@ -0,0 +1,8 @@ +namespace LogExpert.Core.Structs; + +public struct ActEntry +{ + public string Name { get; set; } + + public IKeywordAction Plugin { get; set; } +} \ No newline at end of file diff --git a/src/LogExpert.Resources/LogExpert.Resources.csproj b/src/LogExpert.Resources/LogExpert.Resources.csproj new file mode 100644 index 00000000..553388a5 --- /dev/null +++ b/src/LogExpert.Resources/LogExpert.Resources.csproj @@ -0,0 +1,40 @@ + + + + net8.0 + + + + + PreserveNewest + + + + + + + + + + + + + + + + + + True + True + Resources.resx + + + + + + PublicResXFileCodeGenerator + Resources.Designer.cs + + + + diff --git a/src/LogExpert/Properties/Resources.Designer.cs b/src/LogExpert.Resources/Resources.Designer.cs similarity index 69% rename from src/LogExpert/Properties/Resources.Designer.cs rename to src/LogExpert.Resources/Resources.Designer.cs index b81d26da..fbcf8bd2 100644 --- a/src/LogExpert/Properties/Resources.Designer.cs +++ b/src/LogExpert.Resources/Resources.Designer.cs @@ -1,413 +1,343 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace LogExpert.Properties { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LogExpert.Properties.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Add { - get { - object obj = ResourceManager.GetObject("Add", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Arrow_menu_close { - get { - object obj = ResourceManager.GetObject("Arrow_menu_close", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Arrow_menu_open { - get { - object obj = ResourceManager.GetObject("Arrow_menu_open", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ArrowDown { - get { - object obj = ResourceManager.GetObject("ArrowDown", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ArrowLeft { - get { - object obj = ResourceManager.GetObject("ArrowLeft", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ArrowRight { - get { - object obj = ResourceManager.GetObject("ArrowRight", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap ArrowUp { - get { - object obj = ResourceManager.GetObject("ArrowUp", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Bookmark_add { - get { - object obj = ResourceManager.GetObject("Bookmark_add", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Bookmark_added { - get { - object obj = ResourceManager.GetObject("Bookmark_added", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap bookmark_bubbles { - get { - object obj = ResourceManager.GetObject("bookmark_bubbles", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Bookmark_manager { - get { - object obj = ResourceManager.GetObject("Bookmark_manager", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Bookmark_remove { - get { - object obj = ResourceManager.GetObject("Bookmark_remove", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Bookmarks { - get { - object obj = ResourceManager.GetObject("Bookmarks", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Check_circle { - get { - object obj = ResourceManager.GetObject("Check_circle", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Close { - get { - object obj = ResourceManager.GetObject("Close", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Deceased { - get { - object obj = ResourceManager.GetObject("Deceased", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Delete { - get { - object obj = ResourceManager.GetObject("Delete", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Exit { - get { - object obj = ResourceManager.GetObject("Exit", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Favorite { - get { - object obj = ResourceManager.GetObject("Favorite", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap File_open { - get { - object obj = ResourceManager.GetObject("File_open", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Filter { - get { - object obj = ResourceManager.GetObject("Filter", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Folder_open { - get { - object obj = ResourceManager.GetObject("Folder_open", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). - /// - internal static System.Drawing.Icon Icon1 { - get { - object obj = ResourceManager.GetObject("Icon1", resourceCulture); - return ((System.Drawing.Icon)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Icon similar to (Icon). - /// - internal static System.Drawing.Icon Icon2 { - get { - object obj = ResourceManager.GetObject("Icon2", resourceCulture); - return ((System.Drawing.Icon)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Log_Icon { - get { - object obj = ResourceManager.GetObject("Log_Icon", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Log_Icon_small { - get { - object obj = ResourceManager.GetObject("Log_Icon_small", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap LogExpert { - get { - object obj = ResourceManager.GetObject("LogExpert", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap LogExpert_Icon { - get { - object obj = ResourceManager.GetObject("LogExpert_Icon", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap LogExpert_Logo { - get { - object obj = ResourceManager.GetObject("LogExpert-Logo", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap LogLover { - get { - object obj = ResourceManager.GetObject("LogLover", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Pro_Filter { - get { - object obj = ResourceManager.GetObject("Pro_Filter", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Restart_alt { - get { - object obj = ResourceManager.GetObject("Restart_alt", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Search { - get { - object obj = ResourceManager.GetObject("Search", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Settings { - get { - object obj = ResourceManager.GetObject("Settings", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap Star { - get { - object obj = ResourceManager.GetObject("Star", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - } -} +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace LogExpert { + using System; + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + public class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LogExpert.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + public static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Add { + get { + object obj = ResourceManager.GetObject("Add", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Arrow_menu_close { + get { + object obj = ResourceManager.GetObject("Arrow_menu_close", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Arrow_menu_open { + get { + object obj = ResourceManager.GetObject("Arrow_menu_open", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap ArrowDown { + get { + object obj = ResourceManager.GetObject("ArrowDown", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap ArrowLeft { + get { + object obj = ResourceManager.GetObject("ArrowLeft", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap ArrowRight { + get { + object obj = ResourceManager.GetObject("ArrowRight", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap ArrowUp { + get { + object obj = ResourceManager.GetObject("ArrowUp", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Bookmark_add { + get { + object obj = ResourceManager.GetObject("Bookmark_add", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Bookmark_added { + get { + object obj = ResourceManager.GetObject("Bookmark_added", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap bookmark_bubbles { + get { + object obj = ResourceManager.GetObject("bookmark_bubbles", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Bookmark_manager { + get { + object obj = ResourceManager.GetObject("Bookmark_manager", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Bookmark_remove { + get { + object obj = ResourceManager.GetObject("Bookmark_remove", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Bookmarks { + get { + object obj = ResourceManager.GetObject("Bookmarks", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Check_circle { + get { + object obj = ResourceManager.GetObject("Check_circle", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Close { + get { + object obj = ResourceManager.GetObject("Close", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Deceased { + get { + object obj = ResourceManager.GetObject("Deceased", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Delete { + get { + object obj = ResourceManager.GetObject("Delete", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Exit { + get { + object obj = ResourceManager.GetObject("Exit", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Favorite { + get { + object obj = ResourceManager.GetObject("Favorite", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap File_open { + get { + object obj = ResourceManager.GetObject("File_open", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Filter { + get { + object obj = ResourceManager.GetObject("Filter", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Folder_open { + get { + object obj = ResourceManager.GetObject("Folder_open", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap LogLover { + get { + object obj = ResourceManager.GetObject("LogLover", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Pro_Filter { + get { + object obj = ResourceManager.GetObject("Pro_Filter", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Restart_alt { + get { + object obj = ResourceManager.GetObject("Restart_alt", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Search { + get { + object obj = ResourceManager.GetObject("Search", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Settings { + get { + object obj = ResourceManager.GetObject("Settings", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + + /// + /// Looks up a localized resource of type System.Drawing.Bitmap. + /// + public static System.Drawing.Bitmap Star { + get { + object obj = ResourceManager.GetObject("Star", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/src/LogExpert/Properties/Resources.resx b/src/LogExpert.Resources/Resources.resx similarity index 58% rename from src/LogExpert/Properties/Resources.resx rename to src/LogExpert.Resources/Resources.resx index 2085cd03..e9b5affe 100644 --- a/src/LogExpert/Properties/Resources.resx +++ b/src/LogExpert.Resources/Resources.resx @@ -1,252 +1,211 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - ..\Resources\LogExpert-Logo.png;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Pro_Filter.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\LogExpert.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\LogLover.gif;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Icon1.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Icon2.ico;System.Drawing.Icon, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\LogExpert-Icon.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Log_Icon.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\Log_Icon_small.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - ..\Resources\PNG\48\bookmark_bubbles.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Bookmark_Bubbles - - - ..\Resources\PNG\48\Add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Add - - - ..\Resources\PNG\48\ArrowDown.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - ArrowDown - - - ..\Resources\PNG\48\ArrowLeft.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - ArrowLeft - - - ..\Resources\PNG\48\ArrowRight.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - ArrowRight - - - ..\Resources\PNG\48\ArrowUp.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - ArrowUp - - - ..\Resources\PNG\48\Bookmark_add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Bookmark_add - - - ..\Resources\PNG\48\Bookmark_added.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Bookmark_added - - - ..\Resources\PNG\48\Bookmark_manager.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Bookmark_manager - - - ..\Resources\PNG\48\Bookmark_remove.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Bookmark_remove - - - ..\Resources\PNG\48\Bookmarks.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Bookmarks - - - ..\Resources\PNG\48\Delete.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Delete - - - ..\Resources\PNG\48\Exit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Exit - - - ..\Resources\PNG\48\Favorite.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Favorite - - - ..\Resources\PNG\48\File_open.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - File_open - - - ..\Resources\PNG\48\Filter.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Filter - - - ..\Resources\PNG\48\Folder_open.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Folder_open - - - ..\Resources\PNG\48\Restart_alt.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Restart_alt - - - ..\Resources\PNG\48\Search.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Search - - - ..\Resources\PNG\48\Settings.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Settings - - - ..\Resources\PNG\48\Star.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Star - - - ..\Resources\PNG\48\Arrow_menu_close.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Arrow_menu_close - - - ..\Resources\PNG\48\Arrow_menu_open.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Arrow_menu_open - - - ..\Resources\PNG\48\Close.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Close - - - ..\Resources\PNG\48\Deceased.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Deceased - - - ..\Resources\PNG\48\Check_circle.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - Check_circle - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + images\png\48\Add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + Add + + + images\png\48\ArrowDown.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + ArrowDown + + + images\png\48\ArrowLeft.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\ArrowRight.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\ArrowUp.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Arrow_menu_close.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + Arrow_menu_close + + + images\png\48\Arrow_menu_open.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + Arrow_menu_open + + + images\png\48\Bookmarks.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Bookmark_add.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Bookmark_added.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\bookmark_bubbles.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Bookmark_manager.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Bookmark_remove.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Check_circle.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Close.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Deceased.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Delete.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Exit.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Favorite.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\File_open.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Filter.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Folder_open.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\gif\LogLover.gif;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + Logexpert Logo + + + images\bmp\Pro_Filter.bmp;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Restart_alt.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Search.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + + + images\png\48\Settings.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + Settings Logo + + + images\png\48\Star.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + \ No newline at end of file diff --git a/src/LogExpert/Resources/LogExpert.bmp b/src/LogExpert.Resources/images/bmp/LogExpert.bmp similarity index 100% rename from src/LogExpert/Resources/LogExpert.bmp rename to src/LogExpert.Resources/images/bmp/LogExpert.bmp diff --git a/src/LogExpert/Resources/Pro_Filter.bmp b/src/LogExpert.Resources/images/bmp/Pro_Filter.bmp similarity index 100% rename from src/LogExpert/Resources/Pro_Filter.bmp rename to src/LogExpert.Resources/images/bmp/Pro_Filter.bmp diff --git a/src/LogExpert/Resources/LogExpert-Icon.gif b/src/LogExpert.Resources/images/gif/LogExpert-Icon.gif similarity index 100% rename from src/LogExpert/Resources/LogExpert-Icon.gif rename to src/LogExpert.Resources/images/gif/LogExpert-Icon.gif diff --git a/src/LogExpert/Resources/LogLover.gif b/src/LogExpert.Resources/images/gif/LogLover.gif similarity index 100% rename from src/LogExpert/Resources/LogLover.gif rename to src/LogExpert.Resources/images/gif/LogLover.gif diff --git a/src/LogExpert/Resources/Icon1.ico b/src/LogExpert.Resources/images/icons/Icon1.ico similarity index 100% rename from src/LogExpert/Resources/Icon1.ico rename to src/LogExpert.Resources/images/icons/Icon1.ico diff --git a/src/LogExpert/Resources/Icon2.ico b/src/LogExpert.Resources/images/icons/Icon2.ico similarity index 100% rename from src/LogExpert/Resources/Icon2.ico rename to src/LogExpert.Resources/images/icons/Icon2.ico diff --git a/src/LogExpert/Resources/bubble.ico b/src/LogExpert.Resources/images/icons/bubble.ico similarity index 100% rename from src/LogExpert/Resources/bubble.ico rename to src/LogExpert.Resources/images/icons/bubble.ico diff --git a/src/LogExpert/Resources/logexpert.ico b/src/LogExpert.Resources/images/icons/logexpert.ico similarity index 100% rename from src/LogExpert/Resources/logexpert.ico rename to src/LogExpert.Resources/images/icons/logexpert.ico diff --git a/src/LogExpert/Resources/PNG/48/Add.png b/src/LogExpert.Resources/images/png/48/Add.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Add.png rename to src/LogExpert.Resources/images/png/48/Add.png diff --git a/src/LogExpert/Resources/PNG/48/ArrowDown.png b/src/LogExpert.Resources/images/png/48/ArrowDown.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/ArrowDown.png rename to src/LogExpert.Resources/images/png/48/ArrowDown.png diff --git a/src/LogExpert/Resources/PNG/48/ArrowLeft.png b/src/LogExpert.Resources/images/png/48/ArrowLeft.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/ArrowLeft.png rename to src/LogExpert.Resources/images/png/48/ArrowLeft.png diff --git a/src/LogExpert/Resources/PNG/48/ArrowRight.png b/src/LogExpert.Resources/images/png/48/ArrowRight.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/ArrowRight.png rename to src/LogExpert.Resources/images/png/48/ArrowRight.png diff --git a/src/LogExpert/Resources/PNG/48/ArrowUp.png b/src/LogExpert.Resources/images/png/48/ArrowUp.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/ArrowUp.png rename to src/LogExpert.Resources/images/png/48/ArrowUp.png diff --git a/src/LogExpert/Resources/PNG/48/Arrow_menu_close.png b/src/LogExpert.Resources/images/png/48/Arrow_menu_close.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Arrow_menu_close.png rename to src/LogExpert.Resources/images/png/48/Arrow_menu_close.png diff --git a/src/LogExpert/Resources/PNG/48/Arrow_menu_open.png b/src/LogExpert.Resources/images/png/48/Arrow_menu_open.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Arrow_menu_open.png rename to src/LogExpert.Resources/images/png/48/Arrow_menu_open.png diff --git a/src/LogExpert/Resources/PNG/48/Bookmark_add.png b/src/LogExpert.Resources/images/png/48/Bookmark_add.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Bookmark_add.png rename to src/LogExpert.Resources/images/png/48/Bookmark_add.png diff --git a/src/LogExpert/Resources/PNG/48/Bookmark_added.png b/src/LogExpert.Resources/images/png/48/Bookmark_added.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Bookmark_added.png rename to src/LogExpert.Resources/images/png/48/Bookmark_added.png diff --git a/src/LogExpert/Resources/PNG/48/Bookmark_manager.png b/src/LogExpert.Resources/images/png/48/Bookmark_manager.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Bookmark_manager.png rename to src/LogExpert.Resources/images/png/48/Bookmark_manager.png diff --git a/src/LogExpert/Resources/PNG/48/Bookmark_remove.png b/src/LogExpert.Resources/images/png/48/Bookmark_remove.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Bookmark_remove.png rename to src/LogExpert.Resources/images/png/48/Bookmark_remove.png diff --git a/src/LogExpert/Resources/PNG/48/Bookmarks.png b/src/LogExpert.Resources/images/png/48/Bookmarks.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Bookmarks.png rename to src/LogExpert.Resources/images/png/48/Bookmarks.png diff --git a/src/LogExpert/Resources/PNG/48/Check_circle.png b/src/LogExpert.Resources/images/png/48/Check_circle.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Check_circle.png rename to src/LogExpert.Resources/images/png/48/Check_circle.png diff --git a/src/LogExpert/Resources/PNG/48/Close.png b/src/LogExpert.Resources/images/png/48/Close.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Close.png rename to src/LogExpert.Resources/images/png/48/Close.png diff --git a/src/LogExpert/Resources/PNG/48/Deceased.png b/src/LogExpert.Resources/images/png/48/Deceased.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Deceased.png rename to src/LogExpert.Resources/images/png/48/Deceased.png diff --git a/src/LogExpert/Resources/PNG/48/Delete.png b/src/LogExpert.Resources/images/png/48/Delete.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Delete.png rename to src/LogExpert.Resources/images/png/48/Delete.png diff --git a/src/LogExpert/Resources/PNG/48/Exit.png b/src/LogExpert.Resources/images/png/48/Exit.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Exit.png rename to src/LogExpert.Resources/images/png/48/Exit.png diff --git a/src/LogExpert/Resources/PNG/48/Favorite.png b/src/LogExpert.Resources/images/png/48/Favorite.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Favorite.png rename to src/LogExpert.Resources/images/png/48/Favorite.png diff --git a/src/LogExpert/Resources/PNG/48/File_open.png b/src/LogExpert.Resources/images/png/48/File_open.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/File_open.png rename to src/LogExpert.Resources/images/png/48/File_open.png diff --git a/src/LogExpert/Resources/PNG/48/Filter.png b/src/LogExpert.Resources/images/png/48/Filter.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Filter.png rename to src/LogExpert.Resources/images/png/48/Filter.png diff --git a/src/LogExpert/Resources/PNG/48/Folder_open.png b/src/LogExpert.Resources/images/png/48/Folder_open.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Folder_open.png rename to src/LogExpert.Resources/images/png/48/Folder_open.png diff --git a/src/LogExpert/Resources/PNG/48/Restart_alt.png b/src/LogExpert.Resources/images/png/48/Restart_alt.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Restart_alt.png rename to src/LogExpert.Resources/images/png/48/Restart_alt.png diff --git a/src/LogExpert/Resources/PNG/48/Search.png b/src/LogExpert.Resources/images/png/48/Search.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Search.png rename to src/LogExpert.Resources/images/png/48/Search.png diff --git a/src/LogExpert/Resources/PNG/48/Settings.png b/src/LogExpert.Resources/images/png/48/Settings.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Settings.png rename to src/LogExpert.Resources/images/png/48/Settings.png diff --git a/src/LogExpert/Resources/PNG/48/Star.png b/src/LogExpert.Resources/images/png/48/Star.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/Star.png rename to src/LogExpert.Resources/images/png/48/Star.png diff --git a/src/LogExpert/Resources/PNG/48/bookmark_bubbles.png b/src/LogExpert.Resources/images/png/48/bookmark_bubbles.png similarity index 100% rename from src/LogExpert/Resources/PNG/48/bookmark_bubbles.png rename to src/LogExpert.Resources/images/png/48/bookmark_bubbles.png diff --git a/src/LogExpert.Tests/BufferShiftTest.cs b/src/LogExpert.Tests/BufferShiftTest.cs index aeb13fe1..df3f027e 100644 --- a/src/LogExpert.Tests/BufferShiftTest.cs +++ b/src/LogExpert.Tests/BufferShiftTest.cs @@ -1,145 +1,154 @@ -using LogExpert.Classes.Log; -using LogExpert.Entities; +using System.Text; + +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; +using LogExpert.PluginRegistry.FileSystem; using NUnit.Framework; -using System.Collections.Generic; -using System.Linq; -using System.Text; +namespace LogExpert.Tests; -namespace LogExpert.Tests +[TestFixture] +internal class BufferShiftTest : RolloverHandlerTestBase { - [TestFixture] - internal class BufferShiftTest : RolloverHandlerTestBase + [TearDown] + public void TearDown () + { + Cleanup(); + } + + [OneTimeSetUp] + public void Boot () + { + Cleanup(); + } + + + [Test] + public void TestShiftBuffers1 () { - [TearDown] - public void TearDown() + var linesPerFile = 10; + MultiFileOptions options = new() { - Cleanup(); - } + MaxDayTry = 0, + FormatPattern = "*$J(.)" + }; + + LinkedList files = CreateTestFilesWithoutDate(); - [OneTimeSetUp] - public void Boot() + EncodingOptions encodingOptions = new() { - Cleanup(); - } + Encoding = Encoding.Default + }; + + PluginRegistry.PluginRegistry.Instance.Create(TestDirectory.FullName, 500); + LogfileReader reader = new(files.Last.Value, encodingOptions, true, 40, 50, options, PluginRegistry.PluginRegistry.Instance); + reader.ReadFiles(); + + IList lil = reader.GetLogFileInfoList(); + Assert.That(lil.Count, Is.EqualTo(files.Count)); + LinkedList.Enumerator enumerator = files.GetEnumerator(); + enumerator.MoveNext(); - [Test] - public void TestShiftBuffers1() + foreach (LogFileInfo li in lil.Cast()) { - int linesPerFile = 10; - MultiFileOptions options = new() - { - MaxDayTry = 0, - FormatPattern = "*$J(.)" - }; - LinkedList files = CreateTestFilesWithoutDate(); - EncodingOptions encodingOptions = new() - { - Encoding = Encoding.Default - }; - LogfileReader reader = new(files.Last.Value, encodingOptions, true, 40, 50, options); - reader.ReadFiles(); - - IList lil = reader.GetLogFileInfoList(); - Assert.That(lil.Count, Is.EqualTo(files.Count)); - - LinkedList.Enumerator enumerator = files.GetEnumerator(); + var fileName = enumerator.Current; + Assert.That(li.FullName, Is.EqualTo(fileName)); enumerator.MoveNext(); + } - foreach (LogFileInfo li in lil.Cast()) - { - string fileName = enumerator.Current; - Assert.That(li.FullName, Is.EqualTo(fileName)); - enumerator.MoveNext(); - } - int oldCount = lil.Count; + var oldCount = lil.Count; - // Simulate rollover - // - files = RolloverSimulation(files, "*$J(.)", false); + // Simulate rollover + // + files = RolloverSimulation(files, "*$J(.)", false); - // Simulate rollover detection - // - reader.ShiftBuffers(); + // Simulate rollover detection + // + reader.ShiftBuffers(); - lil = reader.GetLogFileInfoList(); - Assert.That(lil.Count, Is.EqualTo(oldCount + 1)); + lil = reader.GetLogFileInfoList(); - Assert.That(reader.LineCount, Is.EqualTo(linesPerFile * lil.Count)); + Assert.That(lil.Count, Is.EqualTo(oldCount + 1)); - // Check if rollover'd file names have been handled by LogfileReader - // - Assert.That(lil.Count, Is.EqualTo(files.Count)); - enumerator = files.GetEnumerator(); - enumerator.MoveNext(); - foreach (LogFileInfo li in lil) - { - string fileName = enumerator.Current; - Assert.That(li.FullName, Is.EqualTo(fileName)); - enumerator.MoveNext(); - } - - // Check if file buffers have correct files. Assuming here that one buffer fits for a - // complete file - // - enumerator = files.GetEnumerator(); + Assert.That(reader.LineCount, Is.EqualTo(linesPerFile * lil.Count)); + + // Check if rollover'd file names have been handled by LogfileReader + // + Assert.That(lil.Count, Is.EqualTo(files.Count)); + enumerator = files.GetEnumerator(); + enumerator.MoveNext(); + + foreach (LogFileInfo li in lil) + { + var fileName = enumerator.Current; + Assert.That(li.FullName, Is.EqualTo(fileName)); enumerator.MoveNext(); - IList logBuffers = reader.GetBufferList(); - int startLine = 0; - foreach (LogBuffer logBuffer in logBuffers) - { - Assert.That(enumerator.Current, Is.EqualTo(logBuffer.FileInfo.FullName)); - Assert.That(logBuffer.StartLine, Is.EqualTo(startLine)); - startLine += 10; - enumerator.MoveNext(); - } - - // Checking file content - // - enumerator = files.GetEnumerator(); + } + + // Check if file buffers have correct files. Assuming here that one buffer fits for a + // complete file + // + enumerator = files.GetEnumerator(); + enumerator.MoveNext(); + + IList logBuffers = reader.GetBufferList(); + var startLine = 0; + + foreach (LogBuffer logBuffer in logBuffers) + { + Assert.That(enumerator.Current, Is.EqualTo(logBuffer.FileInfo.FullName)); + Assert.That(logBuffer.StartLine, Is.EqualTo(startLine)); + startLine += 10; enumerator.MoveNext(); - enumerator.MoveNext(); // move to 2nd entry. The first file now contains 2nd file's content (because rollover) - logBuffers = reader.GetBufferList(); - int i; - for (i = 0; i < logBuffers.Count - 2; ++i) - { - LogBuffer logBuffer = logBuffers[i]; - ILogLine line = logBuffer.GetLineOfBlock(0); - Assert.That(line.FullLine.Contains(enumerator.Current)); - enumerator.MoveNext(); - } + } + + // Checking file content + // + enumerator = files.GetEnumerator(); + enumerator.MoveNext(); + enumerator.MoveNext(); // move to 2nd entry. The first file now contains 2nd file's content (because rollover) + logBuffers = reader.GetBufferList(); + int i; + + for (i = 0; i < logBuffers.Count - 2; ++i) + { + LogBuffer logBuffer = logBuffers[i]; + ILogLine line = logBuffer.GetLineOfBlock(0); + Assert.That(line.FullLine.Contains(enumerator.Current, StringComparison.Ordinal)); enumerator.MoveNext(); - // the last 2 files now contain the content of the previously watched file - for (; i < logBuffers.Count; ++i) - { - LogBuffer logBuffer = logBuffers[i]; - ILogLine line = logBuffer.GetLineOfBlock(0); - Assert.That(line.FullLine.Contains(enumerator.Current)); - } - - oldCount = lil.Count; - - // Simulate rollover again - now latest file will be deleted (simulates logger's rollover history limit) - // - files = RolloverSimulation(files, "*$J(.)", true); - - // Simulate rollover detection - // - reader.ShiftBuffers(); - lil = reader.GetLogFileInfoList(); - - Assert.That(lil.Count, Is.EqualTo(oldCount)); // same count because oldest file is deleted - Assert.That(lil.Count, Is.EqualTo(files.Count)); - Assert.That(reader.LineCount, Is.EqualTo(linesPerFile * lil.Count)); - - // Check first line to see if buffers are correct - // - ILogLine firstLine = reader.GetLogLine(0); - string[] names = new string[files.Count]; - files.CopyTo(names, 0); - Assert.That(firstLine.FullLine.Contains(names[2])); } + + enumerator.MoveNext(); + // the last 2 files now contain the content of the previously watched file + for (; i < logBuffers.Count; ++i) + { + LogBuffer logBuffer = logBuffers[i]; + ILogLine line = logBuffer.GetLineOfBlock(0); + Assert.That(line.FullLine.Contains(enumerator.Current, StringComparison.Ordinal)); + } + + oldCount = lil.Count; + + // Simulate rollover again - now latest file will be deleted (simulates logger's rollover history limit) + // + files = RolloverSimulation(files, "*$J(.)", true); + + // Simulate rollover detection + // + reader.ShiftBuffers(); + lil = reader.GetLogFileInfoList(); + + Assert.That(lil.Count, Is.EqualTo(oldCount)); // same count because oldest file is deleted + Assert.That(lil.Count, Is.EqualTo(files.Count)); + Assert.That(reader.LineCount, Is.EqualTo(linesPerFile * lil.Count)); + + // Check first line to see if buffers are correct + // + ILogLine firstLine = reader.GetLogLine(0); + var names = new string[files.Count]; + files.CopyTo(names, 0); + Assert.That(firstLine.FullLine.Contains(names[2], StringComparison.Ordinal)); } } \ No newline at end of file diff --git a/src/LogExpert.Tests/CSVColumnizerTest.cs b/src/LogExpert.Tests/CSVColumnizerTest.cs index 31ca0b96..e1a2aa54 100644 --- a/src/LogExpert.Tests/CSVColumnizerTest.cs +++ b/src/LogExpert.Tests/CSVColumnizerTest.cs @@ -1,31 +1,29 @@ -using LogExpert.Classes.Log; -using LogExpert.Entities; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; + using NUnit.Framework; -using System; -using System.IO; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +public class CSVColumnizerTest { - [TestFixture] - public class CSVColumnizerTest + [TestCase(@".\TestData\organizations-10000.csv", new[] { "Index", "Organization Id", "Name", "Website", "Country", "Description", "Founded", "Industry", "Number of employees" })] + [TestCase(@".\TestData\organizations-1000.csv", new[] { "Index", "Organization Id", "Name", "Website", "Country", "Description", "Founded", "Industry", "Number of employees" })] + [TestCase(@".\TestData\people-10000.csv", new[] { "Index", "User Id", "First Name", "Last Name", "Sex", "Email", "Phone", "Date of birth", "Job Title" })] + public void Instantiat_CSVFile_BuildCorrectColumnizer (string filename, string[] expectedHeaders) { - [TestCase(@".\TestData\organizations-10000.csv", new[] {"Index","Organization Id","Name","Website","Country","Description","Founded","Industry","Number of employees"})] - [TestCase(@".\TestData\organizations-1000.csv", new[] {"Index","Organization Id","Name","Website","Country","Description","Founded","Industry","Number of employees"})] - [TestCase(@".\TestData\people-10000.csv", new[] {"Index","User Id","First Name","Last Name","Sex","Email","Phone","Date of birth","Job Title"})] - public void Instantiat_CSVFile_BuildCorrectColumnizer(string filename, string[] expectedHeaders) + CsvColumnizer.CsvColumnizer csvColumnizer = new(); + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); + LogfileReader reader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + reader.ReadFiles(); + ILogLine line = reader.GetLogLine(0); + IColumnizedLogLine logline = new ColumnizedLogLine(); + if (line != null) { - CsvColumnizer.CsvColumnizer csvColumnizer = new(); - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); - LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions()); - reader.ReadFiles(); - ILogLine line = reader.GetLogLine(0); - IColumnizedLogLine logline = new ColumnizedLogLine(); - if (line != null) - { - logline = csvColumnizer.SplitLine(null, line); - } - string expectedResult = string.Join(",", expectedHeaders); - Assert.That(logline.LogLine.FullLine, Is.EqualTo(expectedResult)); + logline = csvColumnizer.SplitLine(null, line); } + var expectedResult = string.Join(",", expectedHeaders); + Assert.That(logline.LogLine.FullLine, Is.EqualTo(expectedResult)); } } diff --git a/src/LogExpert.Tests/ColumnizerPickerTest.cs b/src/LogExpert.Tests/ColumnizerPickerTest.cs index ae6bedad..c802d062 100644 --- a/src/LogExpert.Tests/ColumnizerPickerTest.cs +++ b/src/LogExpert.Tests/ColumnizerPickerTest.cs @@ -1,120 +1,117 @@ -using JsonColumnizer; -using LogExpert.Classes; -using LogExpert.Classes.Columnizer; -using LogExpert.Classes.Log; -using LogExpert.Entities; +using JsonColumnizer; + +using LogExpert.Core.Classes.Columnizer; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; + using Moq; + using NUnit.Framework; -using System; -using System.IO; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +/// +/// Summary description for AutoColumnizerTest +/// +[TestFixture] +public class ColumnizerPickerTest { - /// - /// Summary description for AutoColumnizerTest - /// - [TestFixture] - public class ColumnizerPickerTest + [TestCase("Square Bracket Columnizer", "30/08/2018 08:51:42.712 [TRACE] [a] hello", "30/08/2018 08:51:42.712 [DATAIO] [b] world", null, null, null)] + [TestCase("Square Bracket Columnizer", "30/08/2018 08:51:42.712 [TRACE] hello", "30/08/2018 08:51:42.712 [DATAIO][] world", null, null, null)] + [TestCase("Square Bracket Columnizer", "", "30/08/2018 08:51:42.712 [TRACE] hello", "30/08/2018 08:51:42.712 [TRACE] hello", "[DATAIO][b][c] world", null)] + [TestCase("Timestamp Columnizer", "30/08/2018 08:51:42.712 no bracket 1", "30/08/2018 08:51:42.712 no bracket 2", "30/08/2018 08:51:42.712 [TRACE] with bracket 1", "30/08/2018 08:51:42.712 [TRACE] with bracket 2", "no bracket 3")] + public void FindColumnizer_ReturnCorrectColumnizer (string expectedColumnizerName, string line0, string line1, string line2, string line3, string line4) { - [TestCase("Square Bracket Columnizer", "30/08/2018 08:51:42.712 [TRACE] [a] hello", "30/08/2018 08:51:42.712 [DATAIO] [b] world", null, null, null)] - [TestCase("Square Bracket Columnizer", "30/08/2018 08:51:42.712 [TRACE] hello", "30/08/2018 08:51:42.712 [DATAIO][] world", null, null, null)] - [TestCase("Square Bracket Columnizer", "", "30/08/2018 08:51:42.712 [TRACE] hello", "30/08/2018 08:51:42.712 [TRACE] hello", "[DATAIO][b][c] world", null)] - [TestCase("Timestamp Columnizer", "30/08/2018 08:51:42.712 no bracket 1", "30/08/2018 08:51:42.712 no bracket 2", "30/08/2018 08:51:42.712 [TRACE] with bracket 1", "30/08/2018 08:51:42.712 [TRACE] with bracket 2", "no bracket 3")] - public void FindColumnizer_ReturnCorrectColumnizer(string expectedColumnizerName, string line0, string line1, string line2, string line3, string line4) + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test"); + + Mock autoLogLineColumnizerCallbackMock = new(); + + autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(0)).Returns(new TestLogLine() { - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test"); - - Mock autoLogLineColumnizerCallbackMock = new(); - - autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(0)).Returns(new TestLogLine() - { - FullLine = line0, - LineNumber = 0 - }); - - autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(1)).Returns(new TestLogLine() - { - FullLine = line1, - LineNumber = 1 - }); - - autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(2)).Returns(new TestLogLine() - { - FullLine = line2, - LineNumber = 2 - }); - - autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(3)).Returns(new TestLogLine() - { - FullLine = line3, - LineNumber = 3 - }); - autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(4)).Returns(new TestLogLine() - { - FullLine = line4, - LineNumber = 4 - }); - - var result = ColumnizerPicker.FindColumnizer(path, autoLogLineColumnizerCallbackMock.Object); - - Assert.That(result.GetName(), Is.EqualTo(expectedColumnizerName)); - } - - - [TestCase(@".\TestData\JsonColumnizerTest_01.txt", typeof(JsonCompactColumnizer))] - [TestCase(@".\TestData\SquareBracketColumnizerTest_02.txt", typeof(SquareBracketColumnizer))] - public void FindReplacementForAutoColumnizer_ValidTextFile_ReturnCorrectColumnizer( - string fileName, Type columnizerType) + FullLine = line0, + LineNumber = 0 + }); + + autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(1)).Returns(new TestLogLine() { - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions()); - reader.ReadFiles(); + FullLine = line1, + LineNumber = 1 + }); - Mock autoColumnizer = new(); - autoColumnizer.Setup(a => a.GetName()).Returns("Auto Columnizer"); + autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(2)).Returns(new TestLogLine() + { + FullLine = line2, + LineNumber = 2 + }); - // TODO: When DI container is ready, we can mock this set up. - PluginRegistry.Instance.RegisteredColumnizers.Add(new JsonCompactColumnizer()); - var result = ColumnizerPicker.FindReplacementForAutoColumnizer(fileName, reader, autoColumnizer.Object); + autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(3)).Returns(new TestLogLine() + { + FullLine = line3, + LineNumber = 3 + }); + autoLogLineColumnizerCallbackMock.Setup(a => a.GetLogLine(4)).Returns(new TestLogLine() + { + FullLine = line4, + LineNumber = 4 + }); - Assert.That(columnizerType, Is.EqualTo(result.GetType())); - } + var result = ColumnizerPicker.FindColumnizer(path, autoLogLineColumnizerCallbackMock.Object, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - [TestCase(@".\TestData\FileNotExists.txt", typeof(DefaultLogfileColumnizer))] - public void DecideColumnizerByName_WhenReaderIsNotReady_ReturnCorrectColumnizer( - string fileName, Type columnizerType) - { - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); + Assert.That(result.GetName(), Is.EqualTo(expectedColumnizerName)); + } - // TODO: When DI container is ready, we can mock this set up. - PluginRegistry.Instance.RegisteredColumnizers.Add(new JsonCompactColumnizer()); - var result = ColumnizerPicker.DecideColumnizerByName(fileName, - PluginRegistry.Instance.RegisteredColumnizers); - Assert.That(columnizerType, Is.EqualTo(result.GetType())); - } + [TestCase(@".\TestData\JsonColumnizerTest_01.txt", typeof(JsonCompactColumnizer))] + [TestCase(@".\TestData\SquareBracketColumnizerTest_02.txt", typeof(SquareBracketColumnizer))] + public void FindReplacementForAutoColumnizer_ValidTextFile_ReturnCorrectColumnizer ( + string fileName, Type columnizerType) + { + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); + LogfileReader reader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + reader.ReadFiles(); - [TestCase(@"Invalid Name", typeof(DefaultLogfileColumnizer))] - [TestCase(@"JSON Columnizer", typeof(JsonColumnizer.JsonColumnizer))] - public void DecideColumnizerByName_ValidTextFile_ReturnCorrectColumnizer( - string columnizerName, Type columnizerType) - { - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, columnizerName); + Mock autoColumnizer = new(); + autoColumnizer.Setup(a => a.GetName()).Returns("Auto Columnizer"); - // TODO: When DI container is ready, we can mock this set up. - PluginRegistry.Instance.RegisteredColumnizers.Add(new JsonColumnizer.JsonColumnizer()); + // TODO: When DI container is ready, we can mock this set up. + PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers.Add(new JsonCompactColumnizer()); + var result = ColumnizerPicker.FindReplacementForAutoColumnizer(fileName, reader, autoColumnizer.Object, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - var result = ColumnizerPicker.DecideColumnizerByName(columnizerName, - PluginRegistry.Instance.RegisteredColumnizers); + Assert.That(columnizerType, Is.EqualTo(result.GetType())); + } + + [TestCase(@".\TestData\FileNotExists.txt", typeof(DefaultLogfileColumnizer))] + public void DecideColumnizerByName_WhenReaderIsNotReady_ReturnCorrectColumnizer ( + string fileName, Type columnizerType) + { + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - Assert.That(columnizerType, Is.EqualTo(result.GetType())); - } + // TODO: When DI container is ready, we can mock this set up. + PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers.Add(new JsonCompactColumnizer()); + var result = ColumnizerPicker.DecideColumnizerByName(fileName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); - private class TestLogLine : ILogLine - { - public string Text => FullLine; - public string FullLine { get; set; } - public int LineNumber { get; set; } - } + Assert.That(columnizerType, Is.EqualTo(result.GetType())); + } + + [TestCase(@"Invalid Name", typeof(DefaultLogfileColumnizer))] + [TestCase(@"JSON Columnizer", typeof(JsonColumnizer.JsonColumnizer))] + public void DecideColumnizerByName_ValidTextFile_ReturnCorrectColumnizer ( + string columnizerName, Type columnizerType) + { + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, columnizerName); + + // TODO: When DI container is ready, we can mock this set up. + PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers.Add(new JsonColumnizer.JsonColumnizer()); + + var result = ColumnizerPicker.DecideColumnizerByName(columnizerName, PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + + Assert.That(columnizerType, Is.EqualTo(result.GetType())); + } + + private class TestLogLine : ILogLine + { + public string Text => FullLine; + public string FullLine { get; set; } + public int LineNumber { get; set; } } } \ No newline at end of file diff --git a/src/LogExpert.Tests/DateFormatParserTest.cs b/src/LogExpert.Tests/DateFormatParserTest.cs index c04ff45c..ca8622ee 100644 --- a/src/LogExpert.Tests/DateFormatParserTest.cs +++ b/src/LogExpert.Tests/DateFormatParserTest.cs @@ -1,126 +1,127 @@ -using LogExpert.Classes.DateTimeParser; +using LogExpert.Core.Classes.DateTimeParser; + using NUnit.Framework; + using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +public class DateFormatParserTest { - [TestFixture] - public class DateFormatParserTest + [Test] + public void CanParseAllCultures() { - [Test] - public void CanParseAllCultures() - { - var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); + var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures); - // HashSet exclude = ["dz", "ckb-IR", "ar-SA", "lrc" , "lrc-IR", "mzn" , "mzn-IR", "ps"]; + // HashSet exclude = ["dz", "ckb-IR", "ar-SA", "lrc" , "lrc-IR", "mzn" , "mzn-IR", "ps"]; - foreach (var culture in cultures) + foreach (var culture in cultures) + { + if (culture.Name == "dz" || culture.Name == "ar" || culture.Name.StartsWith("ar-") || culture.Name.StartsWith("dz-")) { - if (culture.Name == "dz" || culture.Name == "ar" || culture.Name.StartsWith("ar-") || culture.Name.StartsWith("dz-")) - { - Console.WriteLine($"The ${culture.Name} (${culture.DisplayName}) time format is not supported yet."); - continue; - } + Console.WriteLine($"The ${culture.Name} (${culture.DisplayName}) time format is not supported yet."); + continue; + } - var datePattern = GetDateAndTimeFormat(culture); + var datePattern = GetDateAndTimeFormat(culture); - if (datePattern.StartsWith('g')) - { - Console.WriteLine("time format that starts with g is not supported yet."); - continue; - } + if (datePattern.StartsWith('g')) + { + Console.WriteLine("time format that starts with g is not supported yet."); + continue; + } - var message = $"Culture: {culture.Name} ({culture.EnglishName} {datePattern})"; - var sections = Parser.ParseSections(datePattern, out bool syntaxError); + var message = $"Culture: {culture.Name} ({culture.EnglishName} {datePattern})"; + var sections = Parser.ParseSections(datePattern, out var syntaxError); - Assert.That(syntaxError, Is.False, message); + Assert.That(syntaxError, Is.False, message); - var dateSection = sections.FirstOrDefault(); - Assert.That(dateSection, Is.Not.Null, message); + var dateSection = sections.FirstOrDefault(); + Assert.That(dateSection, Is.Not.Null, message); - var now = DateTime.Now; - var expectedFormattedDate = now.ToString(datePattern); - var actualFormattedDate = now.ToString(string.Join("", dateSection.GeneralTextDateDurationParts)); - Assert.That(actualFormattedDate, Is.EqualTo(expectedFormattedDate), message); - } + var now = DateTime.Now; + var expectedFormattedDate = now.ToString(datePattern); + var actualFormattedDate = now.ToString(string.Join("", dateSection.GeneralTextDateDurationParts)); + Assert.That(actualFormattedDate, Is.EqualTo(expectedFormattedDate), message); } + } - [Test] - [TestCase("en-US", "MM", "dd", "yyyy", "hh", "mm", "ss", "tt")] - [TestCase("fr-FR", "dd", "MM", "yyyy", "HH", "mm", "ss")] - [TestCase("de-DE", "dd", "MM", "yyyy", "HH", "mm", "ss")] - [TestCase("ar-TN", "dd", "MM", "yyyy", "hh", "mm", "ss", "tt")] - [TestCase("as", "dd", "MM", "yyyy", "tt", "hh", "mm", "ss")] - [TestCase("bg", "dd", "MM", "yyyy", "HH", "mm", "ss")] - public void TestDateFormatParserFromCulture(string cultureInfoName, params string[] expectedDateParts) - { - var culture = CultureInfo.GetCultureInfo(cultureInfoName); + [Test] + [TestCase("en-US", "MM", "dd", "yyyy", "hh", "mm", "ss", "tt")] + [TestCase("fr-FR", "dd", "MM", "yyyy", "HH", "mm", "ss")] + [TestCase("de-DE", "dd", "MM", "yyyy", "HH", "mm", "ss")] + [TestCase("ar-TN", "dd", "MM", "yyyy", "hh", "mm", "ss", "tt")] + [TestCase("as", "dd", "MM", "yyyy", "tt", "hh", "mm", "ss")] + [TestCase("bg", "dd", "MM", "yyyy", "HH", "mm", "ss")] + public void TestDateFormatParserFromCulture(string cultureInfoName, params string[] expectedDateParts) + { + var culture = CultureInfo.GetCultureInfo(cultureInfoName); - var datePattern = GetDateAndTimeFormat(culture); + var datePattern = GetDateAndTimeFormat(culture); - var sections = Parser.ParseSections(datePattern, out bool syntaxError); + var sections = Parser.ParseSections(datePattern, out var syntaxError); - var message = $"Culture: {culture.EnglishName}, Actual date pattern: {datePattern}"; + var message = $"Culture: {culture.EnglishName}, Actual date pattern: {datePattern}"; - Assert.That(syntaxError, Is.False, message); + Assert.That(syntaxError, Is.False, message); - var dateSection = sections.FirstOrDefault(); - Assert.That(dateSection, Is.Not.Null); + var dateSection = sections.FirstOrDefault(); + Assert.That(dateSection, Is.Not.Null); - var dateParts = dateSection - .GeneralTextDateDurationParts - .Where(Token.IsDatePart) - .Select(p => DateFormatPartAdjuster.AdjustDateTimeFormatPart(p)) - .ToArray(); + var dateParts = dateSection + .GeneralTextDateDurationParts + .Where(Token.IsDatePart) + .Select(p => DateFormatPartAdjuster.AdjustDateTimeFormatPart(p)) + .ToArray(); - Assert.That(dateParts.Length, Is.EqualTo(expectedDateParts.Length), message); + Assert.That(dateParts.Length, Is.EqualTo(expectedDateParts.Length), message); - for (var i = 0; i < expectedDateParts.Length; i++) - { - var expected = expectedDateParts[i]; - var actual = dateParts[i]; - Assert.That(actual, Is.EqualTo(expected), message); - } + for (var i = 0; i < expectedDateParts.Length; i++) + { + var expected = expectedDateParts[i]; + var actual = dateParts[i]; + Assert.That(actual, Is.EqualTo(expected), message); } + } - static string RemoveCharacters(string input, string charsToRemove) - { - HashSet charsToRemoveSet = new(charsToRemove); - StringBuilder result = new(); + static string RemoveCharacters(string input, string charsToRemove) + { + HashSet charsToRemoveSet = new(charsToRemove); + StringBuilder result = new(); - foreach (char c in input) + foreach (var c in input) + { + if (!charsToRemoveSet.Contains(c)) { - if (!charsToRemoveSet.Contains(c)) - { - result.Append(c); - } + result.Append(c); } - - return result.ToString(); } - private string GetDateAndTimeFormat(CultureInfo culture) - { + return result.ToString(); + } - string InvisibleUNICODEmarkers = - "\u00AD\u034F\u061C\u115F\u1160\u17B4\u17B5" + - "\u180B\u180C\u180D\u180E\u200B\u200C\u200D\u200E\u200F" + - "\u202A\u202B\u202C\u202D\u202E\u202F\u205F\u2060\u2062" + - "\u2063\u2064\u2066\u2067\u2068\u2069\u2800\u3164\uFE00" + - "\uFE01\uFE02\uFE03\uFE04\uFE05\uFE06\uFE07\uFE08\uFE09" + - "\uFE0A\uFE0B\uFE0C\uFE0D\uFE0E\uFE0F"; + private string GetDateAndTimeFormat(CultureInfo culture) + { + var InvisibleUNICODEmarkers = + "\u00AD\u034F\u061C\u115F\u1160\u17B4\u17B5" + + "\u180B\u180C\u180D\u180E\u200B\u200C\u200D\u200E\u200F" + + "\u202A\u202B\u202C\u202D\u202E\u202F\u205F\u2060\u2062" + + "\u2063\u2064\u2066\u2067\u2068\u2069\u2800\u3164\uFE00" + + "\uFE01\uFE02\uFE03\uFE04\uFE05\uFE06\uFE07\uFE08\uFE09" + + "\uFE0A\uFE0B\uFE0C\uFE0D\uFE0E\uFE0F"; - string dateTime = string.Concat(culture.DateTimeFormat.ShortDatePattern.ToString(), - " ", - culture.DateTimeFormat.LongTimePattern.ToString()); - return RemoveCharacters(dateTime, InvisibleUNICODEmarkers); + var dateTime = string.Concat(culture.DateTimeFormat.ShortDatePattern.ToString(), + " ", + culture.DateTimeFormat.LongTimePattern.ToString()); + + return RemoveCharacters(dateTime, InvisibleUNICODEmarkers); - } } } diff --git a/src/LogExpert.Tests/Extensions/EnumerableTests.cs b/src/LogExpert.Tests/Extensions/EnumerableTests.cs index 94ae6d49..cbc4fd7d 100644 --- a/src/LogExpert.Tests/Extensions/EnumerableTests.cs +++ b/src/LogExpert.Tests/Extensions/EnumerableTests.cs @@ -1,61 +1,59 @@ -using LogExpert.Extensions; +using LogExpert.Core.Extensions; using NUnit.Framework; -using System; using System.Collections.Generic; -namespace LogExpert.Tests.Extensions +namespace LogExpert.Tests.Extensions; + +[TestFixture] +public class EnumerableTests { - [TestFixture] - public class EnumerableTests + [Test] + public void Extensions_IsEmpty_NullArray() { - [Test] - public void Extensions_IsEmpty_NullArray() - { - object[] arrayObject = null; + object[] arrayObject = null; - Assert.That(arrayObject.IsEmpty(), Is.True); - } + Assert.That(arrayObject.IsEmpty(), Is.True); + } - [Test] - public void Extensions_IsEmpty_EmptyArray() - { - object[] arrayObject = Array.Empty(); + [Test] + public void Extensions_IsEmpty_EmptyArray() + { + object[] arrayObject = []; - Assert.That(arrayObject.IsEmpty(), Is.True); - } + Assert.That(arrayObject.IsEmpty(), Is.True); + } - [Test] - public void Extensions_IsEmpty_FilledArray() - { - object[] arrayObject = { new() }; + [Test] + public void Extensions_IsEmpty_FilledArray() + { + object[] arrayObject = [new()]; - Assert.That(!arrayObject.IsEmpty(), Is.True); - } + Assert.That(!arrayObject.IsEmpty(), Is.True); + } - [Test] - public void Extensions_IsEmpty_NullIEnumerable() - { - IEnumerable arrayObject = null; + [Test] + public void Extensions_IsEmpty_NullIEnumerable() + { + IEnumerable arrayObject = null; - Assert.That(arrayObject.IsEmpty(), Is.True); - } + Assert.That(arrayObject.IsEmpty(), Is.True); + } - [Test] - public void Extensions_IsEmpty_EmptyIEnumerable() - { - IEnumerable arrayObject = new List(); + [Test] + public void Extensions_IsEmpty_EmptyIEnumerable() + { + IEnumerable arrayObject = []; - Assert.That(arrayObject.IsEmpty(), Is.True); - } + Assert.That(arrayObject.IsEmpty(), Is.True); + } - [Test] - public void Extensions_IsEmpty_FilledIEnumerable() - { - IEnumerable arrayObject = new List(new[] { new object() }); + [Test] + public void Extensions_IsEmpty_FilledIEnumerable() + { + IEnumerable arrayObject = new List([new object()]); - Assert.That(!arrayObject.IsEmpty(), Is.True); - } + Assert.That(!arrayObject.IsEmpty(), Is.True); } } diff --git a/src/LogExpert.Tests/JSONSaveTest.cs b/src/LogExpert.Tests/JSONSaveTest.cs index e78be754..01f542a3 100644 --- a/src/LogExpert.Tests/JSONSaveTest.cs +++ b/src/LogExpert.Tests/JSONSaveTest.cs @@ -1,41 +1,44 @@ using LogExpert.Config; +using LogExpert.Core.Config; + using Newtonsoft.Json; + using NUnit.Framework; + using System.IO; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +public class JSONSaveTest { - [TestFixture] - public class JSONSaveTest + [Test(Author = "Hirogen", Description = "Save Options as JSON and Check if the written file can be cast again into the settings object")] + public void SaveOptionsAsJSON() { - [Test(Author = "Hirogen", Description = "Save Options as JSON and Check if the written file can be cast again into the settings object")] - public void SaveOptionsAsJSON() + ConfigManager.Instance.Settings.AlwaysOnTop = true; + ConfigManager.Instance.Save(SettingsFlags.All); + var configDir = ConfigManager.Instance.ConfigDir; + var settingsFile = configDir + "\\settings.json"; + + Settings settings = null; + + Assert.DoesNotThrow(CastSettings); + Assert.That(settings, Is.Not.Null); + Assert.That(settings.AlwaysOnTop, Is.True); + + ConfigManager.Instance.Settings.AlwaysOnTop = false; + ConfigManager.Instance.Save(SettingsFlags.All); + + settings = null; + Assert.DoesNotThrow(CastSettings); + + Assert.That(settings, !Is.Null); + Assert.That(settings.AlwaysOnTop, Is.False); + + + void CastSettings() { - ConfigManager.Settings.alwaysOnTop = true; - ConfigManager.Save(SettingsFlags.All); - string configDir = ConfigManager.ConfigDir; - string settingsFile = configDir + "\\settings.json"; - - Settings settings = null; - - Assert.DoesNotThrow(CastSettings); - Assert.That(settings, Is.Not.Null); - Assert.That(settings.alwaysOnTop, Is.True); - - ConfigManager.Settings.alwaysOnTop = false; - ConfigManager.Save(SettingsFlags.All); - - settings = null; - Assert.DoesNotThrow(CastSettings); - - Assert.That(settings, !Is.Null); - Assert.That(settings.alwaysOnTop, Is.False); - - - void CastSettings() - { - settings = JsonConvert.DeserializeObject(File.ReadAllText(settingsFile)); - } + settings = JsonConvert.DeserializeObject(File.ReadAllText(settingsFile)); } } } diff --git a/src/LogExpert.Tests/JsonColumnizerTest.cs b/src/LogExpert.Tests/JsonColumnizerTest.cs index 2ee41a41..aae3663b 100644 --- a/src/LogExpert.Tests/JsonColumnizerTest.cs +++ b/src/LogExpert.Tests/JsonColumnizerTest.cs @@ -1,39 +1,35 @@ -using LogExpert.Classes.Log; -using LogExpert.Entities; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; using NUnit.Framework; -using System; -using System.IO; +namespace LogExpert.Tests; -namespace LogExpert.Tests +[TestFixture] +public class JsonColumnizerTest { - [TestFixture] - public class JsonColumnizerTest + [TestCase(@".\TestData\JsonColumnizerTest_01.txt", "time @m level")] + public void GetColumnNames_HappyFile_ColumnNameMatches (string fileName, string expectedHeaders) { - [TestCase(@".\TestData\JsonColumnizerTest_01.txt", "time @m level")] - public void GetColumnNames_HappyFile_ColumnNameMatches(string fileName, string expectedHeaders) - { - var jsonColumnizer = new JsonColumnizer.JsonColumnizer(); - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - LogfileReader reader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions()); - reader.ReadFiles(); - - ILogLine line = reader.GetLogLine(0); - if (line != null) - { - jsonColumnizer.SplitLine(null, line); - } + var jsonColumnizer = new JsonColumnizer.JsonColumnizer(); + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); + LogfileReader reader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + reader.ReadFiles(); - line = reader.GetLogLine(1); - if (line != null) - { - jsonColumnizer.SplitLine(null, line); - } + ILogLine line = reader.GetLogLine(0); + if (line != null) + { + jsonColumnizer.SplitLine(null, line); + } - var columnHeaders = jsonColumnizer.GetColumnNames(); - var result = string.Join(" ", columnHeaders); - Assert.That(expectedHeaders, Is.EqualTo(result)); + line = reader.GetLogLine(1); + if (line != null) + { + jsonColumnizer.SplitLine(null, line); } + + var columnHeaders = jsonColumnizer.GetColumnNames(); + var result = string.Join(" ", columnHeaders); + Assert.That(expectedHeaders, Is.EqualTo(result)); } } diff --git a/src/LogExpert.Tests/JsonCompactColumnizerTest.cs b/src/LogExpert.Tests/JsonCompactColumnizerTest.cs index 8c2756be..970b7ff4 100644 --- a/src/LogExpert.Tests/JsonCompactColumnizerTest.cs +++ b/src/LogExpert.Tests/JsonCompactColumnizerTest.cs @@ -1,42 +1,39 @@ -using LogExpert.Classes.Log; -using LogExpert.Entities; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; + using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.IO; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +public class JsonCompactColumnizerTest { - [TestFixture] - public class JsonCompactColumnizerTest + [TestCase(@".\TestData\JsonCompactColumnizerTest_01.json", Priority.PerfectlySupport)] + // As long as the json file contains one of the pre-defined key, it's perfectly supported. + [TestCase(@".\TestData\JsonCompactColumnizerTest_02.json", Priority.PerfectlySupport)] + [TestCase(@".\TestData\JsonCompactColumnizerTest_03.json", Priority.WellSupport)] + public void GetPriority_HappyFile_PriorityMatches (string fileName, Priority priority) { - [TestCase(@".\TestData\JsonCompactColumnizerTest_01.json", Priority.PerfectlySupport)] - // As long as the json file contains one of the pre-defined key, it's perfectly supported. - [TestCase(@".\TestData\JsonCompactColumnizerTest_02.json", Priority.PerfectlySupport)] - [TestCase(@".\TestData\JsonCompactColumnizerTest_03.json", Priority.WellSupport)] - public void GetPriority_HappyFile_PriorityMatches(string fileName, Priority priority) + var jsonCompactColumnizer = new JsonColumnizer.JsonCompactColumnizer(); + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); + LogfileReader logFileReader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + logFileReader.ReadFiles(); + List loglines = new() { - var jsonCompactColumnizer = new JsonColumnizer.JsonCompactColumnizer(); - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - LogfileReader logFileReader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions()); - logFileReader.ReadFiles(); - List loglines = new() - { - // Sampling a few lines to select the correct columnizer - logFileReader.GetLogLine(0), - logFileReader.GetLogLine(1), - logFileReader.GetLogLine(2), - logFileReader.GetLogLine(3), - logFileReader.GetLogLine(4), - logFileReader.GetLogLine(5), - logFileReader.GetLogLine(25), - logFileReader.GetLogLine(100), - logFileReader.GetLogLine(200), - logFileReader.GetLogLine(400) - }; + // Sampling a few lines to select the correct columnizer + logFileReader.GetLogLine(0), + logFileReader.GetLogLine(1), + logFileReader.GetLogLine(2), + logFileReader.GetLogLine(3), + logFileReader.GetLogLine(4), + logFileReader.GetLogLine(5), + logFileReader.GetLogLine(25), + logFileReader.GetLogLine(100), + logFileReader.GetLogLine(200), + logFileReader.GetLogLine(400) + }; - var result = jsonCompactColumnizer.GetPriority(path, loglines); - Assert.That(result, Is.EqualTo(priority)); - } + var result = jsonCompactColumnizer.GetPriority(path, loglines); + Assert.That(result, Is.EqualTo(priority)); } } diff --git a/src/LogExpert.Tests/LocalFileSystemTest.cs b/src/LogExpert.Tests/LocalFileSystemTest.cs index 88baaa09..76a6ee1a 100644 --- a/src/LogExpert.Tests/LocalFileSystemTest.cs +++ b/src/LogExpert.Tests/LocalFileSystemTest.cs @@ -1,52 +1,53 @@ -using LogExpert.Classes; +using LogExpert.PluginRegistry.FileSystem; + using NUnit.Framework; + using System; using System.IO; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +internal class LocalFileSystemTest : RolloverHandlerTestBase { - [TestFixture] - internal class LocalFileSystemTest : RolloverHandlerTestBase + [TearDown] + public void TearDown() + { + Cleanup(); + } + + [OneTimeSetUp] + public void Boot() + { + Cleanup(); + } + + + [Test] + public void TestUriHandle() { - [TearDown] - public void TearDown() - { - Cleanup(); - } - - [OneTimeSetUp] - public void Boot() - { - Cleanup(); - } - - - [Test] - public void TestUriHandle() - { - LocalFileSystem fs = new(); - Assert.That(fs.CanHandleUri("file:///c:/logfile.txt"), Is.True); - Assert.That(fs.CanHandleUri("file:///c:\\logfile.txt"), Is.True); - Assert.That(fs.CanHandleUri("c:/logfile.txt"), Is.True); - Assert.That(fs.CanHandleUri("c:\\logfile.txt"), Is.True); - } - - [Test] - public void TestUriToFileStream() - { - DirectoryInfo dInfo = Directory.CreateDirectory(RolloverHandlerTest.TEST_DIR_NAME); - string fullName = CreateFile(dInfo, "test.log"); - - LocalFileSystem fs = new(); - ILogFileInfo info = fs.GetLogfileInfo(fullName); - Assert.That(info.Length > 0, Is.True); - Assert.That(info.OriginalLength == info.Length, Is.True); - Stream stream = info.OpenStream(); - Assert.That(stream.CanSeek, Is.True); - StreamReader reader = new(stream); - string line = reader.ReadLine(); - Assert.That(line.StartsWith("line number", StringComparison.InvariantCultureIgnoreCase), Is.True); - reader.Close(); - } + LocalFileSystem fs = new(); + Assert.That(fs.CanHandleUri("file:///c:/logfile.txt"), Is.True); + Assert.That(fs.CanHandleUri("file:///c:\\logfile.txt"), Is.True); + Assert.That(fs.CanHandleUri("c:/logfile.txt"), Is.True); + Assert.That(fs.CanHandleUri("c:\\logfile.txt"), Is.True); + } + + [Test] + public void TestUriToFileStream() + { + DirectoryInfo dInfo = Directory.CreateDirectory(RolloverHandlerTest.TEST_DIR_NAME); + var fullName = CreateFile(dInfo, "test.log"); + + LocalFileSystem fs = new(); + ILogFileInfo info = fs.GetLogfileInfo(fullName); + Assert.That(info.Length > 0, Is.True); + Assert.That(info.OriginalLength == info.Length, Is.True); + Stream stream = info.OpenStream(); + Assert.That(stream.CanSeek, Is.True); + StreamReader reader = new(stream); + var line = reader.ReadLine(); + Assert.That(line.StartsWith("line number", StringComparison.InvariantCultureIgnoreCase), Is.True); + reader.Close(); } } \ No newline at end of file diff --git a/src/LogExpert.Tests/LogExpert.Tests.csproj b/src/LogExpert.Tests/LogExpert.Tests.csproj index 8e058cf3..71fdb0dc 100644 --- a/src/LogExpert.Tests/LogExpert.Tests.csproj +++ b/src/LogExpert.Tests/LogExpert.Tests.csproj @@ -1,34 +1,34 @@  + net8.0-windows true - Library + true - false true true - false bin\$(Configuration) true - - - true - - - ..\Solution Items\Key.snk LogExpert.Tests - LogExpert.Tests - Copyright © 2018 - 1.0.0.0 - 1.0.0.0 + + + + + + + + + + - + + PreserveNewest @@ -38,6 +38,9 @@ PreserveNewest + + + PreserveNewest @@ -59,16 +62,6 @@ PreserveNewest - - - - - - - - - - PreserveNewest @@ -78,16 +71,9 @@ PreserveNewest - - PreserveNewest - - - - Key.snk - PreserveNewest @@ -98,4 +84,5 @@ PreserveNewest + diff --git a/src/LogExpert.Tests/LogStreamReaderTest.cs b/src/LogExpert.Tests/LogStreamReaderTest.cs index 9bb51099..4ee9dd35 100644 --- a/src/LogExpert.Tests/LogStreamReaderTest.cs +++ b/src/LogExpert.Tests/LogStreamReaderTest.cs @@ -1,29 +1,77 @@ -using LogExpert.Classes.Log; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; + using NUnit.Framework; + using System.IO; using System.Text; -using LogExpert.Entities; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +public class LogStreamReaderTest { - [TestFixture] - public class LogStreamReaderTest + [Test] + [TestCase("Line 1\nLine 2\nLine 3", 3)] + [TestCase("Line 1\nLine 2\nLine 3\n", 3)] + [TestCase("Line 1\r\nLine 2\r\nLine 3", 3)] + [TestCase("Line 1\r\nLine 2\r\nLine 3\r\n", 3)] + [TestCase("Line 1\rLine 2\rLine 3", 3)] + [TestCase("Line 1\rLine 2\rLine 3\r", 3)] + public void ReadLinesWithSystemNewLine(string text, int expectedLines) { - [Test] - [TestCase("Line 1\nLine 2\nLine 3", 3)] - [TestCase("Line 1\nLine 2\nLine 3\n", 3)] - [TestCase("Line 1\r\nLine 2\r\nLine 3", 3)] - [TestCase("Line 1\r\nLine 2\r\nLine 3\r\n", 3)] - [TestCase("Line 1\rLine 2\rLine 3", 3)] - [TestCase("Line 1\rLine 2\rLine 3\r", 3)] - public void ReadLinesWithSystemNewLine(string text, int expectedLines) + using var stream = new MemoryStream(Encoding.ASCII.GetBytes(text)); + using var reader = new PositionAwareStreamReaderSystem(stream, new EncodingOptions()); + var lineCount = 0; + while (true) { - using var stream = new MemoryStream(Encoding.ASCII.GetBytes(text)); - using var reader = new PositionAwareStreamReaderSystem(stream, new EncodingOptions()); - int lineCount = 0; + var line = reader.ReadLine(); + if (line == null) + { + break; + } + + lineCount += 1; + + Assert.That(line.StartsWith($"Line {lineCount}"), $"Invalid line: {line}"); + } + + Assert.That(expectedLines, Is.EqualTo(lineCount), $"Unexpected lines:\n{text}"); + } + + [Test] + [TestCase("\n\n\n", 3)] + [TestCase("\r\n\r\n\r\n", 3)] + [TestCase("\r\r\r", 3)] + public void CountLinesWithSystemNewLine(string text, int expectedLines) + { + using var stream = new MemoryStream(Encoding.ASCII.GetBytes(text)); + using var reader = new PositionAwareStreamReaderSystem(stream, new EncodingOptions()); + var lineCount = 0; + while (reader.ReadLine() != null) + { + lineCount += 1; + } + + Assert.That(expectedLines, Is.EqualTo(lineCount), $"Unexpected lines:\n{text}"); + } + + [Test] + [TestCase("Line 1\nLine 2\nLine 3", 3)] + [TestCase("Line 1\nLine 2\nLine 3\n", 3)] + [TestCase("Line 1\r\nLine 2\r\nLine 3", 3)] + [TestCase("Line 1\r\nLine 2\r\nLine 3\r\n", 3)] + [TestCase("Line 1\rLine 2\rLine 3", 3)] + [TestCase("Line 1\rLine 2\rLine 3\r", 3)] + public void ReadLinesWithLegacyNewLine(string text, int expectedLines) + { + using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(text))) + using (var reader = new PositionAwareStreamReaderLegacy(stream, new EncodingOptions())) + { + var lineCount = 0; while (true) { - string line = reader.ReadLine(); + var line = reader.ReadLine(); if (line == null) { break; @@ -36,71 +84,24 @@ public void ReadLinesWithSystemNewLine(string text, int expectedLines) Assert.That(expectedLines, Is.EqualTo(lineCount), $"Unexpected lines:\n{text}"); } - - [Test] - [TestCase("\n\n\n", 3)] - [TestCase("\r\n\r\n\r\n", 3)] - [TestCase("\r\r\r", 3)] - public void CountLinesWithSystemNewLine(string text, int expectedLines) + } + [Test] + [TestCase("\n\n\n", 3)] + [TestCase("\r\n\r\n\r\n", 3)] + [TestCase("\r\r\r", 3)] + public void CountLinesWithLegacyNewLine(string text, int expectedLines) + { + using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(text))) + using (var reader = new PositionAwareStreamReaderLegacy(stream, new EncodingOptions())) { - using var stream = new MemoryStream(Encoding.ASCII.GetBytes(text)); - using var reader = new PositionAwareStreamReaderSystem(stream, new EncodingOptions()); - int lineCount = 0; + var lineCount = 0; while (reader.ReadLine() != null) { lineCount += 1; } - Assert.That(expectedLines, Is.EqualTo(lineCount), $"Unexpected lines:\n{text}"); - } - - [Test] - [TestCase("Line 1\nLine 2\nLine 3", 3)] - [TestCase("Line 1\nLine 2\nLine 3\n", 3)] - [TestCase("Line 1\r\nLine 2\r\nLine 3", 3)] - [TestCase("Line 1\r\nLine 2\r\nLine 3\r\n", 3)] - [TestCase("Line 1\rLine 2\rLine 3", 3)] - [TestCase("Line 1\rLine 2\rLine 3\r", 3)] - public void ReadLinesWithLegacyNewLine(string text, int expectedLines) - { - using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(text))) - using (var reader = new PositionAwareStreamReaderLegacy(stream, new EncodingOptions())) - { - int lineCount = 0; - while (true) - { - string line = reader.ReadLine(); - if (line == null) - { - break; - } - - lineCount += 1; - - Assert.That(line.StartsWith($"Line {lineCount}"), $"Invalid line: {line}"); - } - - Assert.That(expectedLines, Is.EqualTo(lineCount), $"Unexpected lines:\n{text}"); - } - } - [Test] - [TestCase("\n\n\n", 3)] - [TestCase("\r\n\r\n\r\n", 3)] - [TestCase("\r\r\r", 3)] - public void CountLinesWithLegacyNewLine(string text, int expectedLines) - { - using (var stream = new MemoryStream(Encoding.ASCII.GetBytes(text))) - using (var reader = new PositionAwareStreamReaderLegacy(stream, new EncodingOptions())) - { - int lineCount = 0; - while (reader.ReadLine() != null) - { - lineCount += 1; - } - - Assert.That(expectedLines, Is.EqualTo(lineCount), $"Unexpected lines:\n{text}"); - } + Assert.That(expectedLines, Is.EqualTo(lineCount), $"Unexpected lines:\n{text}"); } } } diff --git a/src/LogExpert.Tests/LogWindowTest.cs b/src/LogExpert.Tests/LogWindowTest.cs index 6391bf0e..93880fc9 100644 --- a/src/LogExpert.Tests/LogWindowTest.cs +++ b/src/LogExpert.Tests/LogWindowTest.cs @@ -1,32 +1,31 @@ using NUnit.Framework; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +//TODO Find out why there is a "Drag and Drop Exception" until then, this 2 Tests can not be executed the block the build pipeline +[TestFixture] +public class LogWindowTest { - //TODO Find out why there is a "Drag and Drop Exception" until then, this 2 Tests can not be executed the block the build pipeline - [TestFixture] - public class LogWindowTest - { - //// TODO: Add more tests when DI container is ready. - //[TestCase(@".\TestData\JsonColumnizerTest_01.txt", typeof(DefaultLogfileColumnizer))] - //public void Instantiate_JsonFile_BuildCorrectColumnizer(string fileName, Type columnizerType) - //{ - // LogTabWindow logTabWindow = new(null, 0, false); - // LogWindow logWindow = new(logTabWindow, fileName, false, false); + //// TODO: Add more tests when DI container is ready. + //[TestCase(@".\TestData\JsonColumnizerTest_01.txt", typeof(DefaultLogfileColumnizer))] + //public void Instantiate_JsonFile_BuildCorrectColumnizer(string fileName, Type columnizerType) + //{ + // LogTabWindow logTabWindow = new(null, 0, false); + // LogWindow logWindow = new(logTabWindow, fileName, false, false); - // Assert.That(columnizerType, Is.EqualTo(logWindow.CurrentColumnizer.GetType())); - //} + // Assert.That(columnizerType, Is.EqualTo(logWindow.CurrentColumnizer.GetType())); + //} - //[TestCase(@".\TestData\XmlTest_01.xml")] - //[TestCase(@".\TestData\CsvTest_01.csv")] - //public void Instantiate_AnyFile_NotCrash(string fileName) - //{ - // PluginRegistry.GetInstance().RegisteredColumnizers.Add(new Log4jXmlColumnizer()); - // PluginRegistry.GetInstance().RegisteredColumnizers.Add(new CsvColumnizerType()); + //[TestCase(@".\TestData\XmlTest_01.xml")] + //[TestCase(@".\TestData\CsvTest_01.csv")] + //public void Instantiate_AnyFile_NotCrash(string fileName) + //{ + // PluginRegistry.GetInstance().RegisteredColumnizers.Add(new Log4jXmlColumnizer()); + // PluginRegistry.GetInstance().RegisteredColumnizers.Add(new CsvColumnizerType()); - // LogTabWindow logTabWindow = new(null, 0, false); - // LogWindow logWindow = new(logTabWindow, fileName, false, false); + // LogTabWindow logTabWindow = new(null, 0, false); + // LogWindow logWindow = new(logTabWindow, fileName, false, false); - // Assert.That(true, Is.True); - //} - } + // Assert.That(true, Is.True); + //} } diff --git a/src/LogExpert.Tests/Properties/AssemblyInfo.cs b/src/LogExpert.Tests/Properties/AssemblyInfo.cs deleted file mode 100644 index 756a12ef..00000000 --- a/src/LogExpert.Tests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -[assembly: ComVisible(false)] - -[assembly: Guid("1ffb09a8-dae4-4deb-aff6-8bae6d01c7ac")] -[assembly: System.Runtime.Versioning.SupportedOSPlatform("windows")] \ No newline at end of file diff --git a/src/LogExpert.Tests/ReaderTest.cs b/src/LogExpert.Tests/ReaderTest.cs index 6b76076b..98367143 100644 --- a/src/LogExpert.Tests/ReaderTest.cs +++ b/src/LogExpert.Tests/ReaderTest.cs @@ -1,67 +1,68 @@ -using LogExpert.Classes.Log; -using LogExpert.Entities; -using LogExpert.Interface; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; + using NUnit.Framework; + using System; using System.IO; using System.Text; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +internal class ReaderTest { - [TestFixture] - internal class ReaderTest + [TearDown] + public void TearDown() { - [TearDown] - public void TearDown() - { - } + } - [OneTimeSetUp] - public void Boot() - { - } + [OneTimeSetUp] + public void Boot() + { + } - private void CompareReaderImplementationsInternal(string fileName, Encoding enc, int maxPosition) - { - string path = Environment.CurrentDirectory + "\\data\\"; - EncodingOptions encOpts = new(); - encOpts.Encoding = enc; + private void CompareReaderImplementationsInternal(string fileName, Encoding enc, int maxPosition) + { + var path = Environment.CurrentDirectory + "\\data\\"; + EncodingOptions encOpts = new(); + encOpts.Encoding = enc; - using Stream s1 = new FileStream(path + fileName, FileMode.Open, FileAccess.Read); - using Stream s2 = new FileStream(path + fileName, FileMode.Open, FileAccess.Read); - using ILogStreamReader r1 = new PositionAwareStreamReaderLegacy(s1, encOpts); - using ILogStreamReader r2 = new PositionAwareStreamReaderSystem(s2, encOpts); - for (int lineNum = 0; ; lineNum++) + using Stream s1 = new FileStream(path + fileName, FileMode.Open, FileAccess.Read); + using Stream s2 = new FileStream(path + fileName, FileMode.Open, FileAccess.Read); + using ILogStreamReader r1 = new PositionAwareStreamReaderLegacy(s1, encOpts); + using ILogStreamReader r2 = new PositionAwareStreamReaderSystem(s2, encOpts); + for (var lineNum = 0; ; lineNum++) + { + var line1 = r1.ReadLine(); + var line2 = r2.ReadLine(); + if (line1 == null && line2 == null) { - string line1 = r1.ReadLine(); - string line2 = r2.ReadLine(); - if (line1 == null && line2 == null) - { - break; - } + break; + } - Assert.That(line1, Is.EqualTo(line2), "File " + fileName); + Assert.That(line1, Is.EqualTo(line2), "File " + fileName); - if (r1.Position != maxPosition) - { - Assert.That(r2.Position, Is.EqualTo(r1.Position), "Line " + lineNum + ", File: " + fileName); - } - else - { - //Its desired that the position of the new implementation is 2 bytes ahead to fix the problem of empty lines every time a new line is appended. - Assert.That(r2.Position - 2, Is.EqualTo(r1.Position), "Line " + lineNum + ", File: " + fileName); - } + if (r1.Position != maxPosition) + { + Assert.That(r2.Position, Is.EqualTo(r1.Position), "Line " + lineNum + ", File: " + fileName); + } + else + { + //Its desired that the position of the new implementation is 2 bytes ahead to fix the problem of empty lines every time a new line is appended. + Assert.That(r2.Position - 2, Is.EqualTo(r1.Position), "Line " + lineNum + ", File: " + fileName); } } - - //TODO find out why it does not work with appveyor, but works fine with normal environment! - //[Test] - //[TestCase("50 MB.txt", "Windows-1252", 50000000)] - //[TestCase("50 MB UTF16.txt", "Unicode", 49999998)] - //[TestCase("50 MB UTF8.txt", "UTF-8", 50000000)] - //public void CompareReaderImplementations(string fileName, string encoding, int maxPosition) - //{ - // CompareReaderImplementationsInternal(fileName, Encoding.GetEncoding(encoding), maxPosition); - //} } + + //TODO find out why it does not work with appveyor, but works fine with normal environment! + //[Test] + //[TestCase("50 MB.txt", "Windows-1252", 50000000)] + //[TestCase("50 MB UTF16.txt", "Unicode", 49999998)] + //[TestCase("50 MB UTF8.txt", "UTF-8", 50000000)] + //public void CompareReaderImplementations(string fileName, string encoding, int maxPosition) + //{ + // CompareReaderImplementationsInternal(fileName, Encoding.GetEncoding(encoding), maxPosition); + //} } \ No newline at end of file diff --git a/src/LogExpert.Tests/RollingNameTest.cs b/src/LogExpert.Tests/RollingNameTest.cs index 51fd14cb..a85f94b4 100644 --- a/src/LogExpert.Tests/RollingNameTest.cs +++ b/src/LogExpert.Tests/RollingNameTest.cs @@ -1,68 +1,68 @@ -using LogExpert.Classes.Log; +using LogExpert.Core.Classes.Log; + using NUnit.Framework; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +[TestFixture] +internal class RollingNameTest { - [TestFixture] - internal class RollingNameTest + [Test] + [TestCase("engine_2010-06-12_0.log", "*$D(yyyy-MM-dd)_$I.log")] + [TestCase("engine_2010-06-12.log", "*$D(yyyy-MM-dd).log")] + [TestCase("engine_0.log", "*_$I.log")] + [TestCase("engine.log","*.log$J(.)")] + [TestCase("engine.log","engine$J.log")] + [TestCase("engine1.log","engine$J.log")] + [TestCase("engine.log", "*$J(.)")] + [TestCase("engine_2010-06-12.log", "*$D(yyyy-MM-dd).log$J(.)")] + public void TestFilename1(string expectedResult, string formatString) { - [Test] - [TestCase("engine_2010-06-12_0.log", "*$D(yyyy-MM-dd)_$I.log")] - [TestCase("engine_2010-06-12.log", "*$D(yyyy-MM-dd).log")] - [TestCase("engine_0.log", "*_$I.log")] - [TestCase("engine.log","*.log$J(.)")] - [TestCase("engine.log","engine$J.log")] - [TestCase("engine1.log","engine$J.log")] - [TestCase("engine.log", "*$J(.)")] - [TestCase("engine_2010-06-12.log", "*$D(yyyy-MM-dd).log$J(.)")] - public void TestFilename1(string expectedResult, string formatString) - { - RolloverFilenameBuilder fnb = new(formatString); - fnb.SetFileName(expectedResult); - string name = fnb.BuildFileName(); - Assert.That(name, Is.EqualTo(expectedResult)); - } + RolloverFilenameBuilder fnb = new(formatString); + fnb.SetFileName(expectedResult); + var name = fnb.BuildFileName(); + Assert.That(name, Is.EqualTo(expectedResult)); + } - [Test] - [TestCase("engine_2010-06-12_0.log", "engine_2010-06-12_1.log", "*$D(yyyy-MM-dd)_$I.log")] - [TestCase("engine_2010-06-12.log", "engine_2010-06-12.log", "*$D(yyyy-MM-dd).log")] - [TestCase("engine_0.log", "engine_1.log","*_$I.log")] - [TestCase("engine.log", "engine.log.1","*.log$J(.)")] - [TestCase("engine.log", "engine1.log","engine$J.log")] - [TestCase("engine1.log", "engine2.log","engine$J.log")] - [TestCase("engine.log", "engine.log.1","*$J(.)")] - [TestCase("engine_2010-06-12.log", "engine_2010-06-12.log.1", "*$D(yyyy-MM-dd).log$J(.)")] - public void TestFilenameAnd1(string fileName, string expectedResult, string formatString) - { - RolloverFilenameBuilder fnb = new(formatString); - fnb.SetFileName(fileName); - fnb.Index += 1; - string name = fnb.BuildFileName(); - Assert.That(name, Is.EqualTo(expectedResult)); - } + [Test] + [TestCase("engine_2010-06-12_0.log", "engine_2010-06-12_1.log", "*$D(yyyy-MM-dd)_$I.log")] + [TestCase("engine_2010-06-12.log", "engine_2010-06-12.log", "*$D(yyyy-MM-dd).log")] + [TestCase("engine_0.log", "engine_1.log","*_$I.log")] + [TestCase("engine.log", "engine.log.1","*.log$J(.)")] + [TestCase("engine.log", "engine1.log","engine$J.log")] + [TestCase("engine1.log", "engine2.log","engine$J.log")] + [TestCase("engine.log", "engine.log.1","*$J(.)")] + [TestCase("engine_2010-06-12.log", "engine_2010-06-12.log.1", "*$D(yyyy-MM-dd).log$J(.)")] + public void TestFilenameAnd1(string fileName, string expectedResult, string formatString) + { + RolloverFilenameBuilder fnb = new(formatString); + fnb.SetFileName(fileName); + fnb.Index += 1; + var name = fnb.BuildFileName(); + Assert.That(name, Is.EqualTo(expectedResult)); + } - [Test] - [TestCase("engine.log", "engine.log.2","*$J(.)")] - [TestCase("engine.log", "engine.log.2","*.log$J(.)")] - public void TestFilenameAnd2(string fileName, string expectedResult, string formatString) - { - RolloverFilenameBuilder fnb = new(formatString); - fnb.SetFileName(fileName); - fnb.Index += 2; - string name = fnb.BuildFileName(); - Assert.That(name, Is.EqualTo(expectedResult)); - } + [Test] + [TestCase("engine.log", "engine.log.2","*$J(.)")] + [TestCase("engine.log", "engine.log.2","*.log$J(.)")] + public void TestFilenameAnd2(string fileName, string expectedResult, string formatString) + { + RolloverFilenameBuilder fnb = new(formatString); + fnb.SetFileName(fileName); + fnb.Index += 2; + var name = fnb.BuildFileName(); + Assert.That(name, Is.EqualTo(expectedResult)); + } - [Test] - [TestCase("engine1.log", "engine.log","engine$J.log")] - public void TestFilenameMinus1(string fileName, string expectedResult, string formatString) - { - RolloverFilenameBuilder fnb = new(formatString); - fnb.SetFileName(fileName); - fnb.Index -= 1; - string name = fnb.BuildFileName(); - Assert.That(name, Is.EqualTo("engine.log")); - } + [Test] + [TestCase("engine1.log", "engine.log","engine$J.log")] + public void TestFilenameMinus1(string fileName, string expectedResult, string formatString) + { + RolloverFilenameBuilder fnb = new(formatString); + fnb.SetFileName(fileName); + fnb.Index -= 1; + var name = fnb.BuildFileName(); + Assert.That(name, Is.EqualTo("engine.log")); } } \ No newline at end of file diff --git a/src/LogExpert.Tests/RolloverHandlerTest.cs b/src/LogExpert.Tests/RolloverHandlerTest.cs index 2d4d56ef..f93e4045 100644 --- a/src/LogExpert.Tests/RolloverHandlerTest.cs +++ b/src/LogExpert.Tests/RolloverHandlerTest.cs @@ -1,54 +1,56 @@ -using System; -using System.Collections.Generic; -using LogExpert.Classes.Log; -using LogExpert.Entities; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; +using LogExpert.PluginRegistry.FileSystem; + using NUnit.Framework; -namespace LogExpert.Tests +using System; +using System.Collections.Generic; + +namespace LogExpert.Tests; + +[TestFixture] +internal class RolloverHandlerTest : RolloverHandlerTestBase { - [TestFixture] - internal class RolloverHandlerTest : RolloverHandlerTestBase + [Test] + [TestCase("*$J(.)", 66)] + public void TestFilenameListWithAppendedIndex(string format, int retries) + { + MultiFileOptions options = new(); + options.FormatPattern = format; + options.MaxDayTry = retries; + + LinkedList files = CreateTestFilesWithoutDate(); + + var firstFile = files.Last.Value; + + ILogFileInfo info = new LogFileInfo(new Uri(firstFile)); + RolloverFilenameHandler handler = new(info, options); + LinkedList fileList = handler.GetNameList(PluginRegistry.PluginRegistry.Instance); + + Assert.That(fileList, Is.EqualTo(files)); + + Cleanup(); + } + + [Test] + [TestCase("*$D(YYYY-mm-DD)_$I.log", 3)] + public void TestFilenameListWithDate(string format, int retries) { - [Test] - [TestCase("*$J(.)", 66)] - public void TestFilenameListWithAppendedIndex(string format, int retries) - { - MultiFileOptions options = new(); - options.FormatPattern = format; - options.MaxDayTry = retries; - - LinkedList files = CreateTestFilesWithoutDate(); - - string firstFile = files.Last.Value; - - ILogFileInfo info = new LogFileInfo(new Uri(firstFile)); - RolloverFilenameHandler handler = new(info, options); - LinkedList fileList = handler.GetNameList(); - - Assert.That(fileList, Is.EqualTo(files)); - - Cleanup(); - } - - [Test] - [TestCase("*$D(YYYY-mm-DD)_$I.log", 3)] - public void TestFilenameListWithDate(string format, int retries) - { - MultiFileOptions options = new(); - options.FormatPattern = format; - options.MaxDayTry = retries; - - LinkedList files = CreateTestFilesWithDate(); - - string firstFile = files.Last.Value; - - ILogFileInfo info = new LogFileInfo(new Uri(firstFile)); - RolloverFilenameHandler handler = new(info, options); - LinkedList fileList = handler.GetNameList(); - - Assert.That(fileList, Is.EqualTo(files)); - - Cleanup(); - } + MultiFileOptions options = new(); + options.FormatPattern = format; + options.MaxDayTry = retries; + + LinkedList files = CreateTestFilesWithDate(); + + var firstFile = files.Last.Value; + + ILogFileInfo info = new LogFileInfo(new Uri(firstFile)); + RolloverFilenameHandler handler = new(info, options); + LinkedList fileList = handler.GetNameList(PluginRegistry.PluginRegistry.Instance); + + Assert.That(fileList, Is.EqualTo(files)); + + Cleanup(); } } \ No newline at end of file diff --git a/src/LogExpert.Tests/RolloverHandlerTestBase.cs b/src/LogExpert.Tests/RolloverHandlerTestBase.cs index d55ae47a..26a08906 100644 --- a/src/LogExpert.Tests/RolloverHandlerTestBase.cs +++ b/src/LogExpert.Tests/RolloverHandlerTestBase.cs @@ -1,104 +1,106 @@ -using System; -using System.Collections.Generic; -using System.IO; -using LogExpert.Classes.Log; +using LogExpert.Core.Classes.Log; -namespace LogExpert.Tests +namespace LogExpert.Tests; + +internal class RolloverHandlerTestBase { - internal class RolloverHandlerTestBase - { - #region Fields + #region Fields - protected const string TEST_DIR_NAME = "test"; + public const string TEST_DIR_NAME = "test"; - #endregion + #endregion + public DirectoryInfo TestDirectory { get; set; } - protected LinkedList CreateTestFilesWithDate() - { - LinkedList createdFiles = new(); - DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_1.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_0.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-10_0.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_1.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_0.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_2.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_1.log")); - createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_0.log")); - return createdFiles; - } + protected LinkedList CreateTestFilesWithDate () + { + LinkedList createdFiles = new(); + DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); + TestDirectory = dInfo; + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_1.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-08_0.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-10_0.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_1.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-11_0.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_2.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_1.log")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine_2010-06-12_0.log")); + return createdFiles; + } - protected LinkedList CreateTestFilesWithoutDate() - { - LinkedList createdFiles = new(); - DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.6")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.5")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.4")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.3")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.2")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log.1")); - createdFiles.AddLast(CreateFile(dInfo, "engine.log")); - return createdFiles; - } + protected LinkedList CreateTestFilesWithoutDate () + { + LinkedList createdFiles = new(); + DirectoryInfo dInfo = Directory.CreateDirectory(TEST_DIR_NAME); + TestDirectory = dInfo; + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.6")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.5")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.4")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.3")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.2")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log.1")); + _ = createdFiles.AddLast(CreateFile(dInfo, "engine.log")); + return createdFiles; + } + + protected LinkedList RolloverSimulation (LinkedList files, string formatPattern, + bool deleteLatestFile) + { + LinkedList fileList = files; + RolloverFilenameBuilder fnb = new(formatPattern); + fnb.SetFileName(fileList.Last.Value); + fnb.Index += fileList.Count; + var newFileName = fnb.BuildFileName(); + fileList.AddFirst(newFileName); + LinkedList.Enumerator enumerator = fileList.GetEnumerator(); + LinkedList.Enumerator nextEnumerator = fileList.GetEnumerator(); + nextEnumerator.MoveNext(); // move on 2nd entry + enumerator.MoveNext(); - protected LinkedList RolloverSimulation(LinkedList files, string formatPattern, - bool deleteLatestFile) + while (nextEnumerator.MoveNext()) { - LinkedList fileList = files; - RolloverFilenameBuilder fnb = new(formatPattern); - fnb.SetFileName(fileList.Last.Value); - fnb.Index += fileList.Count; - string newFileName = fnb.BuildFileName(); - fileList.AddFirst(newFileName); - LinkedList.Enumerator enumerator = fileList.GetEnumerator(); - LinkedList.Enumerator nextEnumerator = fileList.GetEnumerator(); - nextEnumerator.MoveNext(); // move on 2nd entry + File.Move(nextEnumerator.Current, enumerator.Current); enumerator.MoveNext(); - while (nextEnumerator.MoveNext()) - { - File.Move(nextEnumerator.Current, enumerator.Current); - enumerator.MoveNext(); - } - CreateFile(null, nextEnumerator.Current); - - if (deleteLatestFile) - { - File.Delete(fileList.First.Value); - fileList.RemoveFirst(); - } - return fileList; } + CreateFile(null, nextEnumerator.Current); - protected void Cleanup() + if (deleteLatestFile) { - try - { - Directory.Delete(TEST_DIR_NAME, true); - } - catch (Exception) - { - } + File.Delete(fileList.First.Value); + fileList.RemoveFirst(); } - protected string CreateFile(DirectoryInfo dInfo, string fileName) + return fileList; + } + + + protected void Cleanup () + { + try { - int lineCount = 10; - string fullName = dInfo == null ? fileName : dInfo.FullName + Path.DirectorySeparatorChar + fileName; + Directory.Delete(TEST_DIR_NAME, true); + } + catch (Exception) + { + } + } - using (StreamWriter writer = new(File.Create(fullName))) - { - for (int i = 1; i <= lineCount; ++i) - { - writer.WriteLine("Line number " + i.ToString("D3") + " of File " + fullName); - } + protected string CreateFile (DirectoryInfo dInfo, string fileName) + { + var lineCount = 10; + var fullName = dInfo == null ? fileName : dInfo.FullName + Path.DirectorySeparatorChar + fileName; - writer.Flush(); + using (StreamWriter writer = new(File.Create(fullName))) + { + for (var i = 1; i <= lineCount; ++i) + { + writer.WriteLine($"Line number {i:D3} of File {fullName}"); } - return fullName; + writer.Flush(); } + + return fullName; } } \ No newline at end of file diff --git a/src/LogExpert.Tests/SquareBracketColumnizerTest.cs b/src/LogExpert.Tests/SquareBracketColumnizerTest.cs index 3825e46b..2f952833 100644 --- a/src/LogExpert.Tests/SquareBracketColumnizerTest.cs +++ b/src/LogExpert.Tests/SquareBracketColumnizerTest.cs @@ -1,48 +1,42 @@ - -using LogExpert.Classes.Columnizer; -using LogExpert.Classes.Log; -using LogExpert.Entities; +using LogExpert.Core.Classes.Columnizer; +using LogExpert.Core.Classes.Log; +using LogExpert.Core.Entities; using NUnit.Framework; -using System; -using System.Collections.Generic; -using System.IO; +namespace LogExpert.Tests; -namespace LogExpert +[TestFixture] +public class SquareBracketColumnizerTest { - [TestFixture] - public class SquareBracketColumnizerTest + [TestCase(@".\TestData\SquareBracketColumnizerTest_01.txt", 5)] + [TestCase(@".\TestData\SquareBracketColumnizerTest_02.txt", 5)] + [TestCase(@".\TestData\SquareBracketColumnizerTest_03.txt", 6)] + [TestCase(@".\TestData\SquareBracketColumnizerTest_05.txt", 3)] + public void GetPriority_HappyFile_ColumnCountMatches (string fileName, int count) { - [TestCase(@".\TestData\SquareBracketColumnizerTest_01.txt", 5)] - [TestCase(@".\TestData\SquareBracketColumnizerTest_02.txt", 5)] - [TestCase(@".\TestData\SquareBracketColumnizerTest_03.txt", 6)] - [TestCase(@".\TestData\SquareBracketColumnizerTest_05.txt", 3)] - public void GetPriority_HappyFile_ColumnCountMatches(string fileName, int count) - { - SquareBracketColumnizer squareBracketColumnizer = new(); - string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - - LogfileReader logFileReader = new(path, new EncodingOptions(), true, 40, 50, new MultiFileOptions()); - logFileReader.ReadFiles(); - List loglines = new() - { - // Sampling a few lines to select the correct columnizer - logFileReader.GetLogLine(0), - logFileReader.GetLogLine(1), - logFileReader.GetLogLine(2), - logFileReader.GetLogLine(3), - logFileReader.GetLogLine(4), - logFileReader.GetLogLine(5), - logFileReader.GetLogLine(25), - logFileReader.GetLogLine(100), - logFileReader.GetLogLine(200), - logFileReader.GetLogLine(400) - }; + SquareBracketColumnizer squareBracketColumnizer = new(); + var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); - squareBracketColumnizer.GetPriority(path, loglines); - Assert.That(count, Is.EqualTo(squareBracketColumnizer.GetColumnCount())); - } + LogfileReader logFileReader = new(path, new EncodingOptions(), false, 40, 50, new MultiFileOptions(), PluginRegistry.PluginRegistry.Instance); + logFileReader.ReadFiles(); + List loglines = new() + { + // Sampling a few lines to select the correct columnizer + logFileReader.GetLogLine(0), + logFileReader.GetLogLine(1), + logFileReader.GetLogLine(2), + logFileReader.GetLogLine(3), + logFileReader.GetLogLine(4), + logFileReader.GetLogLine(5), + logFileReader.GetLogLine(25), + logFileReader.GetLogLine(100), + logFileReader.GetLogLine(200), + logFileReader.GetLogLine(400) + }; + squareBracketColumnizer.GetPriority(path, loglines); + Assert.That(count, Is.EqualTo(squareBracketColumnizer.GetColumnCount())); } + } \ No newline at end of file diff --git a/src/LogExpert/Dialogs/BufferedDataGridView.Designer.cs b/src/LogExpert.UI/Controls/BufferedDataGridView.Designer.cs similarity index 88% rename from src/LogExpert/Dialogs/BufferedDataGridView.Designer.cs rename to src/LogExpert.UI/Controls/BufferedDataGridView.Designer.cs index 73c2d006..f4908a0f 100644 --- a/src/LogExpert/Dialogs/BufferedDataGridView.Designer.cs +++ b/src/LogExpert.UI/Controls/BufferedDataGridView.Designer.cs @@ -1,36 +1,35 @@ -namespace LogExpert.Dialogs -{ - partial class BufferedDataGridView - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - } - - #endregion - } -} +namespace LogExpert.Dialogs; + +partial class BufferedDataGridView +{ + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/BufferedDataGridView.cs b/src/LogExpert.UI/Controls/BufferedDataGridView.cs new file mode 100644 index 00000000..563cacdd --- /dev/null +++ b/src/LogExpert.UI/Controls/BufferedDataGridView.cs @@ -0,0 +1,336 @@ +using System.Drawing.Drawing2D; +using System.Globalization; +using System.Runtime.Versioning; + +using LogExpert.Core.Entities; +using LogExpert.Core.EventArguments; +using LogExpert.UI.Controls; + +using NLog; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class BufferedDataGridView : DataGridView +{ + #region Fields + + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + private readonly Brush _brush; + + 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)); //dark blue + + private BookmarkOverlay _draggedOverlay; + private Point _dragStartPoint; + private bool _isDrag; + private Size _oldOverlayOffset; + + #endregion + + #region cTor + + public BufferedDataGridView () + { + _pen = new Pen(_bubbleColor, (float)3.0); + _brush = new SolidBrush(_bubbleColor); + + InitializeComponent(); + DoubleBuffered = true; + VirtualMode = true; + } + + #endregion + + #region Events + + public event EventHandler OverlayDoubleClicked; + + #endregion + + #region Properties + + /* + public Graphics Buffer + { + get { return this.myBuffer.Graphics; } + } + */ + + public ContextMenuStrip EditModeMenuStrip { get; set; } + + public bool PaintWithOverlays { get; set; } + + #endregion + + #region Public methods + + public void AddOverlay (BookmarkOverlay overlay) + { + lock (_overlayList) + { + _overlayList.Add(overlay.Position.Y, overlay); + } + } + + #endregion + + #region Overrides + + protected override void OnPaint (PaintEventArgs e) + { + try + { + if (PaintWithOverlays) + { + PaintOverlays(e); + } + else + { + base.OnPaint(e); + } + } + catch (Exception ex) + { + _logger.Error(ex); + } + } + + protected override void OnEditingControlShowing (DataGridViewEditingControlShowingEventArgs e) + { + base.OnEditingControlShowing(e); + e.Control.KeyDown -= OnControlKeyDown; + e.Control.KeyDown += OnControlKeyDown; + var editControl = (DataGridViewTextBoxEditingControl)e.Control; + e.Control.PreviewKeyDown -= OnControlPreviewKeyDown; + e.Control.PreviewKeyDown += OnControlPreviewKeyDown; + + editControl.ContextMenuStrip = EditModeMenuStrip; + } + + protected override void OnMouseDown (MouseEventArgs e) + { + var overlay = GetOverlayForPosition(e.Location); + if (overlay != null) + { + if (e.Button == MouseButtons.Right) + { + if (_isDrag) + { + _isDrag = false; + overlay.Bookmark.OverlayOffset = _oldOverlayOffset; + Refresh(); + } + } + else + { + _dragStartPoint = e.Location; + _isDrag = true; + _draggedOverlay = overlay; + _oldOverlayOffset = overlay.Bookmark.OverlayOffset; + } + } + else + { + _isDrag = false; + base.OnMouseDown(e); + } + } + + protected override void OnMouseUp (MouseEventArgs e) + { + if (_isDrag) + { + _isDrag = false; + Refresh(); + } + else + { + base.OnMouseUp(e); + } + } + + protected override void OnMouseMove (MouseEventArgs e) + { + if (_isDrag) + { + Cursor = Cursors.Hand; + Size offset = new(e.X - _dragStartPoint.X, e.Y - _dragStartPoint.Y); + _draggedOverlay.Bookmark.OverlayOffset = _oldOverlayOffset + offset; + Refresh(); + } + else + { + var overlay = GetOverlayForPosition(e.Location); + Cursor = overlay != null ? Cursors.Hand : Cursors.Default; + base.OnMouseMove(e); + } + } + + protected override void OnMouseDoubleClick (MouseEventArgs e) + { + var overlay = GetOverlayForPosition(e.Location); + if (overlay != null) + { + if (e.Button == MouseButtons.Left) + { + OnOverlayDoubleClicked(new OverlayEventArgs(overlay)); + } + } + else + { + base.OnMouseDoubleClick(e); + } + } + + #endregion + + #region Private Methods + + private BookmarkOverlay GetOverlayForPosition (Point pos) + { + lock (_overlayList) + { + foreach (var overlay in _overlayList.Values) + { + if (overlay.BubbleRect.Contains(pos)) + { + return overlay; + } + } + } + + return null; + } + + private void PaintOverlays (PaintEventArgs e) + { + var currentContext = BufferedGraphicsManager.Current; + + using var myBuffer = currentContext.Allocate(CreateGraphics(), ClientRectangle); + lock (_overlayList) + { + _overlayList.Clear(); + } + + myBuffer.Graphics.SetClip(ClientRectangle, CombineMode.Union); + e.Graphics.SetClip(ClientRectangle, CombineMode.Union); + + PaintEventArgs args = new(myBuffer.Graphics, e.ClipRectangle); + + base.OnPaint(args); + + StringFormat format = new() + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Near + }; + + myBuffer.Graphics.SetClip(DisplayRectangle, CombineMode.Intersect); + + // Remove Columnheader from Clippingarea + Rectangle rectTableHeader = new(DisplayRectangle.X, DisplayRectangle.Y, DisplayRectangle.Width, ColumnHeadersHeight); + myBuffer.Graphics.SetClip(rectTableHeader, CombineMode.Exclude); + + //e.Graphics.SetClip(rect, CombineMode.Union); + + lock (_overlayList) + { + foreach (var overlay in _overlayList.Values) + { + 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); + rectBubble.Location += overlay.Bookmark.OverlayOffset; + overlay.BubbleRect = rectBubble; + myBuffer.Graphics.SetClip(rectBubble, CombineMode.Union); // Bubble to clip + myBuffer.Graphics.SetClip(rectTableHeader, CombineMode.Exclude); + e.Graphics.SetClip(rectBubble, CombineMode.Union); + RectangleF textRect = new(rectBubble.X, rectBubble.Y, rectBubble.Width, rectBubble.Height); + myBuffer.Graphics.FillRectangle(_brush, rectBubble); + //myBuffer.Graphics.DrawLine(_pen, overlay.Position, new Point(rect.X, rect.Y + rect.Height / 2)); + myBuffer.Graphics.DrawLine(_pen, overlay.Position, new Point(rectBubble.X, rectBubble.Y + rectBubble.Height)); + myBuffer.Graphics.DrawString(overlay.Bookmark.Text, _font, _textBrush, textRect, format); + + if (_logger.IsDebugEnabled) + { + _logger.Debug(CultureInfo.InvariantCulture, $"ClipRgn: {myBuffer.Graphics.ClipBounds.Left},{myBuffer.Graphics.ClipBounds.Top},{myBuffer.Graphics.ClipBounds.Width},{myBuffer.Graphics.ClipBounds.Height}"); + } + } + } + + myBuffer.Render(e.Graphics); + } + + #endregion + + #region Events handler + + private void OnControlPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) + { + if ((e.KeyCode == Keys.C || e.KeyCode == Keys.Insert) && e.Control) + { + if (EditingControl != null) + { + e.IsInputKey = true; + } + } + } + + private void OnControlKeyDown (object sender, KeyEventArgs e) + { + if (e.KeyCode is Keys.Up or Keys.Down) + { + if (EditingControl != null) + { + if (EditingControl is LogCellEditingControl editControl) + { + _ = editControl.EditingControlDataGridView.EndEdit(); + var line = editControl.EditingControlDataGridView.CurrentCellAddress.Y; + if (e.KeyCode == Keys.Up) + { + if (line > 0) + { + line--; + } + } + + if (e.KeyCode == Keys.Down) + { + if (line < editControl.EditingControlDataGridView.RowCount - 1) + { + line++; + } + } + + var col = editControl.EditingControlDataGridView.CurrentCellAddress.X; + var scrollIndex = editControl.EditingControlDataGridView.HorizontalScrollingOffset; + var selStart = editControl.SelectionStart; + editControl.EditingControlDataGridView.CurrentCell = editControl.EditingControlDataGridView.Rows[line].Cells[col]; + _ = editControl.EditingControlDataGridView.BeginEdit(false); + editControl.SelectionStart = selStart; + editControl.ScrollToCaret(); + editControl.EditingControlDataGridView.HorizontalScrollingOffset = scrollIndex; + e.Handled = true; + } + else + { + _logger.Warn(CultureInfo.InvariantCulture, "Edit control was null, to be checked"); + } + } + } + } + + protected virtual void OnOverlayDoubleClicked (OverlayEventArgs e) + { + OverlayDoubleClicked?.Invoke(this, e); + } + + #endregion +} diff --git a/src/LogExpert.UI/Controls/ColorComboBox.cs b/src/LogExpert.UI/Controls/ColorComboBox.cs new file mode 100644 index 00000000..3827b7fe --- /dev/null +++ b/src/LogExpert.UI/Controls/ColorComboBox.cs @@ -0,0 +1,102 @@ +using System.Drawing.Drawing2D; +using System.Runtime.Versioning; + +namespace LogExpert.UI.Controls; + +[SupportedOSPlatform("windows")] +internal class ColorComboBox : ComboBox +{ + #region Fields + + private Color _customColor = Color.FromKnownColor(KnownColor.Black); + + #endregion + + #region cTor + + public ColorComboBox () + { + DrawMode = DrawMode.OwnerDrawFixed; + DrawItem += OnColorComboBoxDrawItem; + if (!DesignMode) + { + 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 + ] + ); + } + } + + #endregion + + #region Properties + + public Color CustomColor + { + get => _customColor; + set + { + _customColor = value; + Items.RemoveAt(0); + Items.Insert(0, _customColor); + } + } + + public Color SelectedColor => (Color)(SelectedIndex != -1 ? Items[SelectedIndex] : null); + + #endregion + + #region Events handler + + private void OnColorComboBoxDrawItem (object sender, DrawItemEventArgs e) + { + e.DrawBackground(); + if (e.Index >= 0) + { + Rectangle rectangle = new(4, e.Bounds.Top + 2, 30, e.Bounds.Height - 4); + var rectColor = (Color)Items[e.Index]; + e.Graphics.FillRectangle(new SolidBrush(rectColor), rectangle); + e.Graphics.DrawRectangle(Pens.Black, rectangle); + + if (e.Index == 0) + { + e.Graphics.DrawString("Custom", e.Font, Brushes.Black, + new PointF(42, e.Bounds.Top + 2)); + } + else + { + e.Graphics.DrawString(((Color)Items[e.Index]).Name, e.Font, Brushes.Black, + new PointF(42, e.Bounds.Top + 2)); + } + + if (!Enabled) + { + HatchBrush brush = new(HatchStyle.Percent50, Color.LightGray, Color.FromArgb(10, Color.LightGray)); + rectangle.Inflate(1, 1); + e.Graphics.FillRectangle(brush, rectangle); + brush.Dispose(); + } + e.DrawFocusRectangle(); + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/DateTimeDragControl.Designer.cs b/src/LogExpert.UI/Controls/DateTimeDragControl.Designer.cs similarity index 96% rename from src/LogExpert/Dialogs/DateTimeDragControl.Designer.cs rename to src/LogExpert.UI/Controls/DateTimeDragControl.Designer.cs index 9a769909..8f98bac0 100644 --- a/src/LogExpert/Dialogs/DateTimeDragControl.Designer.cs +++ b/src/LogExpert.UI/Controls/DateTimeDragControl.Designer.cs @@ -1,46 +1,46 @@ -namespace LogExpert.Dialogs -{ - partial class DateTimeDragControl - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.SuspendLayout(); - // - // DateTimeDragControl - // - this.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.Name = "DateTimeDragControl"; - this.Size = new System.Drawing.Size(142, 57); - this.Load += new System.EventHandler(this.DateTimeDragControl_Load); - this.MouseLeave += new System.EventHandler(this.DateTimeDragControl_MouseLeave); - this.Resize += new System.EventHandler(this.DateTimeDragControl_Resize); - this.ResumeLayout(false); - } - - #endregion - } -} +namespace LogExpert.Dialogs +{ + partial class DateTimeDragControl + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.SuspendLayout(); + // + // DateTimeDragControl + // + this.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.Name = "DateTimeDragControl"; + this.Size = new System.Drawing.Size(142, 57); + this.Load += new System.EventHandler(this.DateTimeDragControl_Load); + this.MouseLeave += new System.EventHandler(this.DateTimeDragControl_MouseLeave); + this.Resize += new System.EventHandler(this.DateTimeDragControl_Resize); + this.ResumeLayout(false); + } + + #endregion + } +} diff --git a/src/LogExpert.UI/Controls/DateTimeDragControl.cs b/src/LogExpert.UI/Controls/DateTimeDragControl.cs new file mode 100644 index 00000000..cd804dff --- /dev/null +++ b/src/LogExpert.UI/Controls/DateTimeDragControl.cs @@ -0,0 +1,514 @@ +using System.ComponentModel; +using System.Data; +using System.Globalization; +using System.Runtime.Versioning; + +using LogExpert.Core.Classes.DateTimeParser; +using LogExpert.Core.Enums; + +namespace LogExpert.Dialogs; + +/// +/// This control displays date and time and allows user to interact with the individual parts using the mouse +/// to increment and decrement the values. The date format displayed is derived from the application UI locale. +/// We currently support only three: US (mm/dd/yyyy), French (yyyy-mm-dd) and German (dd.mm.yyyy). +/// The control raises events (ValueChanged, ValueDragged) when the date/time changes so that owner can react accordingly. +/// +[SupportedOSPlatform("windows")] +internal partial class DateTimeDragControl : UserControl +{ + #region Fields + + private const int NO_DIGIT_DRAGGED = -1; + private int _addedValue; + + + private DateTime _dateTime; + private readonly IList _digitRects = []; + + private readonly StringFormat _digitsFormat = new(); + private int _draggedDigit; + + private DragOrientationsEnum _dragOrientation = DragOrientationsEnum.Vertical; + + private readonly ToolStripItem toolStripItemHorizontalDrag = new ToolStripMenuItem(); + private readonly ToolStripItem toolStripItemVerticalDrag = new ToolStripMenuItem(); + private readonly ToolStripItem toolStripItemVerticalInvertedDrag = new ToolStripMenuItem(); + + private int _oldValue; + + private string[] _dateParts; + + private int _startMouseX; + private int _startMouseY; + + #endregion + + #region cTor + + /// + /// Default Constructor + /// + public DateTimeDragControl () + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + _digitsFormat.LineAlignment = StringAlignment.Center; + _digitsFormat.Alignment = StringAlignment.Near; + _digitsFormat.Trimming = StringTrimming.None; + _digitsFormat.FormatFlags = StringFormatFlags.FitBlackBox | StringFormatFlags.NoClip | StringFormatFlags.NoWrap; + + _draggedDigit = NO_DIGIT_DRAGGED; + } + + #endregion + + #region Delegates + + public delegate void ValueChangedEventHandler (object sender, EventArgs e); + + public delegate void ValueDraggedEventHandler (object sender, EventArgs e); + + #endregion + + #region Events + + public event ValueChangedEventHandler ValueChanged; + public event ValueDraggedEventHandler ValueDragged; + + #endregion + + #region Properties + + public DateTime MinDateTime { get; set; } = DateTime.MinValue; + + public DateTime MaxDateTime { get; set; } = DateTime.MaxValue; + + public DragOrientationsEnum DragOrientation + { + get => _dragOrientation; + set + { + _dragOrientation = value; + UpdateContextMenu(); + } + } + + public Color HoverColor { get; set; } + + public DateTime DateTime + { + get => _dateTime.Subtract(TimeSpan.FromMilliseconds(_dateTime.Millisecond)); + set + { + _dateTime = value; + + if (_dateTime < MinDateTime) + { + _dateTime = MinDateTime; + } + if (_dateTime > MaxDateTime) + { + _dateTime = MaxDateTime; + } + } + } + + #endregion + + #region Private Methods + + // Returns the index of the rectangle (digitRects) under the mouse cursor + private int DetermineDraggedDigit (MouseEventArgs e) + { + for (var i = 0; i < _digitRects.Count; ++i) + { + if (_digitRects[i].Contains(e.Location) && Token.IsDatePart(_dateParts[i])) + { + return i; + } + } + + return NO_DIGIT_DRAGGED; + } + + // Return the value corresponding to current dragged digit + private int GetDraggedValue () + { + var datePart = _dateParts[_draggedDigit]; + + if (datePart.StartsWith('y')) + { + return _dateTime.Year; + } + + if (datePart.StartsWith('M')) + { + return _dateTime.Month; + } + + if (datePart.StartsWith('d')) + { + return _dateTime.Day; + } + + if (datePart.StartsWith('h')) + { + return _dateTime.Hour; + } + + if (datePart.StartsWith('m')) + { + return _dateTime.Minute; + } + + return datePart.StartsWith('s') + ? _dateTime.Second + : NO_DIGIT_DRAGGED; + } + + private bool SetDraggedValue (int delta) + { + if (_draggedDigit == NO_DIGIT_DRAGGED) + { + return false; + } + + var changed = true; + try + { + var datePart = _dateParts[_draggedDigit]; + + if (datePart.StartsWith('y')) + { + _dateTime = _dateTime.AddYears(delta); + } + else if (datePart.StartsWith('M')) + { + _dateTime = _dateTime.AddMonths(delta); + } + else if (datePart.StartsWith('d')) + { + _dateTime = _dateTime.AddDays(delta); + } + else if (datePart.StartsWith('h')) + { + _dateTime = _dateTime.AddHours(delta); + } + else if (datePart.StartsWith('m')) + { + _dateTime = _dateTime.AddMinutes(delta); + } + else if (datePart.StartsWith('s')) + { + _dateTime = _dateTime.AddSeconds(delta); + } + } + catch (Exception) + { + // invalid value dragged + } + + if (_dateTime > MaxDateTime) + { + _dateTime = MaxDateTime; + changed = false; + } + + if (_dateTime < MinDateTime) + { + _dateTime = MinDateTime; + changed = false; + } + + return changed; + } + + private void InitCustomRects (Section dateSection) + { + _dateParts = dateSection + .GeneralTextDateDurationParts + .Select(DateFormatPartAdjuster.AdjustDateTimeFormatPart) + .ToArray(); + + var oneCharWidth = ClientRectangle.Width / _dateParts.Sum(s => s.Length); + var left = ClientRectangle.Left; + + _digitRects.Clear(); + + foreach (var datePart in _dateParts) + { + var s = datePart.Length * oneCharWidth; + _digitRects.Add(new Rectangle(left, ClientRectangle.Top, s, ClientRectangle.Height)); + left += s; + } + + } + + private void InitDigitRects () + { + CultureInfo culture = CultureInfo.CurrentCulture; + + var datePattern = string.Concat(culture.DateTimeFormat.ShortDatePattern, " ", culture.DateTimeFormat.LongTimePattern); + + List
sections = Parser.ParseSections(datePattern, out _); + Section dateSection = sections.FirstOrDefault(); + + if (dateSection == null) + { + sections = Parser.ParseSections("dd.MM.yyyy HH:mm:ss", out var _); + dateSection = sections.Single(); + } + + InitCustomRects(dateSection); + } + + #endregion + + #region Events handler + + private void DateTimeDragControl_Load (object sender, EventArgs e) + { + InitDigitRects(); + + BuildContextualMenu(); + } + + #endregion + + protected void OnValueChanged (EventArgs e) + { + ValueChanged?.Invoke(this, e); + } + + protected void OnValueDragged (EventArgs e) + { + ValueDragged?.Invoke(this, e); + } + + #region Contextual Menu + + private void BuildContextualMenu () + { + ContextMenuStrip = new ContextMenuStrip + { + Name = "Timestamp selector" + }; + + ContextMenuStrip.Items.Add(toolStripItemHorizontalDrag); + ContextMenuStrip.Items.Add(toolStripItemVerticalDrag); + ContextMenuStrip.Items.Add(toolStripItemVerticalInvertedDrag); + + toolStripItemHorizontalDrag.Click += OnToolStripItemHorizontalDragClick; + toolStripItemHorizontalDrag.Text = "Drag horizontal"; + + toolStripItemVerticalDrag.Click += OnToolStripItemVerticalDragClick; + toolStripItemVerticalDrag.Text = "Drag vertical"; + + toolStripItemVerticalInvertedDrag.Click += OnToolStripItemVerticalInvertedDragClick; + toolStripItemVerticalInvertedDrag.Text = "Drag vertical inverted"; + + ContextMenuStrip.Opening += OnContextMenuStripOpening; + + UpdateContextMenu(); + } + + private void UpdateContextMenu () + { + toolStripItemHorizontalDrag.Enabled = DragOrientation != DragOrientationsEnum.Horizontal; + toolStripItemVerticalDrag.Enabled = DragOrientation != DragOrientationsEnum.Vertical; + toolStripItemVerticalInvertedDrag.Enabled = DragOrientation != DragOrientationsEnum.InvertedVertical; + } + + private void OnContextMenuStripOpening (object sender, CancelEventArgs e) + { + if (Capture) + { + e.Cancel = true; + } + } + + private void OnToolStripItemHorizontalDragClick (object sender, EventArgs e) + { + DragOrientation = DragOrientationsEnum.Horizontal; + toolStripItemHorizontalDrag.Enabled = false; + toolStripItemVerticalDrag.Enabled = true; + toolStripItemVerticalInvertedDrag.Enabled = true; + } + + private void OnToolStripItemVerticalDragClick (object sender, EventArgs e) + { + DragOrientation = DragOrientationsEnum.Vertical; + toolStripItemHorizontalDrag.Enabled = true; + toolStripItemVerticalDrag.Enabled = false; + toolStripItemVerticalInvertedDrag.Enabled = true; + } + + private void OnToolStripItemVerticalInvertedDragClick (object sender, EventArgs e) + { + DragOrientation = DragOrientationsEnum.InvertedVertical; + toolStripItemHorizontalDrag.Enabled = true; + toolStripItemVerticalDrag.Enabled = true; + toolStripItemVerticalInvertedDrag.Enabled = false; + } + + #endregion + + #region Rendering + + protected override void OnPaint (PaintEventArgs e) + { + base.OnPaint(e); + + // Show what digit is dragged + using (Brush hoverBrush = new SolidBrush(HoverColor)) + { + if (_draggedDigit != NO_DIGIT_DRAGGED) + { + e.Graphics.FillRectangle(hoverBrush, _digitRects[_draggedDigit]); + } + } + + // Display current value with user-defined date format and fixed time format ("HH:mm:ss") + using Brush brush = new SolidBrush(Color.Black); + for (var i = 0; i < _dateParts.Length; i++) + { + var datePart = _dateParts[i]; + Rectangle rect = _digitRects[i]; + string value; + + if (Token.IsDatePart(datePart)) + { + try + { + value = _dateTime.ToString("-" + datePart + "-"); + value = value[1..^1]; + } + catch + { + value = datePart; + } + } + else + { + value = datePart; + } + + e.Graphics.DrawString(value, Font, brush, rect, _digitsFormat); + } + } + + private void DateTimeDragControl_Resize (object sender, EventArgs e) + { + InitDigitRects(); + } + + #endregion + + #region Mouse callbacks + + protected override void OnMouseDown (MouseEventArgs e) + { + base.OnMouseDown(e); + + if (e.Button == MouseButtons.Left) + { + _draggedDigit = DetermineDraggedDigit(e); + if (_draggedDigit == NO_DIGIT_DRAGGED) + { + return; + } + + Capture = true; + _startMouseY = e.Y; + _startMouseX = e.X; + _oldValue = GetDraggedValue(); + _addedValue = 0; + } + else if (e.Button == MouseButtons.Right && Capture) + { + Capture = false; + SetDraggedValue(0); //undo + } + + Invalidate(); // repaint with the selected item (or none) + } + + protected override void OnMouseUp (MouseEventArgs e) + { + if (!Capture) + { + return; + } + + base.OnMouseUp(e); + + Capture = false; + _draggedDigit = NO_DIGIT_DRAGGED; + Invalidate(); // repaint without the selected item + + OnValueChanged(EventArgs.Empty); + } + + protected override void OnMouseMove (MouseEventArgs e) + { + base.OnMouseMove(e); + + if (!Capture) + { + return; + } + + int diff; + switch (DragOrientation) + { + case DragOrientationsEnum.Vertical: + { + diff = _startMouseY - e.Y; + break; + } + case DragOrientationsEnum.InvertedVertical: + { + diff = _startMouseY + e.Y; + break; + } + default: + { + diff = e.X - _startMouseX; + break; + } + } + + var delta = (diff / 5) - _addedValue; // one unit per 5 pixels move + + if (delta == 0) + { + return; + } + + if (SetDraggedValue(delta)) + { + _addedValue += delta; + } + + Invalidate(); + + OnValueDragged(EventArgs.Empty); + } + + private void DateTimeDragControl_MouseLeave (object sender, EventArgs e) + { + if (Capture) + { + return; + } + + _draggedDigit = NO_DIGIT_DRAGGED; + Refresh(); + } + + #endregion +} diff --git a/src/LogExpert/Dialogs/DateTimeDragControl.resx b/src/LogExpert.UI/Controls/DateTimeDragControl.resx similarity index 97% rename from src/LogExpert/Dialogs/DateTimeDragControl.resx rename to src/LogExpert.UI/Controls/DateTimeDragControl.resx index ff31a6db..19dc0dd8 100644 --- a/src/LogExpert/Dialogs/DateTimeDragControl.resx +++ b/src/LogExpert.UI/Controls/DateTimeDragControl.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/KnobControl.Designer.cs b/src/LogExpert.UI/Controls/KnobControl.Designer.cs new file mode 100644 index 00000000..74a54cb3 --- /dev/null +++ b/src/LogExpert.UI/Controls/KnobControl.Designer.cs @@ -0,0 +1,42 @@ +namespace LogExpert.UI.Controls; + +partial class KnobControl +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Component Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.SuspendLayout(); + // + // KnobControl + // + this.Name = "KnobControl"; + this.Size = new System.Drawing.Size(21, 21); + this.ResumeLayout(false); + +} + +#endregion +} diff --git a/src/LogExpert.UI/Controls/KnobControl.cs b/src/LogExpert.UI/Controls/KnobControl.cs new file mode 100644 index 00000000..6aec9072 --- /dev/null +++ b/src/LogExpert.UI/Controls/KnobControl.cs @@ -0,0 +1,180 @@ +using NLog; + +using System.Globalization; +using System.Runtime.Versioning; + +namespace LogExpert.UI.Controls; + +[SupportedOSPlatform("windows")] +internal partial class KnobControl : UserControl +{ + #region Fields + + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + + + private readonly StringFormat _stringFormat = new(); + + private bool _isShiftPressed; + + private int _oldValue; + private int _startMouseY; + private int _value; + + #endregion + + #region cTor + + public KnobControl() + { + InitializeComponent(); + _stringFormat.LineAlignment = StringAlignment.Far; + _stringFormat.Alignment = StringAlignment.Center; + } + + #endregion + + #region Delegates + + public delegate void ValueChangedEventHandler(object sender, EventArgs e); + + #endregion + + #region Events + + public event ValueChangedEventHandler ValueChanged; + + #endregion + + #region Properties + + public int MinValue { get; set; } + + public int MaxValue { get; set; } + + public int Value + { + get => _value; + set + { + _value = value; + Refresh(); + } + } + + + public int Range => MaxValue - MinValue; + + public int DragSensitivity { get; set; } = 3; + + #endregion + + #region Overrides + + protected override void OnPaint(PaintEventArgs e) + { + base.OnPaint(e); + + Color foregroundColor = Enabled ? Color.Black : Color.Gray; + + Pen blackPen = new(foregroundColor, 1); + Pen greyPen = new(Color.Gray, 1); + + Rectangle rect = ClientRectangle; + var height = Font.Height + 3; + if (height > rect.Height) + { + height = rect.Height + 3; + } + rect.Inflate(-1, -height / 2); + rect.Offset(0, -height / 2); + e.Graphics.DrawEllipse(greyPen, rect); + + //rect = this.ClientRectangle; + rect.Inflate(-2, -2); + + var startAngle = 135.0F + 270F * ((float)_value / (float)Range); + var sweepAngle = 0.1F; + e.Graphics.DrawPie(blackPen, rect, startAngle, sweepAngle); + + Brush brush = new SolidBrush(foregroundColor); + RectangleF rectF = new(0, 0, ClientRectangle.Width, ClientRectangle.Height); + e.Graphics.DrawString("" + _value, Font, brush, rectF, _stringFormat); + + blackPen.Dispose(); + greyPen.Dispose(); + brush.Dispose(); + } + + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + + if (e.Button == MouseButtons.Left) + { + Capture = true; + _startMouseY = e.Y; + _oldValue = Value; + } + if (e.Button == MouseButtons.Right) + { + Capture = false; + Value = _oldValue; + Invalidate(); + } + } + + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + Capture = false; + _oldValue = Value; + OnValueChanged(new EventArgs()); + } + + protected void OnValueChanged(EventArgs e) + { + ValueChanged?.Invoke(this, e); + } + + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + if (!Capture) + { + return; + } + + var sense = _isShiftPressed ? DragSensitivity * 2 : DragSensitivity; + + var diff = _startMouseY - e.Y; + _logger.Debug(CultureInfo.InvariantCulture, "KnobDiff: {0}", diff); + var range = MaxValue - MinValue; + _value = _oldValue + diff / sense; + + if (_value < MinValue) + { + _value = MinValue; + } + + if (_value > MaxValue) + { + _value = MaxValue; + } + Invalidate(); + } + + protected override void OnKeyDown(KeyEventArgs e) + { + _isShiftPressed = e.Shift; + base.OnKeyDown(e); + } + + protected override void OnKeyUp(KeyEventArgs e) + { + _isShiftPressed = e.Shift; + base.OnKeyUp(e); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Controls/KnobControl.resx b/src/LogExpert.UI/Controls/KnobControl.resx similarity index 97% rename from src/LogExpert/Controls/KnobControl.resx rename to src/LogExpert.UI/Controls/KnobControl.resx index ff31a6db..19dc0dd8 100644 --- a/src/LogExpert/Controls/KnobControl.resx +++ b/src/LogExpert.UI/Controls/KnobControl.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogCellEditingControl.cs b/src/LogExpert.UI/Controls/LogCellEditingControl.cs new file mode 100644 index 00000000..024bd30c --- /dev/null +++ b/src/LogExpert.UI/Controls/LogCellEditingControl.cs @@ -0,0 +1,31 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Controls; + +[SupportedOSPlatform("windows")] +internal class LogCellEditingControl : DataGridViewTextBoxEditingControl +{ + #region Public methods + + public override bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey) + { + switch (key & Keys.KeyCode) + { + case Keys.Left: + case Keys.Up: + case Keys.Down: + case Keys.Right: + case Keys.Home: + case Keys.End: + case Keys.PageDown: + case Keys.PageUp: + { + return true; + } + } + + return !dataGridViewWantsInputKey; + } + + #endregion +} diff --git a/src/LogExpert.UI/Controls/LogGridCell.cs b/src/LogExpert.UI/Controls/LogGridCell.cs new file mode 100644 index 00000000..e9954a17 --- /dev/null +++ b/src/LogExpert.UI/Controls/LogGridCell.cs @@ -0,0 +1,13 @@ +using System; +using System.Windows.Forms; + +namespace LogExpert.UI.Controls; + +internal class LogGridCell : DataGridViewTextBoxCell +{ + #region Properties + + public override Type EditType => typeof(LogCellEditingControl); + + #endregion +} diff --git a/src/LogExpert.UI/Controls/LogTabControl.cs b/src/LogExpert.UI/Controls/LogTabControl.cs new file mode 100644 index 00000000..611d9fe5 --- /dev/null +++ b/src/LogExpert.UI/Controls/LogTabControl.cs @@ -0,0 +1,42 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Controls; + +[SupportedOSPlatform("windows")] +internal class LogTabControl : TabControl +{ + #region Fields + + private BufferedGraphics myBuffer; + + #endregion + + #region cTor + + public LogTabControl() : base() + { + //SetStyle(ControlStyles.AllPaintingInWmPaint, true); + //SetStyle(ControlStyles.UserPaint, true); + //SetStyle(ControlStyles.DoubleBuffer, true); + } + + #endregion + + #region Overrides + + protected override void OnPaint(PaintEventArgs e) + { + BufferedGraphicsContext currentContext; + currentContext = BufferedGraphicsManager.Current; + myBuffer = currentContext.Allocate(CreateGraphics(), DisplayRectangle); + + PaintEventArgs args = new(myBuffer.Graphics, e.ClipRectangle); + + base.OnPaint(args); + + myBuffer.Render(e.Graphics); + myBuffer.Dispose(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogTextColumn.cs b/src/LogExpert.UI/Controls/LogTextColumn.cs new file mode 100644 index 00000000..c0054b30 --- /dev/null +++ b/src/LogExpert.UI/Controls/LogTextColumn.cs @@ -0,0 +1,15 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Controls; + +internal class LogTextColumn : DataGridViewColumn +{ + #region cTor + + [SupportedOSPlatform("windows")] + public LogTextColumn () : base(new LogGridCell()) + { + } + + #endregion +} diff --git a/src/LogExpert.UI/Controls/LogWindow/ColumnCache.cs b/src/LogExpert.UI/Controls/LogWindow/ColumnCache.cs new file mode 100644 index 00000000..ab9f0746 --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/ColumnCache.cs @@ -0,0 +1,41 @@ +using LogExpert.Core.Callback; +using LogExpert.Core.Classes.Log; + +namespace LogExpert.UI.Controls.LogWindow; + +internal class ColumnCache +{ + #region Fields + + private IColumnizedLogLine _cachedColumns; + private ILogLineColumnizer _lastColumnizer; + private int _lastLineNumber = -1; + + #endregion + + #region Internals + + internal IColumnizedLogLine GetColumnsForLine (LogfileReader logFileReader, int lineNumber, ILogLineColumnizer columnizer, ColumnizerCallback columnizerCallback) + { + if (_lastColumnizer != columnizer || (_lastLineNumber != lineNumber && _cachedColumns != null) || columnizerCallback.LineNum != lineNumber) + { + _lastColumnizer = columnizer; + _lastLineNumber = lineNumber; + ILogLine line = logFileReader.GetLogLineWithWait(lineNumber).Result; + + if (line != null) + { + columnizerCallback.SetLineNum(lineNumber); + _cachedColumns = columnizer.SplitLine(columnizerCallback, line); + } + else + { + _cachedColumns = null; + } + } + + return _cachedColumns; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/LogExpertCallback.cs b/src/LogExpert.UI/Controls/LogWindow/LogExpertCallback.cs new file mode 100644 index 00000000..93733053 --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/LogExpertCallback.cs @@ -0,0 +1,25 @@ +using LogExpert.Core.Callback; + +namespace LogExpert.UI.Controls.LogWindow; + +internal class LogExpertCallback (LogWindow logWindow) : ColumnizerCallback(logWindow), ILogExpertCallback +{ + #region Public methods + + public void AddTempFileTab (string fileName, string title) + { + logWindow.AddTempFileTab(fileName, title); + } + + public void AddPipedTab (IList lineEntryList, string title) + { + logWindow.WritePipeTab(lineEntryList, title); + } + + public string GetTabTitle () + { + return logWindow.Text; + } + + #endregion +} diff --git a/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs new file mode 100644 index 00000000..271af9a6 --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.cs @@ -0,0 +1,7751 @@ +using System.ComponentModel; +using System.Globalization; +using System.Runtime.Versioning; +using System.Text; +using System.Text.RegularExpressions; + +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; +using LogExpert.Core.Classes.Persister; +using LogExpert.Core.Config; +using LogExpert.Core.Entities; +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; +using LogExpert.UI.Extensions; +using LogExpert.UI.Interface; + +using NLog; + +using WeifenLuo.WinFormsUI.Docking; +//using static LogExpert.PluginRegistry.PluginRegistry; //TODO: Adjust the instance name so using static can be used. + +namespace LogExpert.UI.Controls.LogWindow; + +//TODO: Implemented 4 interfaces explicitly. Find them by searching: ILogWindow. +[SupportedOSPlatform("windows")] +internal partial class LogWindow : DockContent, ILogPaintContextUI, ILogView, ILogWindow +{ + #region Fields + + private const int SPREAD_MAX = 99; + private const int PROGRESS_BAR_MODULO = 1000; + private const int FILTER_ADVANCED_SPLITTER_DISTANCE = 110; + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + private readonly Image _advancedButtonImage; + + private readonly object _bookmarkLock = new(); + private readonly BookmarkDataProvider _bookmarkProvider = new(); + + private readonly IList _cancelHandlerList = []; + + private readonly object _currentColumnizerLock = new(); + + private readonly object _currentHighlightGroupLock = new(); + + private readonly EventWaitHandle _externaLoadingFinishedEvent = new ManualResetEvent(false); + + private readonly IList _filterPipeList = []; + private readonly Dictionary _freezeStateMap = []; + private readonly GuiStateArgs _guiStateArgs = new(); + + private readonly List _lineHashList = []; + + private readonly EventWaitHandle _loadingFinishedEvent = new ManualResetEvent(false); + + private readonly EventWaitHandle _logEventArgsEvent = new ManualResetEvent(false); + + private readonly List _logEventArgsList = []; + private readonly Task _logEventHandlerTask; + //private readonly Thread _logEventHandlerThread; + private readonly Image _panelCloseButtonImage; + + private readonly Image _panelOpenButtonImage; + private readonly LogTabWindow.LogTabWindow _parentLogTabWin; + + private readonly ProgressEventArgs _progressEventArgs = new(); + private readonly object _reloadLock = new(); + private readonly Image _searchButtonImage; + private readonly StatusLineEventArgs _statusEventArgs = new(); + + private readonly object _tempHighlightEntryListLock = new(); + + private readonly Task _timeShiftSyncTask; + private readonly CancellationTokenSource cts = new(); + + //private readonly Thread _timeShiftSyncThread; + private readonly EventWaitHandle _timeShiftSyncTimerEvent = new ManualResetEvent(false); + private readonly EventWaitHandle _timeShiftSyncWakeupEvent = new ManualResetEvent(false); + + private readonly TimeSpreadCalculator _timeSpreadCalc; + + private readonly object _timeSyncListLock = new(); + + private ColumnCache _columnCache = new(); + + private ILogLineColumnizer _currentColumnizer; + + //List currentHilightEntryList = new List(); + private HighlightGroup _currentHighlightGroup = new(); + + private SearchParams _currentSearchParams; + + private string[] _fileNames; + private List _filterHitList = []; + private FilterParams _filterParams = new(); + private int _filterPipeNameCounter; + private List _filterResultList = []; + + private ILogLineColumnizer _forcedColumnizer; + private ILogLineColumnizer _forcedColumnizerForLoading; + private bool _isDeadFile; + private bool _isErrorShowing; + private bool _isLoadError; + private bool _isLoading; + private bool _isMultiFile; + private bool _isSearching; + private bool _isTimestampDisplaySyncing; + private List _lastFilterLinesList = []; + + private int _lineHeight; + + private LogfileReader _logFileReader; + private MultiFileOptions _multiFileOptions = new(); + private bool _noSelectionUpdates; + private PatternArgs _patternArgs = new(); + private PatternWindow _patternWindow; + + private ReloadMemento _reloadMemento; + private int _reloadOverloadCounter; + private SortedList _rowHeightList = []; + private int _selectedCol; // set by context menu event for column headers only + private bool _shouldCallTimeSync; + private bool _shouldCancel; + private bool _shouldTimestampDisplaySyncingCancel; + private bool _showAdvanced; + private List _tempHighlightEntryList = []; + private int _timeShiftSyncLine; + + private bool _waitingForClose; + + #endregion + + #region cTor + + [SupportedOSPlatform("windows")] + public LogWindow (LogTabWindow.LogTabWindow parent, string fileName, bool isTempFile, bool forcePersistenceLoading, IConfigManager configManager) + { + SuspendLayout(); + + //HighDPI Functionality must be called before all UI Elements are initialized, to make sure they work as intended + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + InitializeComponent(); + + CreateDefaultViewStyle(); + + columnNamesLabel.Text = string.Empty; // no filtering on columns by default + + _parentLogTabWin = parent; + IsTempFile = isTempFile; + ConfigManager = configManager; //TODO: This should be changed to DI + //Thread.CurrentThread.Name = "LogWindowThread"; + ColumnizerCallbackObject = new ColumnizerCallback(this); + + FileName = fileName; + ForcePersistenceLoading = forcePersistenceLoading; + + dataGridView.CellValueNeeded += OnDataGridViewCellValueNeeded; + dataGridView.CellPainting += OnDataGridViewCellPainting; + + filterGridView.CellValueNeeded += OnFilterGridViewCellValueNeeded; + filterGridView.CellPainting += OnFilterGridViewCellPainting; + filterListBox.DrawMode = DrawMode.OwnerDrawVariable; + filterListBox.MeasureItem += MeasureItem; + + Closing += OnLogWindowClosing; + Disposed += OnLogWindowDisposed; + Load += OnLogWindowLoad; + + _timeSpreadCalc = new TimeSpreadCalculator(this); + timeSpreadingControl.TimeSpreadCalc = _timeSpreadCalc; + timeSpreadingControl.LineSelected += OnTimeSpreadingControlLineSelected; + tableLayoutPanel1.ColumnStyles[1].SizeType = SizeType.Absolute; + tableLayoutPanel1.ColumnStyles[1].Width = 20; + tableLayoutPanel1.ColumnStyles[0].SizeType = SizeType.Percent; + tableLayoutPanel1.ColumnStyles[0].Width = 100; + + _parentLogTabWin.HighlightSettingsChanged += OnParentHighlightSettingsChanged; + SetColumnizer(PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers[0]); + + _patternArgs.MaxMisses = 5; + _patternArgs.MinWeight = 1; + _patternArgs.MaxDiffInBlock = 5; + _patternArgs.Fuzzy = 5; + + //InitPatternWindow(); + + //this.toolwinTabControl.TabPages.Add(this.patternWindow); + //this.toolwinTabControl.TabPages.Add(this.bookmarkWindow); + + _filterParams = new FilterParams(); + foreach (var item in configManager.Settings.FilterHistoryList) + { + _ = filterComboBox.Items.Add(item); + } + + filterComboBox.DropDownHeight = filterComboBox.ItemHeight * configManager.Settings.Preferences.MaximumFilterEntriesDisplayed; + AutoResizeFilterBox(); + + filterRegexCheckBox.Checked = _filterParams.IsRegex; + filterCaseSensitiveCheckBox.Checked = _filterParams.IsCaseSensitive; + filterTailCheckBox.Checked = _filterParams.IsFilterTail; + + splitContainerLogWindow.Panel2Collapsed = true; + advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; + + _timeShiftSyncTask = new Task(SyncTimestampDisplayWorker, cts.Token); + _timeShiftSyncTask.Start(); + + _logEventHandlerTask = new Task(LogEventWorker, cts.Token); + _logEventHandlerTask.Start(); + + //this.filterUpdateThread = new Thread(new ThreadStart(this.FilterUpdateWorker)); + //this.filterUpdateThread.Start(); + + _advancedButtonImage = advancedButton.Image; + _searchButtonImage = filterSearchButton.Image; + filterSearchButton.Image = null; + + dataGridView.EditModeMenuStrip = editModeContextMenuStrip; + markEditModeToolStripMenuItem.Enabled = true; + + _panelOpenButtonImage = Resources.Arrow_menu_open; + _panelCloseButtonImage = Resources.Arrow_menu_close; + + var settings = configManager.Settings; + + if (settings.AppBounds.Right > 0) + { + Bounds = settings.AppBounds; + } + + _waitingForClose = false; + dataGridView.Enabled = false; + dataGridView.ColumnDividerDoubleClick += OnDataGridViewColumnDividerDoubleClick; + ShowAdvancedFilterPanel(false); + filterKnobBackSpread.MinValue = 0; + filterKnobBackSpread.MaxValue = SPREAD_MAX; + filterKnobBackSpread.ValueChanged += OnFilterKnobControlValueChanged; + filterKnobForeSpread.MinValue = 0; + filterKnobForeSpread.MaxValue = SPREAD_MAX; + filterKnobForeSpread.ValueChanged += OnFilterKnobControlValueChanged; + fuzzyKnobControl.MinValue = 0; + fuzzyKnobControl.MaxValue = 10; + //PreferencesChanged(settings.preferences, true); + AdjustHighlightSplitterWidth(); + ToggleHighlightPanel(false); // hidden + + _bookmarkProvider.BookmarkAdded += OnBookmarkProviderBookmarkAdded; + _bookmarkProvider.BookmarkRemoved += OnBookmarkProviderBookmarkRemoved; + _bookmarkProvider.AllBookmarksRemoved += OnBookmarkProviderAllBookmarksRemoved; + + ResumeLayout(); + } + + #endregion + + #region Delegates + + // used for filterTab restore + public delegate void FilterRestoreFx (LogWindow newWin, PersistenceData persistenceData); + + public delegate void RestoreFiltersFx (PersistenceData persistenceData); + + public delegate bool ScrollToTimestampFx (DateTime timestamp, bool roundToSeconds, bool triggerSyncCall); + + public delegate void TailFollowedEventHandler (object sender, EventArgs e); + + #endregion + + #region Events + + public event EventHandler FileSizeChanged; + + public event EventHandler ProgressBarUpdate; + + public event EventHandler StatusLineEvent; + + public event EventHandler GuiStateUpdate; + + public event TailFollowedEventHandler TailFollowed; + + public event EventHandler FileNotFound; + + public event EventHandler FileRespawned; + + public event EventHandler FilterListChanged; + + public event EventHandler CurrentHighlightGroupChanged; + + public event EventHandler BookmarkAdded; + + public event EventHandler BookmarkRemoved; + + public event EventHandler BookmarkTextChanged; + + public event EventHandler ColumnizerChanged; + + public event EventHandler SyncModeChanged; + + #endregion + + #region Properties + + public Color BookmarkColor { get; set; } = Color.FromArgb(165, 200, 225); + + public ILogLineColumnizer CurrentColumnizer + { + get => _currentColumnizer; + private set + { + lock (_currentColumnizerLock) + { + _currentColumnizer = value; + _logger.Debug($"Setting columnizer {_currentColumnizer.GetName()} "); + } + } + } + + [SupportedOSPlatform("windows")] + public bool ShowBookmarkBubbles + { + get => _guiStateArgs.ShowBookmarkBubbles; + set + { + _guiStateArgs.ShowBookmarkBubbles = dataGridView.PaintWithOverlays = value; + dataGridView.Refresh(); + } + } + + public int CurrentLineNum => dataGridView.CurrentRow == null + ? -1 + : dataGridView.CurrentRow.Index; + + public string FileName { get; private set; } + + public string SessionFileName { get; set; } + + public bool IsMultiFile + { + get => _isMultiFile; + private set => _guiStateArgs.IsMultiFileActive = _isMultiFile = value; + } + + public bool IsTempFile { get; } + + private readonly IConfigManager ConfigManager; + + public string TempTitleName { get; set; } = ""; + + internal FilterPipe FilterPipe { get; set; } + + public string Title => IsTempFile + ? TempTitleName + : FileName; + + public ColumnizerCallback ColumnizerCallbackObject { get; } + + public bool ForcePersistenceLoading { get; set; } + + public string ForcedPersistenceFileName { get; set; } + + public Preferences Preferences => _parentLogTabWin.Preferences; + + public string GivenFileName { get; set; } + + public TimeSyncList TimeSyncList { get; private set; } + + public bool IsTimeSynced => TimeSyncList != null; + + protected EncodingOptions EncodingOptions { get; set; } + + public IBookmarkData BookmarkData => _bookmarkProvider; + + public Font MonospacedFont { get; private set; } + + public Font NormalFont { get; private set; } + + public Font BoldFont { get; private set; } + + LogfileReader ILogWindow.LogFileReader => _logFileReader; + + //public event EventHandler ILogWindow.FileSizeChanged + //{ + // add => FileSizeChanged += new EventHandler(value); + // remove => FileSizeChanged -= new EventHandler(value); + //} + + //event EventHandler ILogWindow.TailFollowed + //{ + // add => TailFollowed += new TailFollowedEventHandler(value); + // remove => TailFollowed -= new TailFollowedEventHandler(value); + //} + + #endregion + + #region Public methods + + public ILogLine GetLogLine (int lineNum) + { + return _logFileReader.GetLogLine(lineNum); + } + + public ILogLine GetLogLineWithWait (int lineNum) + { + return _logFileReader.GetLogLineWithWait(lineNum).Result; + } + + public Bookmark GetBookmarkForLine (int lineNum) + { + return _bookmarkProvider.GetBookmarkForLine(lineNum); + } + + #endregion + + #region Internals + + internal IColumnizedLogLine GetColumnsForLine (int lineNumber) + { + return _columnCache.GetColumnsForLine(_logFileReader, lineNumber, CurrentColumnizer, ColumnizerCallbackObject); + + //string line = this.logFileReader.GetLogLine(lineNumber); + //if (line != null) + //{ + // string[] cols; + // this.columnizerCallback.LineNum = lineNumber; + // cols = this.CurrentColumnizer.SplitLine(this.columnizerCallback, line); + // return cols; + //} + //else + //{ + // return null; + //} + } + + [SupportedOSPlatform("windows")] + internal void RefreshAllGrids () + { + dataGridView.Refresh(); + filterGridView.Refresh(); + } + + [SupportedOSPlatform("windows")] + internal void ChangeMultifileMask () + { + MultiFileMaskDialog dlg = new(this, FileName) + { + Owner = this, + MaxDays = _multiFileOptions.MaxDayTry, + FileNamePattern = _multiFileOptions.FormatPattern + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + _multiFileOptions.FormatPattern = dlg.FileNamePattern; + _multiFileOptions.MaxDayTry = dlg.MaxDays; + if (IsMultiFile) + { + Reload(); + } + } + } + + [SupportedOSPlatform("windows")] + internal void ToggleColumnFinder (bool show, bool setFocus) + { + _guiStateArgs.ColumnFinderVisible = show; + + if (show) + { + columnComboBox.AutoCompleteMode = AutoCompleteMode.Suggest; + columnComboBox.AutoCompleteSource = AutoCompleteSource.CustomSource; + columnComboBox.AutoCompleteCustomSource = [.. CurrentColumnizer.GetColumnNames()]; + + if (setFocus) + { + columnComboBox.Focus(); + } + } + else + { + dataGridView.Focus(); + } + + tableLayoutPanel1.RowStyles[0].Height = show ? 28 : 0; + } + + #endregion + + #region Overrides + + protected override string GetPersistString () + { + return "LogWindow#" + FileName; + } + + #endregion + + [SupportedOSPlatform("windows")] + private void OnButtonSizeChanged (object sender, EventArgs e) + { + if (sender is Button button && button.Image != null) + { + button.ImageAlign = ContentAlignment.MiddleCenter; + button.Image = new Bitmap(button.Image, new Size(button.Size.Height, button.Size.Height)); + } + } + + // used for external wait fx WaitForLoadFinished() + + private delegate void SelectLineFx (int line, bool triggerSyncCall); + + private Action, List, List> FilterFxAction; + //private delegate void FilterFx(FilterParams filterParams, List filterResultLines, List lastFilterResultLines, List filterHitList); + + private delegate void UpdateProgressBarFx (int lineNum); + + private delegate void SetColumnizerFx (ILogLineColumnizer columnizer); + + private delegate void WriteFilterToTabFinishedFx (FilterPipe pipe, string namePrefix, PersistenceData persistenceData); + + private delegate void SetBookmarkFx (int lineNum, string comment); + + private delegate void FunctionWith1BoolParam (bool arg); + + private delegate void PatternStatisticFx (PatternArgs patternArgs); + + private delegate void ActionPluginExecuteFx (string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer); + + private delegate void PositionAfterReloadFx (ReloadMemento reloadMemento); + + private delegate void AutoResizeColumnsFx (BufferedDataGridView gridView); + + private delegate bool BoolReturnDelegate (); + + // =================== ILogLineColumnizerCallback ============================ + +#if DEBUG + [SupportedOSPlatform("windows")] + internal void DumpBufferInfo () + { + var currentLineNum = dataGridView.CurrentCellAddress.Y; + _logFileReader.LogBufferInfoForLine(currentLineNum); + } + + internal void DumpBufferDiagnostic () + { + _logFileReader.LogBufferDiagnostic(); + } +#endif + + [SupportedOSPlatform("windows")] + void ILogWindow.SelectLine (int lineNum, bool triggerSyncCall, bool shouldScroll) + { + SelectLine(lineNum, triggerSyncCall, shouldScroll); + } + + [SupportedOSPlatform("windows")] + void ILogWindow.AddTempFileTab (string fileName, string title) + { + AddTempFileTab(fileName, title); + } + + [SupportedOSPlatform("windows")] + void ILogWindow.WritePipeTab (IList lineEntryList, string title) + { + WritePipeTab(lineEntryList, title); + } + + #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[..(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; + CellPainting(gridView.Focused, e.RowIndex, e.ColumnIndex, true, e); + } + + [SupportedOSPlatform("windows")] + private void OnFilterGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) + { + if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) + { + e.Value = string.Empty; + 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); + + 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.DrawFocusRectangle(); + } + } + + [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 CreateDefaultViewStyle () + { + dataGridView.DefaultCellStyle = PaintHelper.GetDataGridViewCellStyle(); + filterGridView.DefaultCellStyle = PaintHelper.GetDataGridViewCellStyle(); + dataGridView.RowsDefaultCellStyle = PaintHelper.GetDataGridDefaultRowStyle(); + filterGridView.RowsDefaultCellStyle = PaintHelper.GetDataGridDefaultRowStyle(); + } + + [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 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); + GetHighlightActions(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); + GetHighlightActions(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) + { + _logFileReader.PreProcessColumnizer = CurrentColumnizer is IPreProcessColumnizer columnizer1 + ? columnizer1 + : 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, HighlightEntry groundEntry) + { + PaintHighlightedCell(e, groundEntry); + } + + private void PaintHighlightedCell (DataGridViewCellPaintingEventArgs e, 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); + + e.Graphics.SetClip(e.CellBounds); + + foreach (var matchEntry in matchList) + { + var font = matchEntry != null && matchEntry.HighlightEntry.IsBold ? BoldFont : NormalFont; + + using var 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.HasFlag(DataGridViewElementStates.Selected)) + { + if (foreColor.Equals(Color.Black)) + { + foreColor = Color.White; + } + } + else + { + 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); + } + } + + /// + /// 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 GetHighlightActions (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); + var diff = timeStamp1.Ticks > timeStamp2.Ticks + ? new DateTime(timeStamp1.Ticks - timeStamp2.Ticks) + : new DateTime(timeStamp2.Ticks - timeStamp1.Ticks); + + StatusLineText($"Time diff is {diff: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; + } + } + + filterGridView.CurrentCell = filterGridView.Rows.GetRowCount(DataGridViewElementStates.None) > 0 + ? filterGridView.Rows[index].Cells[0] + : 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 lineNum, bool triggerSyncCall, bool shouldScroll) + { + try + { + _shouldCallTimeSync = triggerSyncCall; + var wasCancelled = _shouldCancel; + _shouldCancel = false; + _isSearching = false; + StatusLineText(string.Empty); + _guiStateArgs.MenuEnabled = true; + + if (wasCancelled) + { + return; + } + + if (lineNum == -1) + { + // Hmm... is that experimental code from early days? + MessageBox.Show(this, "Not found:", "Search result"); + return; + } + + // Prevent ArgumentOutOfRangeException + if (lineNum >= dataGridView.Rows.GetRowCount(DataGridViewElementStates.None)) + { + lineNum = dataGridView.Rows.GetRowCount(DataGridViewElementStates.None) - 1; + } + + dataGridView.Rows[lineNum].Selected = true; + + if (shouldScroll) + { + dataGridView.CurrentCell = dataGridView.Rows[lineNum].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.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; + _ = 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; + } + + return filterParams.IsCaseSensitive != filterCaseSensitiveCheckBox.Checked; + } + + [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, List 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) + { + tableLayoutPanel1.ColumnStyles[1].Width = show + ? 16 + : 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 (bool focused, int rowIndex, int columnIndex, bool isFilteredGridView, DataGridViewCellPaintingEventArgs e) + { + if (rowIndex < 0 || columnIndex < 0 || (isFilteredGridView && _filterResultList.Count <= rowIndex)) + { + e.Handled = false; + return; + } + + if (isFilteredGridView) + { + rowIndex = _filterResultList[rowIndex]; + } + + 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(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, entry); + } + + if (columnIndex == 0) + { + if (_bookmarkProvider.IsBookmarkAtLine(rowIndex)) + { + //keeping this comment, because it's the original code + // = new Rectangle(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, rect); + + var bookmark = _bookmarkProvider.GetBookmarkForLine(rowIndex); + + if (bookmark.Text.Length > 0) + { + StringFormat format = new() + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Center + }; + + //Todo Add this as a Settings Option + var fontName = isFilteredGridView ? "Verdana" : "Courier New"; + var stringToDraw = isFilteredGridView ? "!" : "i"; + + using var brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); //dark orange + using var font = new Font(fontName, Preferences.FontSize, FontStyle.Bold); + e.Graphics.DrawString(stringToDraw, font, brush2, new RectangleF(rect.Left, rect.Top, rect.Width, rect.Height), format); + } + } + } + + e.Paint(e.CellBounds, DataGridViewPaintParts.Border); + e.Handled = true; + } + } + + public void OnDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) + { + var gridView = (BufferedDataGridView)sender; + CellPainting(gridView.Focused, e.RowIndex, e.ColumnIndex, false, 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 = FindTimestampLineInternal(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 FindTimestampLineInternal (int lineNum, int rangeStart, int rangeEnd, DateTime timestamp, bool roundToSeconds) + { + _logger.Debug($"FindTimestampLine_Internal(): timestamp={timestamp}, lineNum={lineNum}, rangeStart={rangeStart}, rangeEnd={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 FindTimestampLineInternal(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={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 () + { + return dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index != -1 + ? _logFileReader.GetLogLine(dataGridView.CurrentRow.Index) + : null; + } + + public ILogLine GetLine (int lineNum) + { + return lineNum < 0 || _logFileReader == null || lineNum >= _logFileReader.LineCount + ? null + : _logFileReader.GetLogLine(lineNum); + } + + public int GetRealLineNum () + { + var lineNum = CurrentLineNum; + return lineNum == -1 + ? -1 + : _logFileReader.GetRealLineNumForVirtualLineNum(lineNum); + } + + public ILogFileInfo GetCurrentFileInfo () + { + return dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index != -1 + ? _logFileReader.GetLogFileInfoForLine(dataGridView.CurrentRow.Index) + : 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/Controls/LogWindow/LogWindow.designer.cs b/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs similarity index 95% rename from src/LogExpert/Controls/LogWindow/LogWindow.designer.cs rename to src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs index 25a3091c..2e032551 100644 --- a/src/LogExpert/Controls/LogWindow/LogWindow.designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/LogWindow.designer.cs @@ -1,1307 +1,1304 @@ -using LogExpert.Dialogs; -using LogExpert.Extensions.Forms; -using LogExpert.Properties; - -using System; -using System.Drawing; -using System.IO; -using System.Windows.Forms; - -namespace LogExpert.Controls.LogWindow -{ - partial class LogWindow - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LogWindow)); - splitContainerLogWindow = new SplitContainer(); - tableLayoutPanel1 = new TableLayoutPanel(); - columnFinderPanel = new Panel(); - columnComboBox = new ComboBox(); - lblColumnName = new Label(); - dataGridView = new BufferedDataGridView(); - dataGridContextMenuStrip = new ContextMenuStrip(components); - copyToolStripMenuItem = new ToolStripMenuItem(); - copyToTabToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator1 = new MenuToolStripSeparatorExtension(); - scrollAllTabsToTimestampToolStripMenuItem = new ToolStripMenuItem(); - syncTimestampsToToolStripMenuItem = new ToolStripMenuItem(); - freeThisWindowFromTimeSyncToolStripMenuItem = new ToolStripMenuItem(); - locateLineInOriginalFileToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator2 = new MenuToolStripSeparatorExtension(); - toggleBoomarkToolStripMenuItem = new ToolStripMenuItem(); - bookmarkCommentToolStripMenuItem = new ToolStripMenuItem(); - markEditModeToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator3 = new MenuToolStripSeparatorExtension(); - tempHighlightsToolStripMenuItem = new ToolStripMenuItem(); - removeAllToolStripMenuItem = new ToolStripMenuItem(); - makePermanentToolStripMenuItem = new ToolStripMenuItem(); - markCurrentFilterRangeToolStripMenuItem = new ToolStripMenuItem(); - pluginSeparator = new MenuToolStripSeparatorExtension(); - timeSpreadingControl = new TimeSpreadingControl(); - advancedBackPanel = new Panel(); - advancedFilterSplitContainer = new SplitContainer(); - pnlProFilter = new Panel(); - columnButton = new Button(); - columnRestrictCheckBox = new CheckBox(); - rangeCheckBox = new CheckBox(); - filterRangeComboBox = new ComboBox(); - columnNamesLabel = new Label(); - fuzzyLabel = new Label(); - fuzzyKnobControl = new KnobControl(); - invertFilterCheckBox = new CheckBox(); - pnlProFilterLabel = new Panel(); - lblBackSpread = new Label(); - filterKnobBackSpread = new KnobControl(); - lblForeSpread = new Label(); - filterKnobForeSpread = new KnobControl(); - btnFilterToTab = new Button(); - panelBackgroundAdvancedFilterSplitContainer = new Panel(); - btnToggleHighlightPanel = new Button(); - highlightSplitContainer = new SplitContainer(); - filterGridView = new BufferedDataGridView(); - filterContextMenuStrip = new ContextMenuStrip(components); - setBookmarksOnSelectedLinesToolStripMenuItem = new ToolStripMenuItem(); - filterToTabToolStripMenuItem = new ToolStripMenuItem(); - markFilterHitsInLogViewToolStripMenuItem = new ToolStripMenuItem(); - highlightSplitContainerBackPanel = new Panel(); - hideFilterListOnLoadCheckBox = new CheckBox(); - filterDownButton = new Button(); - filterUpButton = new Button(); - filterOnLoadCheckBox = new CheckBox(); - saveFilterButton = new Button(); - deleteFilterButton = new Button(); - filterListBox = new ListBox(); - filterListContextMenuStrip = new ContextMenuStrip(components); - colorToolStripMenuItem = new ToolStripMenuItem(); - pnlFilterInput = new Panel(); - filterSplitContainer = new SplitContainer(); - filterComboBox = new ComboBox(); - lblTextFilter = new Label(); - advancedButton = new Button(); - syncFilterCheckBox = new CheckBox(); - lblFilterCount = new Label(); - filterTailCheckBox = new CheckBox(); - filterRegexCheckBox = new CheckBox(); - filterCaseSensitiveCheckBox = new CheckBox(); - filterSearchButton = new Button(); - bookmarkContextMenuStrip = new ContextMenuStrip(components); - deleteBookmarksToolStripMenuItem = new ToolStripMenuItem(); - columnContextMenuStrip = new ContextMenuStrip(components); - freezeLeftColumnsUntilHereToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator4 = new MenuToolStripSeparatorExtension(); - moveToLastColumnToolStripMenuItem = new ToolStripMenuItem(); - moveLeftToolStripMenuItem = new ToolStripMenuItem(); - moveRightToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator5 = new MenuToolStripSeparatorExtension(); - hideColumnToolStripMenuItem = new ToolStripMenuItem(); - restoreColumnsToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparator6 = new MenuToolStripSeparatorExtension(); - allColumnsToolStripMenuItem = new ToolStripMenuItem(); - editModeContextMenuStrip = new ContextMenuStrip(components); - editModecopyToolStripMenuItem = new ToolStripMenuItem(); - highlightSelectionInLogFileToolStripMenuItem = new ToolStripMenuItem(); - highlightSelectionInLogFilewordModeToolStripMenuItem = new ToolStripMenuItem(); - filterForSelectionToolStripMenuItem = new ToolStripMenuItem(); - setSelectedTextAsBookmarkCommentToolStripMenuItem = new ToolStripMenuItem(); - helpToolTip = new ToolTip(components); - ((System.ComponentModel.ISupportInitialize)splitContainerLogWindow).BeginInit(); - splitContainerLogWindow.Panel1.SuspendLayout(); - splitContainerLogWindow.Panel2.SuspendLayout(); - splitContainerLogWindow.SuspendLayout(); - tableLayoutPanel1.SuspendLayout(); - columnFinderPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); - dataGridContextMenuStrip.SuspendLayout(); - advancedBackPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)advancedFilterSplitContainer).BeginInit(); - advancedFilterSplitContainer.Panel1.SuspendLayout(); - advancedFilterSplitContainer.Panel2.SuspendLayout(); - advancedFilterSplitContainer.SuspendLayout(); - pnlProFilter.SuspendLayout(); - panelBackgroundAdvancedFilterSplitContainer.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)highlightSplitContainer).BeginInit(); - highlightSplitContainer.Panel1.SuspendLayout(); - highlightSplitContainer.Panel2.SuspendLayout(); - highlightSplitContainer.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)filterGridView).BeginInit(); - filterContextMenuStrip.SuspendLayout(); - highlightSplitContainerBackPanel.SuspendLayout(); - filterListContextMenuStrip.SuspendLayout(); - pnlFilterInput.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)filterSplitContainer).BeginInit(); - filterSplitContainer.Panel1.SuspendLayout(); - filterSplitContainer.Panel2.SuspendLayout(); - filterSplitContainer.SuspendLayout(); - bookmarkContextMenuStrip.SuspendLayout(); - columnContextMenuStrip.SuspendLayout(); - editModeContextMenuStrip.SuspendLayout(); - SuspendLayout(); - // - // splitContainerLogWindow - // - splitContainerLogWindow.BorderStyle = BorderStyle.FixedSingle; - splitContainerLogWindow.Dock = DockStyle.Fill; - splitContainerLogWindow.Location = new Point(0, 0); - splitContainerLogWindow.Margin = new Padding(0); - splitContainerLogWindow.Name = "splitContainerLogWindow"; - splitContainerLogWindow.Orientation = Orientation.Horizontal; - // - // splitContainerLogWindow.Panel1 - // - splitContainerLogWindow.Panel1.Controls.Add(tableLayoutPanel1); - splitContainerLogWindow.Panel1MinSize = 50; - // - // splitContainerLogWindow.Panel2 - // - splitContainerLogWindow.Panel2.Controls.Add(advancedBackPanel); - splitContainerLogWindow.Panel2.Controls.Add(pnlFilterInput); - splitContainerLogWindow.Panel2MinSize = 50; - splitContainerLogWindow.Size = new Size(1862, 1104); - splitContainerLogWindow.SplitterDistance = 486; - splitContainerLogWindow.TabIndex = 9; - splitContainerLogWindow.SplitterMoved += OnSplitContainerSplitterMoved; - // - // tableLayoutPanel1 - // - tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; - tableLayoutPanel1.ColumnCount = 2; - tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle()); - tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 181F)); - tableLayoutPanel1.Controls.Add(columnFinderPanel, 0, 0); - tableLayoutPanel1.Controls.Add(dataGridView, 0, 1); - tableLayoutPanel1.Controls.Add(timeSpreadingControl, 1, 1); - tableLayoutPanel1.Dock = DockStyle.Fill; - tableLayoutPanel1.ForeColor = SystemColors.ControlText; - tableLayoutPanel1.Location = new Point(0, 0); - tableLayoutPanel1.Margin = new Padding(0); - tableLayoutPanel1.Name = "tableLayoutPanel1"; - tableLayoutPanel1.RowCount = 2; - tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 28F)); - tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100F)); - tableLayoutPanel1.Size = new Size(1860, 484); - tableLayoutPanel1.TabIndex = 2; - // - // columnFinderPanel - // - columnFinderPanel.Controls.Add(columnComboBox); - columnFinderPanel.Controls.Add(lblColumnName); - columnFinderPanel.Dock = DockStyle.Fill; - columnFinderPanel.Location = new Point(4, 4); - columnFinderPanel.Name = "columnFinderPanel"; - columnFinderPanel.Size = new Size(841, 22); - columnFinderPanel.TabIndex = 2; - // - // columnComboBox - // - columnComboBox.FormattingEnabled = true; - columnComboBox.Location = new Point(125, 1); - columnComboBox.MaxDropDownItems = 15; - columnComboBox.Name = "columnComboBox"; - columnComboBox.Size = new Size(181, 21); - columnComboBox.TabIndex = 1; - helpToolTip.SetToolTip(columnComboBox, "Select column to scroll to"); - columnComboBox.SelectionChangeCommitted += OnColumnComboBoxSelectionChangeCommitted; - columnComboBox.KeyDown += OnColumnComboBoxKeyDown; - columnComboBox.PreviewKeyDown += OnColumnComboBoxPreviewKeyDown; - // - // lblColumnName - // - lblColumnName.AutoSize = true; - lblColumnName.Location = new Point(8, 4); - lblColumnName.Name = "lblColumnName"; - lblColumnName.Size = new Size(74, 13); - lblColumnName.TabIndex = 0; - lblColumnName.Text = "Column name:"; - // - // dataGridView - // - dataGridView.AllowUserToAddRows = false; - dataGridView.AllowUserToDeleteRows = false; - dataGridView.AllowUserToOrderColumns = true; - dataGridView.AllowUserToResizeRows = false; - dataGridView.BackgroundColor = SystemColors.Window; - dataGridView.BorderStyle = BorderStyle.None; - dataGridView.CellBorderStyle = DataGridViewCellBorderStyle.None; - dataGridView.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; - dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridView.ContextMenuStrip = dataGridContextMenuStrip; - dataGridView.Dock = DockStyle.Fill; - dataGridView.EditMode = DataGridViewEditMode.EditProgrammatically; - dataGridView.EditModeMenuStrip = null; - dataGridView.ImeMode = ImeMode.Disable; - dataGridView.Location = new Point(1, 30); - dataGridView.Margin = new Padding(0); - dataGridView.Name = "dataGridView"; - dataGridView.PaintWithOverlays = false; - dataGridView.RowHeadersVisible = false; - dataGridView.RowHeadersWidth = 62; - dataGridView.RowTemplate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomLeft; - dataGridView.RowTemplate.DefaultCellStyle.Padding = new Padding(2, 0, 0, 0); - dataGridView.RowTemplate.Height = 15; - dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - dataGridView.ShowCellErrors = false; - dataGridView.ShowCellToolTips = false; - dataGridView.ShowEditingIcon = false; - dataGridView.ShowRowErrors = false; - dataGridView.Size = new Size(847, 453); - dataGridView.TabIndex = 0; - dataGridView.VirtualMode = true; - dataGridView.OverlayDoubleClicked += OnDataGridViewOverlayDoubleClicked; - dataGridView.CellClick += OnDataGridViewCellClick; - dataGridView.CellContentDoubleClick += OnDataGridViewCellContentDoubleClick; - dataGridView.CellContextMenuStripNeeded += OnDataGridViewCellContextMenuStripNeeded; - dataGridView.CellDoubleClick += OnDataGridViewCellDoubleClick; - dataGridView.CellValuePushed += OnDataGridViewCellValuePushed; - dataGridView.RowHeightInfoNeeded += OnDataGridViewRowHeightInfoNeeded; - dataGridView.RowUnshared += OnDataGridViewRowUnshared; - dataGridView.Scroll += OnDataGridViewScroll; - dataGridView.SelectionChanged += OnDataGridViewSelectionChanged; - dataGridView.Paint += OnDataGridViewPaint; - dataGridView.Enter += OnDataGridViewEnter; - dataGridView.KeyDown += OnDataGridViewKeyDown; - dataGridView.Leave += OnDataGridViewLeave; - dataGridView.PreviewKeyDown += OnDataGridViewPreviewKeyDown; - dataGridView.Resize += OnDataGridViewResize; - // - // dataGridContextMenuStrip - // - dataGridContextMenuStrip.ImageScalingSize = new Size(24, 24); - dataGridContextMenuStrip.Items.AddRange(new ToolStripItem[] { copyToolStripMenuItem, copyToTabToolStripMenuItem, menuToolStripSeparator1, scrollAllTabsToTimestampToolStripMenuItem, syncTimestampsToToolStripMenuItem, freeThisWindowFromTimeSyncToolStripMenuItem, locateLineInOriginalFileToolStripMenuItem, menuToolStripSeparator2, toggleBoomarkToolStripMenuItem, bookmarkCommentToolStripMenuItem, markEditModeToolStripMenuItem, menuToolStripSeparator3, tempHighlightsToolStripMenuItem, markCurrentFilterRangeToolStripMenuItem, pluginSeparator }); - dataGridContextMenuStrip.Name = "dataGridContextMenuStrip"; - dataGridContextMenuStrip.Size = new Size(287, 270); - dataGridContextMenuStrip.Opening += OnDataGridContextMenuStripOpening; - // - // copyToolStripMenuItem - // - copyToolStripMenuItem.Name = "copyToolStripMenuItem"; - copyToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C; - copyToolStripMenuItem.Size = new Size(286, 22); - copyToolStripMenuItem.Text = "Copy to clipboard"; - copyToolStripMenuItem.Click += OnCopyToolStripMenuItemClick; - // - // copyToTabToolStripMenuItem - // - copyToTabToolStripMenuItem.Name = "copyToTabToolStripMenuItem"; - copyToTabToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T; - copyToTabToolStripMenuItem.Size = new Size(286, 22); - copyToTabToolStripMenuItem.Text = "Copy to new tab"; - copyToTabToolStripMenuItem.ToolTipText = "Copy marked lines into a new tab window"; - copyToTabToolStripMenuItem.Click += OnCopyToTabToolStripMenuItemClick; - // - // menuToolStripSeparator1 - // - menuToolStripSeparator1.Name = "menuToolStripSeparator1"; - menuToolStripSeparator1.Size = new Size(283, 6); - // - // scrollAllTabsToTimestampToolStripMenuItem - // - scrollAllTabsToTimestampToolStripMenuItem.Name = "scrollAllTabsToTimestampToolStripMenuItem"; - scrollAllTabsToTimestampToolStripMenuItem.Size = new Size(286, 22); - scrollAllTabsToTimestampToolStripMenuItem.Text = "Scroll all tabs to current timestamp"; - scrollAllTabsToTimestampToolStripMenuItem.ToolTipText = "Scolls all open tabs to the selected timestamp, if possible"; - scrollAllTabsToTimestampToolStripMenuItem.Click += OnScrollAllTabsToTimestampToolStripMenuItemClick; - // - // syncTimestampsToToolStripMenuItem - // - syncTimestampsToToolStripMenuItem.Name = "syncTimestampsToToolStripMenuItem"; - syncTimestampsToToolStripMenuItem.Size = new Size(286, 22); - syncTimestampsToToolStripMenuItem.Text = "Time synced files"; - // - // freeThisWindowFromTimeSyncToolStripMenuItem - // - freeThisWindowFromTimeSyncToolStripMenuItem.Name = "freeThisWindowFromTimeSyncToolStripMenuItem"; - freeThisWindowFromTimeSyncToolStripMenuItem.Size = new Size(286, 22); - freeThisWindowFromTimeSyncToolStripMenuItem.Text = "Free this window from time sync"; - freeThisWindowFromTimeSyncToolStripMenuItem.Click += OnFreeThisWindowFromTimeSyncToolStripMenuItemClick; - // - // locateLineInOriginalFileToolStripMenuItem - // - locateLineInOriginalFileToolStripMenuItem.Name = "locateLineInOriginalFileToolStripMenuItem"; - locateLineInOriginalFileToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; - locateLineInOriginalFileToolStripMenuItem.Size = new Size(286, 22); - locateLineInOriginalFileToolStripMenuItem.Text = "Locate filtered line in original file"; - locateLineInOriginalFileToolStripMenuItem.Click += OnLocateLineInOriginalFileToolStripMenuItemClick; - // - // menuToolStripSeparator2 - // - menuToolStripSeparator2.Name = "menuToolStripSeparator2"; - menuToolStripSeparator2.Size = new Size(283, 6); - // - // toggleBoomarkToolStripMenuItem - // - toggleBoomarkToolStripMenuItem.Name = "toggleBoomarkToolStripMenuItem"; - toggleBoomarkToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F2; - toggleBoomarkToolStripMenuItem.Size = new Size(286, 22); - toggleBoomarkToolStripMenuItem.Text = "Toggle Boomark"; - toggleBoomarkToolStripMenuItem.Click += OnToggleBoomarkToolStripMenuItemClick; - // - // bookmarkCommentToolStripMenuItem - // - bookmarkCommentToolStripMenuItem.Name = "bookmarkCommentToolStripMenuItem"; - bookmarkCommentToolStripMenuItem.ShortcutKeys = Keys.Alt | Keys.F2; - bookmarkCommentToolStripMenuItem.Size = new Size(286, 22); - bookmarkCommentToolStripMenuItem.Text = "Bookmark comment..."; - bookmarkCommentToolStripMenuItem.ToolTipText = "Edit the comment for a bookmark"; - bookmarkCommentToolStripMenuItem.Click += OnBookmarkCommentToolStripMenuItemClick; - // - // markEditModeToolStripMenuItem - // - markEditModeToolStripMenuItem.Name = "markEditModeToolStripMenuItem"; - markEditModeToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; - markEditModeToolStripMenuItem.Size = new Size(286, 22); - markEditModeToolStripMenuItem.Text = "Mark/Edit-Mode"; - markEditModeToolStripMenuItem.Click += OnMarkEditModeToolStripMenuItemClick; - // - // menuToolStripSeparator3 - // - menuToolStripSeparator3.Name = "menuToolStripSeparator3"; - menuToolStripSeparator3.Size = new Size(283, 6); - // - // tempHighlightsToolStripMenuItem - // - tempHighlightsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { removeAllToolStripMenuItem, makePermanentToolStripMenuItem }); - tempHighlightsToolStripMenuItem.Name = "tempHighlightsToolStripMenuItem"; - tempHighlightsToolStripMenuItem.Size = new Size(286, 22); - tempHighlightsToolStripMenuItem.Text = "Temp Highlights"; - // - // removeAllToolStripMenuItem - // - removeAllToolStripMenuItem.Name = "removeAllToolStripMenuItem"; - removeAllToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.Shift | Keys.H; - removeAllToolStripMenuItem.Size = new Size(207, 22); - removeAllToolStripMenuItem.Text = "Remove all"; - removeAllToolStripMenuItem.Click += OnRemoveAllToolStripMenuItemClick; - // - // makePermanentToolStripMenuItem - // - makePermanentToolStripMenuItem.Name = "makePermanentToolStripMenuItem"; - makePermanentToolStripMenuItem.Size = new Size(207, 22); - makePermanentToolStripMenuItem.Text = "Make all permanent"; - makePermanentToolStripMenuItem.Click += OnMakePermanentToolStripMenuItemClick; - // - // markCurrentFilterRangeToolStripMenuItem - // - markCurrentFilterRangeToolStripMenuItem.Name = "markCurrentFilterRangeToolStripMenuItem"; - markCurrentFilterRangeToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.R; - markCurrentFilterRangeToolStripMenuItem.Size = new Size(286, 22); - markCurrentFilterRangeToolStripMenuItem.Text = "Mark current filter range"; - markCurrentFilterRangeToolStripMenuItem.Click += OnMarkCurrentFilterRangeToolStripMenuItemClick; - // - // pluginSeparator - // - pluginSeparator.Name = "pluginSeparator"; - pluginSeparator.Size = new Size(283, 6); - // - // timeSpreadingControl - // - timeSpreadingControl.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; - timeSpreadingControl.Font = new Font("Verdana", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - timeSpreadingControl.ForeColor = Color.Teal; - timeSpreadingControl.Location = new Point(1842, 30); - timeSpreadingControl.Margin = new Padding(2, 0, 1, 0); - timeSpreadingControl.Name = "timeSpreadingControl"; - timeSpreadingControl.ReverseAlpha = false; - timeSpreadingControl.Size = new Size(16, 453); - timeSpreadingControl.TabIndex = 1; - // - // advancedBackPanel - // - advancedBackPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - advancedBackPanel.Controls.Add(advancedFilterSplitContainer); - advancedBackPanel.Location = new Point(3, 48); - advancedBackPanel.Name = "advancedBackPanel"; - advancedBackPanel.Size = new Size(1855, 561); - advancedBackPanel.TabIndex = 3; - // - // advancedFilterSplitContainer - // - advancedFilterSplitContainer.Dock = DockStyle.Fill; - advancedFilterSplitContainer.IsSplitterFixed = true; - advancedFilterSplitContainer.Location = new Point(0, 0); - advancedFilterSplitContainer.Margin = new Padding(0); - advancedFilterSplitContainer.Name = "advancedFilterSplitContainer"; - advancedFilterSplitContainer.Orientation = Orientation.Horizontal; - // - // advancedFilterSplitContainer.Panel1 - // - advancedFilterSplitContainer.Panel1.Controls.Add(pnlProFilter); - advancedFilterSplitContainer.Panel1MinSize = 100; - // - // advancedFilterSplitContainer.Panel2 - // - advancedFilterSplitContainer.Panel2.Controls.Add(panelBackgroundAdvancedFilterSplitContainer); - advancedFilterSplitContainer.Panel2MinSize = 200; - advancedFilterSplitContainer.Size = new Size(1855, 561); - advancedFilterSplitContainer.SplitterDistance = 124; - advancedFilterSplitContainer.SplitterWidth = 2; - advancedFilterSplitContainer.TabIndex = 2; - // - // pnlProFilter - // - pnlProFilter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - pnlProFilter.Controls.Add(columnButton); - pnlProFilter.Controls.Add(columnRestrictCheckBox); - pnlProFilter.Controls.Add(rangeCheckBox); - pnlProFilter.Controls.Add(filterRangeComboBox); - pnlProFilter.Controls.Add(columnNamesLabel); - pnlProFilter.Controls.Add(fuzzyLabel); - pnlProFilter.Controls.Add(fuzzyKnobControl); - pnlProFilter.Controls.Add(invertFilterCheckBox); - pnlProFilter.Controls.Add(pnlProFilterLabel); - pnlProFilter.Controls.Add(lblBackSpread); - pnlProFilter.Controls.Add(filterKnobBackSpread); - pnlProFilter.Controls.Add(lblForeSpread); - pnlProFilter.Controls.Add(filterKnobForeSpread); - pnlProFilter.Controls.Add(btnFilterToTab); - pnlProFilter.Location = new Point(0, 3); - pnlProFilter.Name = "pnlProFilter"; - pnlProFilter.Size = new Size(1852, 117); - pnlProFilter.TabIndex = 0; - // - // columnButton - // - columnButton.Enabled = false; - columnButton.Location = new Point(750, 41); - columnButton.Name = "columnButton"; - columnButton.Size = new Size(85, 35); - columnButton.TabIndex = 15; - columnButton.Text = "Columns..."; - helpToolTip.SetToolTip(columnButton, "Choose columns for 'Column restrict'"); - columnButton.UseVisualStyleBackColor = true; - columnButton.Click += OnColumnButtonClick; - // - // columnRestrictCheckBox - // - columnRestrictCheckBox.AutoSize = true; - columnRestrictCheckBox.Location = new Point(594, 38); - columnRestrictCheckBox.Name = "columnRestrictCheckBox"; - columnRestrictCheckBox.Size = new Size(95, 17); - columnRestrictCheckBox.TabIndex = 14; - columnRestrictCheckBox.Text = "Column restrict"; - helpToolTip.SetToolTip(columnRestrictCheckBox, "Restrict search to columns"); - columnRestrictCheckBox.UseVisualStyleBackColor = true; - columnRestrictCheckBox.CheckedChanged += OnColumnRestrictCheckBoxCheckedChanged; - // - // rangeCheckBox - // - rangeCheckBox.AutoSize = true; - rangeCheckBox.Location = new Point(73, 38); - rangeCheckBox.Name = "rangeCheckBox"; - rangeCheckBox.Size = new Size(93, 17); - rangeCheckBox.TabIndex = 13; - rangeCheckBox.Text = "Range search"; - helpToolTip.SetToolTip(rangeCheckBox, "Enable a special search mode which filters all content between the 2 given search terms."); - rangeCheckBox.UseVisualStyleBackColor = true; - rangeCheckBox.CheckedChanged += OnRangeCheckBoxCheckedChanged; - // - // filterRangeComboBox - // - filterRangeComboBox.Enabled = false; - filterRangeComboBox.FormattingEnabled = true; - filterRangeComboBox.Location = new Point(73, 11); - filterRangeComboBox.Name = "filterRangeComboBox"; - filterRangeComboBox.Size = new Size(207, 21); - filterRangeComboBox.TabIndex = 12; - helpToolTip.SetToolTip(filterRangeComboBox, "2nd search string ('end string') when using the range search"); - filterRangeComboBox.TextChanged += OnFilterRangeComboBoxTextChanged; - // - // columnNamesLabel - // - columnNamesLabel.AutoSize = true; - columnNamesLabel.Location = new Point(841, 41); - columnNamesLabel.Name = "columnNamesLabel"; - columnNamesLabel.Size = new Size(75, 13); - columnNamesLabel.TabIndex = 11; - columnNamesLabel.Text = "column names"; - // - // fuzzyLabel - // - fuzzyLabel.AutoSize = true; - fuzzyLabel.Location = new Point(502, 38); - fuzzyLabel.Name = "fuzzyLabel"; - fuzzyLabel.Size = new Size(56, 13); - fuzzyLabel.TabIndex = 11; - fuzzyLabel.Text = "Fuzzyness"; - // - // fuzzyKnobControl - // - fuzzyKnobControl.DragSensitivity = 6; - fuzzyKnobControl.Font = new Font("Verdana", 6F, FontStyle.Regular, GraphicsUnit.Point, 0); - fuzzyKnobControl.Location = new Point(521, 7); - fuzzyKnobControl.Margin = new Padding(2); - fuzzyKnobControl.MaxValue = 0; - fuzzyKnobControl.MinValue = 0; - fuzzyKnobControl.Name = "fuzzyKnobControl"; - fuzzyKnobControl.Size = new Size(17, 29); - fuzzyKnobControl.TabIndex = 10; - helpToolTip.SetToolTip(fuzzyKnobControl, "Fuzzy search level (0 = fuzzy off)"); - fuzzyKnobControl.Value = 0; - fuzzyKnobControl.ValueChanged += OnFuzzyKnobControlValueChanged; - // - // invertFilterCheckBox - // - invertFilterCheckBox.AutoSize = true; - invertFilterCheckBox.Location = new Point(594, 7); - invertFilterCheckBox.Name = "invertFilterCheckBox"; - invertFilterCheckBox.Size = new Size(86, 17); - invertFilterCheckBox.TabIndex = 8; - invertFilterCheckBox.Text = "Invert Match"; - helpToolTip.SetToolTip(invertFilterCheckBox, "Invert the search result"); - invertFilterCheckBox.UseVisualStyleBackColor = true; - invertFilterCheckBox.CheckedChanged += OnInvertFilterCheckBoxCheckedChanged; - // - // pnlProFilterLabel - // - pnlProFilterLabel.BackgroundImage = Resources.Pro_Filter; - pnlProFilterLabel.BackgroundImageLayout = ImageLayout.Center; - pnlProFilterLabel.Location = new Point(5, 7); - pnlProFilterLabel.Name = "pnlProFilterLabel"; - pnlProFilterLabel.Size = new Size(60, 44); - pnlProFilterLabel.TabIndex = 7; - // - // lblBackSpread - // - lblBackSpread.AutoSize = true; - lblBackSpread.Location = new Point(287, 38); - lblBackSpread.Name = "lblBackSpread"; - lblBackSpread.Size = new Size(72, 13); - lblBackSpread.TabIndex = 6; - lblBackSpread.Text = "Back Spread "; - // - // filterKnobBackSpread - // - filterKnobBackSpread.DragSensitivity = 3; - filterKnobBackSpread.Font = new Font("Verdana", 6F, FontStyle.Regular, GraphicsUnit.Point, 0); - filterKnobBackSpread.Location = new Point(313, 7); - filterKnobBackSpread.Margin = new Padding(2); - filterKnobBackSpread.MaxValue = 0; - filterKnobBackSpread.MinValue = 0; - filterKnobBackSpread.Name = "filterKnobBackSpread"; - filterKnobBackSpread.Size = new Size(17, 29); - filterKnobBackSpread.TabIndex = 5; - helpToolTip.SetToolTip(filterKnobBackSpread, "Add preceding lines to search result (Drag up/down, press Shift for finer pitch)"); - filterKnobBackSpread.Value = 0; - // - // lblForeSpread - // - lblForeSpread.AutoSize = true; - lblForeSpread.Location = new Point(397, 38); - lblForeSpread.Name = "lblForeSpread"; - lblForeSpread.Size = new Size(65, 13); - lblForeSpread.TabIndex = 2; - lblForeSpread.Text = "Fore Spread"; - // - // filterKnobForeSpread - // - filterKnobForeSpread.DragSensitivity = 3; - filterKnobForeSpread.Font = new Font("Verdana", 6F, FontStyle.Regular, GraphicsUnit.Point, 0); - filterKnobForeSpread.Location = new Point(420, 7); - filterKnobForeSpread.Margin = new Padding(2); - filterKnobForeSpread.MaxValue = 0; - filterKnobForeSpread.MinValue = 0; - filterKnobForeSpread.Name = "filterKnobForeSpread"; - filterKnobForeSpread.Size = new Size(17, 29); - filterKnobForeSpread.TabIndex = 1; - helpToolTip.SetToolTip(filterKnobForeSpread, "Add following lines to search result (Drag up/down, press Shift for finer pitch)"); - filterKnobForeSpread.Value = 0; - // - // btnFilterToTab - // - btnFilterToTab.Location = new Point(750, 3); - btnFilterToTab.Name = "btnFilterToTab"; - btnFilterToTab.Size = new Size(85, 35); - btnFilterToTab.TabIndex = 0; - btnFilterToTab.Text = "Filter to Tab"; - helpToolTip.SetToolTip(btnFilterToTab, "Launch a new tab with filtered content"); - btnFilterToTab.UseVisualStyleBackColor = true; - btnFilterToTab.Click += OnFilterToTabButtonClick; - // - // panelBackgroundAdvancedFilterSplitContainer - // - panelBackgroundAdvancedFilterSplitContainer.Controls.Add(btnToggleHighlightPanel); - panelBackgroundAdvancedFilterSplitContainer.Controls.Add(highlightSplitContainer); - panelBackgroundAdvancedFilterSplitContainer.Dock = DockStyle.Fill; - panelBackgroundAdvancedFilterSplitContainer.Location = new Point(0, 0); - panelBackgroundAdvancedFilterSplitContainer.Name = "panelBackgroundAdvancedFilterSplitContainer"; - panelBackgroundAdvancedFilterSplitContainer.Size = new Size(1855, 435); - panelBackgroundAdvancedFilterSplitContainer.TabIndex = 7; - // - // btnToggleHighlightPanel - // - btnToggleHighlightPanel.Anchor = AnchorStyles.Top | AnchorStyles.Right; - btnToggleHighlightPanel.Image = Resources.Arrow_menu_open; - btnToggleHighlightPanel.Location = new Point(1832, 1); - btnToggleHighlightPanel.Name = "btnToggleHighlightPanel"; - btnToggleHighlightPanel.Size = new Size(20, 21); - btnToggleHighlightPanel.TabIndex = 6; - helpToolTip.SetToolTip(btnToggleHighlightPanel, "Open or close a list with saved filters"); - btnToggleHighlightPanel.UseVisualStyleBackColor = true; - btnToggleHighlightPanel.SizeChanged += OnButtonSizeChanged; - btnToggleHighlightPanel.Click += OnToggleHighlightPanelButtonClick; - // - // highlightSplitContainer - // - highlightSplitContainer.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; - highlightSplitContainer.BorderStyle = BorderStyle.FixedSingle; - highlightSplitContainer.FixedPanel = FixedPanel.Panel2; - highlightSplitContainer.Location = new Point(0, 3); - highlightSplitContainer.Name = "highlightSplitContainer"; - // - // highlightSplitContainer.Panel1 - // - highlightSplitContainer.Panel1.Controls.Add(filterGridView); - highlightSplitContainer.Panel1MinSize = 100; - // - // highlightSplitContainer.Panel2 - // - highlightSplitContainer.Panel2.Controls.Add(highlightSplitContainerBackPanel); - highlightSplitContainer.Panel2MinSize = 350; - highlightSplitContainer.Size = new Size(1829, 432); - highlightSplitContainer.SplitterDistance = 1475; - highlightSplitContainer.TabIndex = 2; - // - // filterGridView - // - filterGridView.AllowUserToAddRows = false; - filterGridView.AllowUserToDeleteRows = false; - filterGridView.AllowUserToOrderColumns = true; - filterGridView.AllowUserToResizeRows = false; - filterGridView.BackgroundColor = SystemColors.Window; - filterGridView.BorderStyle = BorderStyle.None; - filterGridView.CellBorderStyle = DataGridViewCellBorderStyle.None; - filterGridView.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; - filterGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; - filterGridView.ContextMenuStrip = filterContextMenuStrip; - filterGridView.Dock = DockStyle.Fill; - filterGridView.EditMode = DataGridViewEditMode.EditProgrammatically; - filterGridView.EditModeMenuStrip = null; - filterGridView.ImeMode = ImeMode.Disable; - filterGridView.Location = new Point(0, 0); - filterGridView.Margin = new Padding(0); - filterGridView.Name = "filterGridView"; - filterGridView.PaintWithOverlays = false; - filterGridView.ReadOnly = true; - filterGridView.RowHeadersVisible = false; - filterGridView.RowHeadersWidth = 62; - filterGridView.RowTemplate.Height = 15; - filterGridView.RowTemplate.ReadOnly = true; - filterGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; - filterGridView.ShowCellErrors = false; - filterGridView.ShowCellToolTips = false; - filterGridView.ShowEditingIcon = false; - filterGridView.ShowRowErrors = false; - filterGridView.Size = new Size(1473, 430); - filterGridView.TabIndex = 1; - filterGridView.VirtualMode = true; - filterGridView.CellContextMenuStripNeeded += OnFilterGridViewCellContextMenuStripNeeded; - filterGridView.CellDoubleClick += OnFilterGridViewCellDoubleClick; - filterGridView.ColumnDividerDoubleClick += OnFilterGridViewColumnDividerDoubleClick; - filterGridView.RowHeightInfoNeeded += OnFilterGridViewRowHeightInfoNeeded; - filterGridView.Enter += OnFilterGridViewEnter; - filterGridView.KeyDown += OnFilterGridViewKeyDown; - filterGridView.Leave += OnFilterGridViewLeave; - // - // filterContextMenuStrip - // - filterContextMenuStrip.ImageScalingSize = new Size(24, 24); - filterContextMenuStrip.Items.AddRange(new ToolStripItem[] { setBookmarksOnSelectedLinesToolStripMenuItem, filterToTabToolStripMenuItem, markFilterHitsInLogViewToolStripMenuItem }); - filterContextMenuStrip.Name = "filterContextMenuStrip"; - filterContextMenuStrip.Size = new Size(243, 70); - // - // setBookmarksOnSelectedLinesToolStripMenuItem - // - setBookmarksOnSelectedLinesToolStripMenuItem.Name = "setBookmarksOnSelectedLinesToolStripMenuItem"; - setBookmarksOnSelectedLinesToolStripMenuItem.Size = new Size(242, 22); - setBookmarksOnSelectedLinesToolStripMenuItem.Text = "Set bookmarks on selected lines"; - setBookmarksOnSelectedLinesToolStripMenuItem.Click += OnSetBookmarksOnSelectedLinesToolStripMenuItemClick; - // - // filterToTabToolStripMenuItem - // - filterToTabToolStripMenuItem.Name = "filterToTabToolStripMenuItem"; - filterToTabToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.Shift | Keys.T; - filterToTabToolStripMenuItem.Size = new Size(242, 22); - filterToTabToolStripMenuItem.Text = "Filter to new tab"; - filterToTabToolStripMenuItem.Click += OnFilterToTabToolStripMenuItemClick; - // - // markFilterHitsInLogViewToolStripMenuItem - // - markFilterHitsInLogViewToolStripMenuItem.Name = "markFilterHitsInLogViewToolStripMenuItem"; - markFilterHitsInLogViewToolStripMenuItem.Size = new Size(242, 22); - markFilterHitsInLogViewToolStripMenuItem.Text = "Mark filter hits in log view"; - markFilterHitsInLogViewToolStripMenuItem.Click += OnMarkFilterHitsInLogViewToolStripMenuItemClick; - // - // highlightSplitContainerBackPanel - // - highlightSplitContainerBackPanel.Controls.Add(hideFilterListOnLoadCheckBox); - highlightSplitContainerBackPanel.Controls.Add(filterDownButton); - highlightSplitContainerBackPanel.Controls.Add(filterUpButton); - highlightSplitContainerBackPanel.Controls.Add(filterOnLoadCheckBox); - highlightSplitContainerBackPanel.Controls.Add(saveFilterButton); - highlightSplitContainerBackPanel.Controls.Add(deleteFilterButton); - highlightSplitContainerBackPanel.Controls.Add(filterListBox); - highlightSplitContainerBackPanel.Dock = DockStyle.Fill; - highlightSplitContainerBackPanel.Location = new Point(0, 0); - highlightSplitContainerBackPanel.Name = "highlightSplitContainerBackPanel"; - highlightSplitContainerBackPanel.Size = new Size(348, 430); - highlightSplitContainerBackPanel.TabIndex = 1; - // - // hideFilterListOnLoadCheckBox - // - hideFilterListOnLoadCheckBox.AutoSize = true; - hideFilterListOnLoadCheckBox.Location = new Point(258, 147); - hideFilterListOnLoadCheckBox.Name = "hideFilterListOnLoadCheckBox"; - hideFilterListOnLoadCheckBox.Size = new Size(71, 17); - hideFilterListOnLoadCheckBox.TabIndex = 20; - hideFilterListOnLoadCheckBox.Text = "Auto hide"; - helpToolTip.SetToolTip(hideFilterListOnLoadCheckBox, "Hides the filter list after loading a filter"); - hideFilterListOnLoadCheckBox.UseVisualStyleBackColor = true; - hideFilterListOnLoadCheckBox.MouseClick += OnHideFilterListOnLoadCheckBoxMouseClick; - // - // filterDownButton - // - filterDownButton.BackgroundImage = Resources.ArrowDown; - filterDownButton.BackgroundImageLayout = ImageLayout.Stretch; - filterDownButton.Location = new Point(296, 85); - filterDownButton.Name = "filterDownButton"; - filterDownButton.Size = new Size(35, 35); - filterDownButton.TabIndex = 19; - helpToolTip.SetToolTip(filterDownButton, "Move the selected entry down in the list"); - filterDownButton.UseVisualStyleBackColor = true; - filterDownButton.SizeChanged += OnButtonSizeChanged; - filterDownButton.Click += OnFilterDownButtonClick; - // - // filterUpButton - // - filterUpButton.BackgroundImage = Resources.ArrowUp; - filterUpButton.BackgroundImageLayout = ImageLayout.Stretch; - filterUpButton.Location = new Point(258, 85); - filterUpButton.Name = "filterUpButton"; - filterUpButton.Size = new Size(35, 35); - filterUpButton.TabIndex = 18; - helpToolTip.SetToolTip(filterUpButton, "Move the selected entry up in the list"); - filterUpButton.UseVisualStyleBackColor = true; - filterUpButton.SizeChanged += OnButtonSizeChanged; - filterUpButton.Click += OnFilterUpButtonClick; - // - // filterOnLoadCheckBox - // - filterOnLoadCheckBox.AutoSize = true; - filterOnLoadCheckBox.Location = new Point(258, 123); - filterOnLoadCheckBox.Name = "filterOnLoadCheckBox"; - filterOnLoadCheckBox.Size = new Size(71, 17); - filterOnLoadCheckBox.TabIndex = 17; - filterOnLoadCheckBox.Text = "Auto start"; - helpToolTip.SetToolTip(filterOnLoadCheckBox, "Start immediate filtering after loading a saved filter"); - filterOnLoadCheckBox.UseVisualStyleBackColor = true; - filterOnLoadCheckBox.KeyPress += OnFilterOnLoadCheckBoxKeyPress; - filterOnLoadCheckBox.MouseClick += OnFilterOnLoadCheckBoxMouseClick; - // - // saveFilterButton - // - saveFilterButton.Location = new Point(258, 11); - saveFilterButton.Name = "saveFilterButton"; - saveFilterButton.Size = new Size(75, 35); - saveFilterButton.TabIndex = 16; - saveFilterButton.Text = "Save filter"; - saveFilterButton.UseVisualStyleBackColor = true; - saveFilterButton.Click += OnSaveFilterButtonClick; - // - // deleteFilterButton - // - deleteFilterButton.Location = new Point(258, 47); - deleteFilterButton.Name = "deleteFilterButton"; - deleteFilterButton.Size = new Size(75, 35); - deleteFilterButton.TabIndex = 3; - deleteFilterButton.Text = "Delete"; - deleteFilterButton.UseVisualStyleBackColor = true; - deleteFilterButton.Click += OnDeleteFilterButtonClick; - // - // filterListBox - // - filterListBox.ContextMenuStrip = filterListContextMenuStrip; - filterListBox.Dock = DockStyle.Left; - filterListBox.DrawMode = DrawMode.OwnerDrawFixed; - filterListBox.Font = new Font("Courier New", 12F, FontStyle.Regular, GraphicsUnit.Point, 0); - filterListBox.FormattingEnabled = true; - filterListBox.IntegralHeight = false; - filterListBox.ItemHeight = 25; - filterListBox.Location = new Point(0, 0); - filterListBox.Name = "filterListBox"; - filterListBox.Size = new Size(252, 430); - filterListBox.TabIndex = 0; - helpToolTip.SetToolTip(filterListBox, "Doubleclick to load a saved filter"); - filterListBox.DrawItem += OnFilterListBoxDrawItem; - filterListBox.MouseDoubleClick += OnFilterListBoxMouseDoubleClick; - // - // filterListContextMenuStrip - // - filterListContextMenuStrip.ImageScalingSize = new Size(24, 24); - filterListContextMenuStrip.Items.AddRange(new ToolStripItem[] { colorToolStripMenuItem }); - filterListContextMenuStrip.Name = "filterListContextMenuStrip"; - filterListContextMenuStrip.Size = new Size(113, 26); - // - // colorToolStripMenuItem - // - colorToolStripMenuItem.Name = "colorToolStripMenuItem"; - colorToolStripMenuItem.Size = new Size(112, 22); - colorToolStripMenuItem.Text = "Color..."; - colorToolStripMenuItem.Click += OnColorToolStripMenuItemClick; - // - // pnlFilterInput - // - pnlFilterInput.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - pnlFilterInput.Controls.Add(filterSplitContainer); - pnlFilterInput.Location = new Point(3, 2); - pnlFilterInput.Name = "pnlFilterInput"; - pnlFilterInput.Size = new Size(1855, 46); - pnlFilterInput.TabIndex = 0; - // - // filterSplitContainer - // - filterSplitContainer.Dock = DockStyle.Fill; - filterSplitContainer.Location = new Point(0, 0); - filterSplitContainer.Name = "filterSplitContainer"; - // - // filterSplitContainer.Panel1 - // - filterSplitContainer.Panel1.Controls.Add(filterComboBox); - filterSplitContainer.Panel1.Controls.Add(lblTextFilter); - filterSplitContainer.Panel1MinSize = 200; - // - // filterSplitContainer.Panel2 - // - filterSplitContainer.Panel2.Controls.Add(advancedButton); - filterSplitContainer.Panel2.Controls.Add(syncFilterCheckBox); - filterSplitContainer.Panel2.Controls.Add(lblFilterCount); - filterSplitContainer.Panel2.Controls.Add(filterTailCheckBox); - filterSplitContainer.Panel2.Controls.Add(filterRegexCheckBox); - filterSplitContainer.Panel2.Controls.Add(filterCaseSensitiveCheckBox); - filterSplitContainer.Panel2.Controls.Add(filterSearchButton); - filterSplitContainer.Panel2MinSize = 550; - filterSplitContainer.Size = new Size(1855, 46); - filterSplitContainer.SplitterDistance = 518; - filterSplitContainer.TabIndex = 11; - filterSplitContainer.MouseDoubleClick += OnFilterSplitContainerMouseDoubleClick; - filterSplitContainer.MouseDown += OnFilterSplitContainerMouseDown; - filterSplitContainer.MouseMove += OnFilterSplitContainerMouseMove; - filterSplitContainer.MouseUp += OnFilterSplitContainerMouseUp; - // - // filterComboBox - // - filterComboBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; - filterComboBox.Font = new Font("Courier New", 12F, FontStyle.Regular, GraphicsUnit.Point, 0); - filterComboBox.FormattingEnabled = true; - filterComboBox.Location = new Point(89, 5); - filterComboBox.Name = "filterComboBox"; - filterComboBox.Size = new Size(426, 26); - filterComboBox.TabIndex = 4; - helpToolTip.SetToolTip(filterComboBox, "Search string for the filter"); - filterComboBox.TextChanged += OnFilterComboBoxTextChanged; - filterComboBox.KeyDown += OnFilterComboBoxKeyDown; - // - // lblTextFilter - // - lblTextFilter.AutoSize = true; - lblTextFilter.Location = new Point(5, 5); - lblTextFilter.Name = "lblTextFilter"; - lblTextFilter.Size = new Size(53, 13); - lblTextFilter.TabIndex = 3; - lblTextFilter.Text = "Text &filter:"; - // - // advancedButton - // - advancedButton.DialogResult = DialogResult.Cancel; - advancedButton.Image = (Image)resources.GetObject("advancedButton.Image"); - advancedButton.ImageAlign = ContentAlignment.MiddleRight; - advancedButton.Location = new Point(539, 5); - advancedButton.Name = "advancedButton"; - advancedButton.Size = new Size(110, 35); - advancedButton.TabIndex = 17; - advancedButton.Text = "Show advanced..."; - helpToolTip.SetToolTip(advancedButton, "Toggel the advanced filter options panel"); - advancedButton.UseVisualStyleBackColor = true; - advancedButton.Click += OnAdvancedButtonClick; - // - // syncFilterCheckBox - // - syncFilterCheckBox.AutoSize = true; - syncFilterCheckBox.Location = new Point(467, 5); - syncFilterCheckBox.Name = "syncFilterCheckBox"; - syncFilterCheckBox.Size = new Size(50, 17); - syncFilterCheckBox.TabIndex = 16; - syncFilterCheckBox.Text = "Sync"; - helpToolTip.SetToolTip(syncFilterCheckBox, "Sync the current selected line in the filter view to the selection in the log file view"); - syncFilterCheckBox.UseVisualStyleBackColor = true; - syncFilterCheckBox.CheckedChanged += OnSyncFilterCheckBoxCheckedChanged; - // - // lblFilterCount - // - lblFilterCount.Anchor = AnchorStyles.Right; - lblFilterCount.BorderStyle = BorderStyle.Fixed3D; - lblFilterCount.Location = new Point(1259, 8); - lblFilterCount.Name = "lblFilterCount"; - lblFilterCount.Size = new Size(71, 21); - lblFilterCount.TabIndex = 15; - lblFilterCount.Text = "0"; - lblFilterCount.TextAlign = ContentAlignment.MiddleRight; - // - // filterTailCheckBox - // - filterTailCheckBox.AutoSize = true; - filterTailCheckBox.Location = new Point(367, 5); - filterTailCheckBox.Name = "filterTailCheckBox"; - filterTailCheckBox.Size = new Size(64, 17); - filterTailCheckBox.TabIndex = 14; - filterTailCheckBox.Text = "Filter tail"; - helpToolTip.SetToolTip(filterTailCheckBox, "Filter tailed file content (keeps filter view up to date on file changes)"); - filterTailCheckBox.UseVisualStyleBackColor = true; - // - // filterRegexCheckBox - // - filterRegexCheckBox.AutoSize = true; - filterRegexCheckBox.Location = new Point(283, 5); - filterRegexCheckBox.Name = "filterRegexCheckBox"; - filterRegexCheckBox.Size = new Size(57, 17); - filterRegexCheckBox.TabIndex = 13; - filterRegexCheckBox.Text = "Regex"; - helpToolTip.SetToolTip(filterRegexCheckBox, "Use regular expressions. (right-click for RegEx helper window)"); - filterRegexCheckBox.UseVisualStyleBackColor = true; - filterRegexCheckBox.CheckedChanged += OnFilterRegexCheckBoxCheckedChanged; - filterRegexCheckBox.MouseUp += OnFilterRegexCheckBoxMouseUp; - // - // filterCaseSensitiveCheckBox - // - filterCaseSensitiveCheckBox.AutoSize = true; - filterCaseSensitiveCheckBox.Location = new Point(137, 5); - filterCaseSensitiveCheckBox.Name = "filterCaseSensitiveCheckBox"; - filterCaseSensitiveCheckBox.Size = new Size(94, 17); - filterCaseSensitiveCheckBox.TabIndex = 12; - filterCaseSensitiveCheckBox.Text = "Case sensitive"; - helpToolTip.SetToolTip(filterCaseSensitiveCheckBox, "Makes the filter case sensitive"); - filterCaseSensitiveCheckBox.UseVisualStyleBackColor = true; - filterCaseSensitiveCheckBox.CheckedChanged += OnFilterCaseSensitiveCheckBoxCheckedChanged; - // - // filterSearchButton - // - filterSearchButton.Image = (Image)resources.GetObject("filterSearchButton.Image"); - filterSearchButton.ImageAlign = ContentAlignment.MiddleRight; - filterSearchButton.Location = new Point(3, 5); - filterSearchButton.Name = "filterSearchButton"; - filterSearchButton.Size = new Size(128, 35); - filterSearchButton.TabIndex = 11; - filterSearchButton.Text = "Search"; - helpToolTip.SetToolTip(filterSearchButton, "Start the filter search"); - filterSearchButton.UseVisualStyleBackColor = true; - filterSearchButton.Click += OnFilterSearchButtonClick; - // - // bookmarkContextMenuStrip - // - bookmarkContextMenuStrip.ImageScalingSize = new Size(24, 24); - bookmarkContextMenuStrip.Items.AddRange(new ToolStripItem[] { deleteBookmarksToolStripMenuItem }); - bookmarkContextMenuStrip.Name = "bookmarkContextMenuStrip"; - bookmarkContextMenuStrip.Size = new Size(68, 26); - // - // deleteBookmarksToolStripMenuItem - // - deleteBookmarksToolStripMenuItem.Name = "deleteBookmarksToolStripMenuItem"; - deleteBookmarksToolStripMenuItem.Size = new Size(67, 22); - // - // columnContextMenuStrip - // - 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.Opening += OnColumnContextMenuStripOpening; - // - // freezeLeftColumnsUntilHereToolStripMenuItem - // - freezeLeftColumnsUntilHereToolStripMenuItem.Name = "freezeLeftColumnsUntilHereToolStripMenuItem"; - freezeLeftColumnsUntilHereToolStripMenuItem.Size = new Size(229, 22); - freezeLeftColumnsUntilHereToolStripMenuItem.Text = "Freeze left columns until here"; - freezeLeftColumnsUntilHereToolStripMenuItem.Click += OnFreezeLeftColumnsUntilHereToolStripMenuItemClick; - // - // menuToolStripSeparator4 - // - menuToolStripSeparator4.Name = "menuToolStripSeparator4"; - menuToolStripSeparator4.Size = new Size(226, 6); - // - // moveToLastColumnToolStripMenuItem - // - moveToLastColumnToolStripMenuItem.Name = "moveToLastColumnToolStripMenuItem"; - moveToLastColumnToolStripMenuItem.Size = new Size(229, 22); - moveToLastColumnToolStripMenuItem.Text = "Move to last column"; - moveToLastColumnToolStripMenuItem.ToolTipText = "Move this column to the last position"; - moveToLastColumnToolStripMenuItem.Click += OnMoveToLastColumnToolStripMenuItemClick; - // - // moveLeftToolStripMenuItem - // - moveLeftToolStripMenuItem.Name = "moveLeftToolStripMenuItem"; - moveLeftToolStripMenuItem.Size = new Size(229, 22); - moveLeftToolStripMenuItem.Text = "Move left"; - moveLeftToolStripMenuItem.Click += OnMoveLeftToolStripMenuItemClick; - // - // moveRightToolStripMenuItem - // - moveRightToolStripMenuItem.Name = "moveRightToolStripMenuItem"; - moveRightToolStripMenuItem.Size = new Size(229, 22); - moveRightToolStripMenuItem.Text = "Move right"; - moveRightToolStripMenuItem.Click += OnMoveRightToolStripMenuItemClick; - // - // menuToolStripSeparator5 - // - menuToolStripSeparator5.Name = "menuToolStripSeparator5"; - menuToolStripSeparator5.Size = new Size(226, 6); - // - // hideColumnToolStripMenuItem - // - hideColumnToolStripMenuItem.Name = "hideColumnToolStripMenuItem"; - hideColumnToolStripMenuItem.Size = new Size(229, 22); - hideColumnToolStripMenuItem.Text = "Hide column"; - hideColumnToolStripMenuItem.ToolTipText = "Hide this column"; - hideColumnToolStripMenuItem.Click += OnHideColumnToolStripMenuItemClick; - // - // restoreColumnsToolStripMenuItem - // - restoreColumnsToolStripMenuItem.Name = "restoreColumnsToolStripMenuItem"; - restoreColumnsToolStripMenuItem.Size = new Size(229, 22); - restoreColumnsToolStripMenuItem.Text = "Restore columns"; - restoreColumnsToolStripMenuItem.Click += OnRestoreColumnsToolStripMenuItemClick; - // - // menuToolStripSeparator6 - // - menuToolStripSeparator6.Name = "menuToolStripSeparator6"; - menuToolStripSeparator6.Size = new Size(226, 6); - // - // allColumnsToolStripMenuItem - // - allColumnsToolStripMenuItem.Name = "allColumnsToolStripMenuItem"; - allColumnsToolStripMenuItem.Size = new Size(229, 22); - allColumnsToolStripMenuItem.Text = "Scroll to column..."; - // - // editModeContextMenuStrip - // - editModeContextMenuStrip.ImageScalingSize = new Size(24, 24); - editModeContextMenuStrip.Items.AddRange(new ToolStripItem[] { editModecopyToolStripMenuItem, highlightSelectionInLogFileToolStripMenuItem, highlightSelectionInLogFilewordModeToolStripMenuItem, filterForSelectionToolStripMenuItem, setSelectedTextAsBookmarkCommentToolStripMenuItem }); - editModeContextMenuStrip.Name = "editModeContextMenuStrip"; - editModeContextMenuStrip.Size = new Size(344, 114); - // - // editModecopyToolStripMenuItem - // - editModecopyToolStripMenuItem.Name = "editModecopyToolStripMenuItem"; - editModecopyToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C; - editModecopyToolStripMenuItem.Size = new Size(343, 22); - editModecopyToolStripMenuItem.Text = "Copy"; - editModecopyToolStripMenuItem.Click += OnEditModeCopyToolStripMenuItemClick; - // - // highlightSelectionInLogFileToolStripMenuItem - // - highlightSelectionInLogFileToolStripMenuItem.Name = "highlightSelectionInLogFileToolStripMenuItem"; - highlightSelectionInLogFileToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.H; - highlightSelectionInLogFileToolStripMenuItem.Size = new Size(343, 22); - highlightSelectionInLogFileToolStripMenuItem.Text = "Highlight selection in log file (full line)"; - highlightSelectionInLogFileToolStripMenuItem.Click += OnHighlightSelectionInLogFileToolStripMenuItemClick; - // - // highlightSelectionInLogFilewordModeToolStripMenuItem - // - highlightSelectionInLogFilewordModeToolStripMenuItem.Name = "highlightSelectionInLogFilewordModeToolStripMenuItem"; - highlightSelectionInLogFilewordModeToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; - highlightSelectionInLogFilewordModeToolStripMenuItem.Size = new Size(343, 22); - highlightSelectionInLogFilewordModeToolStripMenuItem.Text = "Highlight selection in log file (word mode)"; - highlightSelectionInLogFilewordModeToolStripMenuItem.Click += OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick; - // - // filterForSelectionToolStripMenuItem - // - filterForSelectionToolStripMenuItem.Name = "filterForSelectionToolStripMenuItem"; - filterForSelectionToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F; - filterForSelectionToolStripMenuItem.Size = new Size(343, 22); - filterForSelectionToolStripMenuItem.Text = "Filter for selection"; - filterForSelectionToolStripMenuItem.Click += OnFilterForSelectionToolStripMenuItemClick; - // - // setSelectedTextAsBookmarkCommentToolStripMenuItem - // - setSelectedTextAsBookmarkCommentToolStripMenuItem.Name = "setSelectedTextAsBookmarkCommentToolStripMenuItem"; - setSelectedTextAsBookmarkCommentToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.B; - setSelectedTextAsBookmarkCommentToolStripMenuItem.Size = new Size(343, 22); - setSelectedTextAsBookmarkCommentToolStripMenuItem.Text = "Set selected text as bookmark comment"; - setSelectedTextAsBookmarkCommentToolStripMenuItem.Click += OnSetSelectedTextAsBookmarkCommentToolStripMenuItemClick; - // - // LogWindow - // - ClientSize = new Size(1862, 1104); - ControlBox = false; - Controls.Add(splitContainerLogWindow); - Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - FormBorderStyle = FormBorderStyle.None; - Icon = (Icon)resources.GetObject("$this.Icon"); - Margin = new Padding(0); - MaximizeBox = false; - MinimizeBox = false; - Name = "LogWindow"; - ShowIcon = false; - ShowInTaskbar = false; - SizeGripStyle = SizeGripStyle.Hide; - SizeChanged += OnLogWindowSizeChanged; - Enter += OnLogWindowEnter; - KeyDown += OnLogWindowKeyDown; - Leave += OnLogWindowLeave; - splitContainerLogWindow.Panel1.ResumeLayout(false); - splitContainerLogWindow.Panel2.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)splitContainerLogWindow).EndInit(); - splitContainerLogWindow.ResumeLayout(false); - tableLayoutPanel1.ResumeLayout(false); - columnFinderPanel.ResumeLayout(false); - columnFinderPanel.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); - dataGridContextMenuStrip.ResumeLayout(false); - advancedBackPanel.ResumeLayout(false); - advancedFilterSplitContainer.Panel1.ResumeLayout(false); - advancedFilterSplitContainer.Panel2.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)advancedFilterSplitContainer).EndInit(); - advancedFilterSplitContainer.ResumeLayout(false); - pnlProFilter.ResumeLayout(false); - pnlProFilter.PerformLayout(); - panelBackgroundAdvancedFilterSplitContainer.ResumeLayout(false); - highlightSplitContainer.Panel1.ResumeLayout(false); - highlightSplitContainer.Panel2.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)highlightSplitContainer).EndInit(); - highlightSplitContainer.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)filterGridView).EndInit(); - filterContextMenuStrip.ResumeLayout(false); - highlightSplitContainerBackPanel.ResumeLayout(false); - highlightSplitContainerBackPanel.PerformLayout(); - filterListContextMenuStrip.ResumeLayout(false); - pnlFilterInput.ResumeLayout(false); - filterSplitContainer.Panel1.ResumeLayout(false); - filterSplitContainer.Panel1.PerformLayout(); - filterSplitContainer.Panel2.ResumeLayout(false); - filterSplitContainer.Panel2.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)filterSplitContainer).EndInit(); - filterSplitContainer.ResumeLayout(false); - bookmarkContextMenuStrip.ResumeLayout(false); - columnContextMenuStrip.ResumeLayout(false); - editModeContextMenuStrip.ResumeLayout(false); - ResumeLayout(false); - } - - #endregion - - private System.Windows.Forms.SplitContainer splitContainerLogWindow; - private System.Windows.Forms.Panel pnlFilterInput; - private BufferedDataGridView dataGridView; - private BufferedDataGridView filterGridView; - private System.Windows.Forms.SplitContainer advancedFilterSplitContainer; - private System.Windows.Forms.Panel pnlProFilter; - private System.Windows.Forms.Button btnFilterToTab; - private KnobControl filterKnobForeSpread; - private System.Windows.Forms.Label lblForeSpread; - private KnobControl filterKnobBackSpread; - private System.Windows.Forms.Label lblBackSpread; - private System.Windows.Forms.Panel pnlProFilterLabel; - private System.Windows.Forms.CheckBox invertFilterCheckBox; - private System.Windows.Forms.Label fuzzyLabel; - private KnobControl fuzzyKnobControl; - private System.Windows.Forms.CheckBox rangeCheckBox; - private System.Windows.Forms.ComboBox filterRangeComboBox; - private System.Windows.Forms.ContextMenuStrip dataGridContextMenuStrip; - private System.Windows.Forms.ToolStripMenuItem copyToTabToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem scrollAllTabsToTimestampToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem locateLineInOriginalFileToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem toggleBoomarkToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem markEditModeToolStripMenuItem; - private System.Windows.Forms.ContextMenuStrip bookmarkContextMenuStrip; - private System.Windows.Forms.ToolStripMenuItem deleteBookmarksToolStripMenuItem; - private System.Windows.Forms.CheckBox columnRestrictCheckBox; - private System.Windows.Forms.Button columnButton; - private System.Windows.Forms.ContextMenuStrip columnContextMenuStrip; - private System.Windows.Forms.ToolStripMenuItem freezeLeftColumnsUntilHereToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem moveToLastColumnToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem moveLeftToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem moveRightToolStripMenuItem; - private TimeSpreadingControl timeSpreadingControl; - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; - private System.Windows.Forms.ToolStripMenuItem bookmarkCommentToolStripMenuItem; - private System.Windows.Forms.ContextMenuStrip editModeContextMenuStrip; - private System.Windows.Forms.ToolStripMenuItem highlightSelectionInLogFileToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem editModecopyToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem tempHighlightsToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem removeAllToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem makePermanentToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem filterForSelectionToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem setSelectedTextAsBookmarkCommentToolStripMenuItem; - private System.Windows.Forms.ToolTip helpToolTip; - private System.Windows.Forms.SplitContainer highlightSplitContainer; - private System.Windows.Forms.Button btnToggleHighlightPanel; - private System.Windows.Forms.Panel highlightSplitContainerBackPanel; - private System.Windows.Forms.Button saveFilterButton; - private System.Windows.Forms.Button deleteFilterButton; - private System.Windows.Forms.ListBox filterListBox; - private System.Windows.Forms.ContextMenuStrip filterContextMenuStrip; - private System.Windows.Forms.ToolStripMenuItem setBookmarksOnSelectedLinesToolStripMenuItem; - private System.Windows.Forms.CheckBox filterOnLoadCheckBox; - private System.Windows.Forms.ToolStripMenuItem markCurrentFilterRangeToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem syncTimestampsToToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem freeThisWindowFromTimeSyncToolStripMenuItem; - private System.Windows.Forms.Button filterDownButton; - private System.Windows.Forms.Button filterUpButton; - private System.Windows.Forms.ContextMenuStrip filterListContextMenuStrip; - private System.Windows.Forms.ToolStripMenuItem colorToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem filterToTabToolStripMenuItem; - private System.Windows.Forms.CheckBox hideFilterListOnLoadCheckBox; - private System.Windows.Forms.Panel advancedBackPanel; - private System.Windows.Forms.ToolStripMenuItem markFilterHitsInLogViewToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem highlightSelectionInLogFilewordModeToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem hideColumnToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem restoreColumnsToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem allColumnsToolStripMenuItem; - private System.Windows.Forms.Label columnNamesLabel; - private System.Windows.Forms.Panel columnFinderPanel; - private System.Windows.Forms.ComboBox columnComboBox; - private System.Windows.Forms.Label lblColumnName; - private System.Windows.Forms.SplitContainer filterSplitContainer; - private System.Windows.Forms.Label lblTextFilter; - private System.Windows.Forms.ComboBox filterComboBox; - private System.Windows.Forms.Button advancedButton; - private System.Windows.Forms.CheckBox syncFilterCheckBox; - private System.Windows.Forms.Label lblFilterCount; - private System.Windows.Forms.CheckBox filterTailCheckBox; - private System.Windows.Forms.CheckBox filterRegexCheckBox; - 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; - } -} +using LogExpert.Dialogs; +using System; +using System.Drawing; +using System.IO; +using System.Windows.Forms; + +namespace LogExpert.UI.Controls.LogWindow +{ + partial class LogWindow + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent () + { + components = new System.ComponentModel.Container(); + var resources = new System.ComponentModel.ComponentResourceManager(typeof(LogWindow)); + splitContainerLogWindow = new SplitContainer(); + tableLayoutPanel1 = new TableLayoutPanel(); + columnFinderPanel = new Panel(); + columnComboBox = new ComboBox(); + lblColumnName = new Label(); + dataGridView = new BufferedDataGridView(); + dataGridContextMenuStrip = new ContextMenuStrip(components); + copyToolStripMenuItem = new ToolStripMenuItem(); + copyToTabToolStripMenuItem = new ToolStripMenuItem(); + menuToolStripSeparator1 = new ToolStripSeparator(); + scrollAllTabsToTimestampToolStripMenuItem = new ToolStripMenuItem(); + syncTimestampsToToolStripMenuItem = new ToolStripMenuItem(); + freeThisWindowFromTimeSyncToolStripMenuItem = new ToolStripMenuItem(); + locateLineInOriginalFileToolStripMenuItem = new ToolStripMenuItem(); + menuToolStripSeparator2 = new ToolStripSeparator(); + toggleBoomarkToolStripMenuItem = new ToolStripMenuItem(); + bookmarkCommentToolStripMenuItem = new ToolStripMenuItem(); + markEditModeToolStripMenuItem = new ToolStripMenuItem(); + menuToolStripSeparator3 = new ToolStripSeparator(); + tempHighlightsToolStripMenuItem = new ToolStripMenuItem(); + removeAllToolStripMenuItem = new ToolStripMenuItem(); + makePermanentToolStripMenuItem = new ToolStripMenuItem(); + markCurrentFilterRangeToolStripMenuItem = new ToolStripMenuItem(); + pluginSeparator = new ToolStripSeparator(); + timeSpreadingControl = new TimeSpreadingControl(); + advancedBackPanel = new Panel(); + advancedFilterSplitContainer = new SplitContainer(); + pnlProFilter = new Panel(); + columnButton = new Button(); + columnRestrictCheckBox = new CheckBox(); + rangeCheckBox = new CheckBox(); + filterRangeComboBox = new ComboBox(); + columnNamesLabel = new Label(); + fuzzyLabel = new Label(); + fuzzyKnobControl = new KnobControl(); + invertFilterCheckBox = new CheckBox(); + pnlProFilterLabel = new Panel(); + lblBackSpread = new Label(); + filterKnobBackSpread = new KnobControl(); + lblForeSpread = new Label(); + filterKnobForeSpread = new KnobControl(); + btnFilterToTab = new Button(); + panelBackgroundAdvancedFilterSplitContainer = new Panel(); + btnToggleHighlightPanel = new Button(); + highlightSplitContainer = new SplitContainer(); + filterGridView = new BufferedDataGridView(); + filterContextMenuStrip = new ContextMenuStrip(components); + setBookmarksOnSelectedLinesToolStripMenuItem = new ToolStripMenuItem(); + filterToTabToolStripMenuItem = new ToolStripMenuItem(); + markFilterHitsInLogViewToolStripMenuItem = new ToolStripMenuItem(); + highlightSplitContainerBackPanel = new Panel(); + hideFilterListOnLoadCheckBox = new CheckBox(); + filterDownButton = new Button(); + filterUpButton = new Button(); + filterOnLoadCheckBox = new CheckBox(); + saveFilterButton = new Button(); + deleteFilterButton = new Button(); + filterListBox = new ListBox(); + filterListContextMenuStrip = new ContextMenuStrip(components); + colorToolStripMenuItem = new ToolStripMenuItem(); + pnlFilterInput = new Panel(); + filterSplitContainer = new SplitContainer(); + filterComboBox = new ComboBox(); + lblTextFilter = new Label(); + advancedButton = new Button(); + syncFilterCheckBox = new CheckBox(); + lblFilterCount = new Label(); + filterTailCheckBox = new CheckBox(); + filterRegexCheckBox = new CheckBox(); + filterCaseSensitiveCheckBox = new CheckBox(); + filterSearchButton = new Button(); + bookmarkContextMenuStrip = new ContextMenuStrip(components); + deleteBookmarksToolStripMenuItem = new ToolStripMenuItem(); + columnContextMenuStrip = new ContextMenuStrip(components); + freezeLeftColumnsUntilHereToolStripMenuItem = new ToolStripMenuItem(); + menuToolStripSeparator4 = new ToolStripSeparator(); + moveToLastColumnToolStripMenuItem = new ToolStripMenuItem(); + moveLeftToolStripMenuItem = new ToolStripMenuItem(); + moveRightToolStripMenuItem = new ToolStripMenuItem(); + menuToolStripSeparator5 = new ToolStripSeparator(); + hideColumnToolStripMenuItem = new ToolStripMenuItem(); + restoreColumnsToolStripMenuItem = new ToolStripMenuItem(); + menuToolStripSeparator6 = new ToolStripSeparator(); + allColumnsToolStripMenuItem = new ToolStripMenuItem(); + editModeContextMenuStrip = new ContextMenuStrip(components); + editModecopyToolStripMenuItem = new ToolStripMenuItem(); + highlightSelectionInLogFileToolStripMenuItem = new ToolStripMenuItem(); + highlightSelectionInLogFilewordModeToolStripMenuItem = new ToolStripMenuItem(); + filterForSelectionToolStripMenuItem = new ToolStripMenuItem(); + setSelectedTextAsBookmarkCommentToolStripMenuItem = new ToolStripMenuItem(); + helpToolTip = new ToolTip(components); + ((System.ComponentModel.ISupportInitialize)splitContainerLogWindow).BeginInit(); + splitContainerLogWindow.Panel1.SuspendLayout(); + splitContainerLogWindow.Panel2.SuspendLayout(); + splitContainerLogWindow.SuspendLayout(); + tableLayoutPanel1.SuspendLayout(); + columnFinderPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).BeginInit(); + dataGridContextMenuStrip.SuspendLayout(); + advancedBackPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)advancedFilterSplitContainer).BeginInit(); + advancedFilterSplitContainer.Panel1.SuspendLayout(); + advancedFilterSplitContainer.Panel2.SuspendLayout(); + advancedFilterSplitContainer.SuspendLayout(); + pnlProFilter.SuspendLayout(); + panelBackgroundAdvancedFilterSplitContainer.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)highlightSplitContainer).BeginInit(); + highlightSplitContainer.Panel1.SuspendLayout(); + highlightSplitContainer.Panel2.SuspendLayout(); + highlightSplitContainer.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)filterGridView).BeginInit(); + filterContextMenuStrip.SuspendLayout(); + highlightSplitContainerBackPanel.SuspendLayout(); + filterListContextMenuStrip.SuspendLayout(); + pnlFilterInput.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)filterSplitContainer).BeginInit(); + filterSplitContainer.Panel1.SuspendLayout(); + filterSplitContainer.Panel2.SuspendLayout(); + filterSplitContainer.SuspendLayout(); + bookmarkContextMenuStrip.SuspendLayout(); + columnContextMenuStrip.SuspendLayout(); + editModeContextMenuStrip.SuspendLayout(); + SuspendLayout(); + // + // splitContainerLogWindow + // + splitContainerLogWindow.BorderStyle = BorderStyle.FixedSingle; + splitContainerLogWindow.Dock = DockStyle.Fill; + splitContainerLogWindow.Location = new Point(0, 0); + splitContainerLogWindow.Margin = new Padding(0); + splitContainerLogWindow.Name = "splitContainerLogWindow"; + splitContainerLogWindow.Orientation = Orientation.Horizontal; + // + // splitContainerLogWindow.Panel1 + // + splitContainerLogWindow.Panel1.Controls.Add(tableLayoutPanel1); + splitContainerLogWindow.Panel1MinSize = 50; + // + // splitContainerLogWindow.Panel2 + // + splitContainerLogWindow.Panel2.Controls.Add(advancedBackPanel); + splitContainerLogWindow.Panel2.Controls.Add(pnlFilterInput); + splitContainerLogWindow.Panel2MinSize = 50; + splitContainerLogWindow.Size = new Size(1862, 1104); + splitContainerLogWindow.SplitterDistance = 486; + splitContainerLogWindow.TabIndex = 9; + splitContainerLogWindow.SplitterMoved += OnSplitContainerSplitterMoved; + // + // tableLayoutPanel1 + // + tableLayoutPanel1.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; + tableLayoutPanel1.ColumnCount = 2; + tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle()); + tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 181F)); + tableLayoutPanel1.Controls.Add(columnFinderPanel, 0, 0); + tableLayoutPanel1.Controls.Add(dataGridView, 0, 1); + tableLayoutPanel1.Controls.Add(timeSpreadingControl, 1, 1); + tableLayoutPanel1.Dock = DockStyle.Fill; + tableLayoutPanel1.ForeColor = SystemColors.ControlText; + tableLayoutPanel1.Location = new Point(0, 0); + tableLayoutPanel1.Margin = new Padding(0); + tableLayoutPanel1.Name = "tableLayoutPanel1"; + tableLayoutPanel1.RowCount = 2; + tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 28F)); + tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Percent, 100F)); + tableLayoutPanel1.Size = new Size(1860, 484); + tableLayoutPanel1.TabIndex = 2; + // + // columnFinderPanel + // + columnFinderPanel.Controls.Add(columnComboBox); + columnFinderPanel.Controls.Add(lblColumnName); + columnFinderPanel.Dock = DockStyle.Fill; + columnFinderPanel.Location = new Point(4, 4); + columnFinderPanel.Name = "columnFinderPanel"; + columnFinderPanel.Size = new Size(841, 22); + columnFinderPanel.TabIndex = 2; + // + // columnComboBox + // + columnComboBox.FormattingEnabled = true; + columnComboBox.Location = new Point(125, 1); + columnComboBox.MaxDropDownItems = 15; + columnComboBox.Name = "columnComboBox"; + columnComboBox.Size = new Size(181, 21); + columnComboBox.TabIndex = 1; + helpToolTip.SetToolTip(columnComboBox, "Select column to scroll to"); + columnComboBox.SelectionChangeCommitted += OnColumnComboBoxSelectionChangeCommitted; + columnComboBox.KeyDown += OnColumnComboBoxKeyDown; + columnComboBox.PreviewKeyDown += OnColumnComboBoxPreviewKeyDown; + // + // lblColumnName + // + lblColumnName.AutoSize = true; + lblColumnName.Location = new Point(8, 4); + lblColumnName.Name = "lblColumnName"; + lblColumnName.Size = new Size(74, 13); + lblColumnName.TabIndex = 0; + lblColumnName.Text = "Column name:"; + // + // dataGridView + // + dataGridView.AllowUserToAddRows = false; + dataGridView.AllowUserToDeleteRows = false; + dataGridView.AllowUserToOrderColumns = true; + dataGridView.AllowUserToResizeRows = false; + dataGridView.BackgroundColor = SystemColors.Window; + dataGridView.BorderStyle = BorderStyle.None; + dataGridView.CellBorderStyle = DataGridViewCellBorderStyle.None; + dataGridView.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; + dataGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridView.ContextMenuStrip = dataGridContextMenuStrip; + dataGridView.Dock = DockStyle.Fill; + dataGridView.EditMode = DataGridViewEditMode.EditProgrammatically; + dataGridView.EditModeMenuStrip = null; + dataGridView.ImeMode = ImeMode.Disable; + dataGridView.Location = new Point(1, 30); + dataGridView.Margin = new Padding(0); + dataGridView.Name = "dataGridView"; + dataGridView.PaintWithOverlays = false; + dataGridView.RowHeadersVisible = false; + dataGridView.RowHeadersWidth = 62; + dataGridView.RowTemplate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomLeft; + dataGridView.RowTemplate.DefaultCellStyle.Padding = new Padding(2, 0, 0, 0); + dataGridView.RowTemplate.Height = 15; + dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + dataGridView.ShowCellErrors = false; + dataGridView.ShowCellToolTips = false; + dataGridView.ShowEditingIcon = false; + dataGridView.ShowRowErrors = false; + dataGridView.Size = new Size(847, 453); + dataGridView.TabIndex = 0; + dataGridView.VirtualMode = true; + dataGridView.OverlayDoubleClicked += OnDataGridViewOverlayDoubleClicked; + dataGridView.CellClick += OnDataGridViewCellClick; + dataGridView.CellContentDoubleClick += OnDataGridViewCellContentDoubleClick; + dataGridView.CellContextMenuStripNeeded += OnDataGridViewCellContextMenuStripNeeded; + dataGridView.CellDoubleClick += OnDataGridViewCellDoubleClick; + dataGridView.CellValuePushed += OnDataGridViewCellValuePushed; + dataGridView.RowHeightInfoNeeded += OnDataGridViewRowHeightInfoNeeded; + dataGridView.RowUnshared += OnDataGridViewRowUnshared; + dataGridView.Scroll += OnDataGridViewScroll; + dataGridView.SelectionChanged += OnDataGridViewSelectionChanged; + dataGridView.Paint += OnDataGridViewPaint; + dataGridView.Enter += OnDataGridViewEnter; + dataGridView.KeyDown += OnDataGridViewKeyDown; + dataGridView.Leave += OnDataGridViewLeave; + dataGridView.PreviewKeyDown += OnDataGridViewPreviewKeyDown; + dataGridView.Resize += OnDataGridViewResize; + // + // dataGridContextMenuStrip + // + dataGridContextMenuStrip.ImageScalingSize = new Size(24, 24); + dataGridContextMenuStrip.Items.AddRange(new ToolStripItem[] { copyToolStripMenuItem, copyToTabToolStripMenuItem, menuToolStripSeparator1, scrollAllTabsToTimestampToolStripMenuItem, syncTimestampsToToolStripMenuItem, freeThisWindowFromTimeSyncToolStripMenuItem, locateLineInOriginalFileToolStripMenuItem, menuToolStripSeparator2, toggleBoomarkToolStripMenuItem, bookmarkCommentToolStripMenuItem, markEditModeToolStripMenuItem, menuToolStripSeparator3, tempHighlightsToolStripMenuItem, markCurrentFilterRangeToolStripMenuItem, pluginSeparator }); + dataGridContextMenuStrip.Name = "dataGridContextMenuStrip"; + dataGridContextMenuStrip.Size = new Size(287, 270); + dataGridContextMenuStrip.Opening += OnDataGridContextMenuStripOpening; + // + // copyToolStripMenuItem + // + copyToolStripMenuItem.Name = "copyToolStripMenuItem"; + copyToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C; + copyToolStripMenuItem.Size = new Size(286, 22); + copyToolStripMenuItem.Text = "Copy to clipboard"; + copyToolStripMenuItem.Click += OnCopyToolStripMenuItemClick; + // + // copyToTabToolStripMenuItem + // + copyToTabToolStripMenuItem.Name = "copyToTabToolStripMenuItem"; + copyToTabToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T; + copyToTabToolStripMenuItem.Size = new Size(286, 22); + copyToTabToolStripMenuItem.Text = "Copy to new tab"; + copyToTabToolStripMenuItem.ToolTipText = "Copy marked lines into a new tab window"; + copyToTabToolStripMenuItem.Click += OnCopyToTabToolStripMenuItemClick; + // + // menuToolStripSeparator1 + // + menuToolStripSeparator1.Name = "menuToolStripSeparator1"; + menuToolStripSeparator1.Size = new Size(283, 6); + // + // scrollAllTabsToTimestampToolStripMenuItem + // + scrollAllTabsToTimestampToolStripMenuItem.Name = "scrollAllTabsToTimestampToolStripMenuItem"; + scrollAllTabsToTimestampToolStripMenuItem.Size = new Size(286, 22); + scrollAllTabsToTimestampToolStripMenuItem.Text = "Scroll all tabs to current timestamp"; + scrollAllTabsToTimestampToolStripMenuItem.ToolTipText = "Scolls all open tabs to the selected timestamp, if possible"; + scrollAllTabsToTimestampToolStripMenuItem.Click += OnScrollAllTabsToTimestampToolStripMenuItemClick; + // + // syncTimestampsToToolStripMenuItem + // + syncTimestampsToToolStripMenuItem.Name = "syncTimestampsToToolStripMenuItem"; + syncTimestampsToToolStripMenuItem.Size = new Size(286, 22); + syncTimestampsToToolStripMenuItem.Text = "Time synced files"; + // + // freeThisWindowFromTimeSyncToolStripMenuItem + // + freeThisWindowFromTimeSyncToolStripMenuItem.Name = "freeThisWindowFromTimeSyncToolStripMenuItem"; + freeThisWindowFromTimeSyncToolStripMenuItem.Size = new Size(286, 22); + freeThisWindowFromTimeSyncToolStripMenuItem.Text = "Free this window from time sync"; + freeThisWindowFromTimeSyncToolStripMenuItem.Click += OnFreeThisWindowFromTimeSyncToolStripMenuItemClick; + // + // locateLineInOriginalFileToolStripMenuItem + // + locateLineInOriginalFileToolStripMenuItem.Name = "locateLineInOriginalFileToolStripMenuItem"; + locateLineInOriginalFileToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L; + locateLineInOriginalFileToolStripMenuItem.Size = new Size(286, 22); + locateLineInOriginalFileToolStripMenuItem.Text = "Locate filtered line in original file"; + locateLineInOriginalFileToolStripMenuItem.Click += OnLocateLineInOriginalFileToolStripMenuItemClick; + // + // menuToolStripSeparator2 + // + menuToolStripSeparator2.Name = "menuToolStripSeparator2"; + menuToolStripSeparator2.Size = new Size(283, 6); + // + // toggleBoomarkToolStripMenuItem + // + toggleBoomarkToolStripMenuItem.Name = "toggleBoomarkToolStripMenuItem"; + toggleBoomarkToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F2; + toggleBoomarkToolStripMenuItem.Size = new Size(286, 22); + toggleBoomarkToolStripMenuItem.Text = "Toggle Boomark"; + toggleBoomarkToolStripMenuItem.Click += OnToggleBoomarkToolStripMenuItemClick; + // + // bookmarkCommentToolStripMenuItem + // + bookmarkCommentToolStripMenuItem.Name = "bookmarkCommentToolStripMenuItem"; + bookmarkCommentToolStripMenuItem.ShortcutKeys = Keys.Alt | Keys.F2; + bookmarkCommentToolStripMenuItem.Size = new Size(286, 22); + bookmarkCommentToolStripMenuItem.Text = "Bookmark comment..."; + bookmarkCommentToolStripMenuItem.ToolTipText = "Edit the comment for a bookmark"; + bookmarkCommentToolStripMenuItem.Click += OnBookmarkCommentToolStripMenuItemClick; + // + // markEditModeToolStripMenuItem + // + markEditModeToolStripMenuItem.Name = "markEditModeToolStripMenuItem"; + markEditModeToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.E; + markEditModeToolStripMenuItem.Size = new Size(286, 22); + markEditModeToolStripMenuItem.Text = "Mark/Edit-Mode"; + markEditModeToolStripMenuItem.Click += OnMarkEditModeToolStripMenuItemClick; + // + // menuToolStripSeparator3 + // + menuToolStripSeparator3.Name = "menuToolStripSeparator3"; + menuToolStripSeparator3.Size = new Size(283, 6); + // + // tempHighlightsToolStripMenuItem + // + tempHighlightsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { removeAllToolStripMenuItem, makePermanentToolStripMenuItem }); + tempHighlightsToolStripMenuItem.Name = "tempHighlightsToolStripMenuItem"; + tempHighlightsToolStripMenuItem.Size = new Size(286, 22); + tempHighlightsToolStripMenuItem.Text = "Temp Highlights"; + // + // removeAllToolStripMenuItem + // + removeAllToolStripMenuItem.Name = "removeAllToolStripMenuItem"; + removeAllToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.Shift | Keys.H; + removeAllToolStripMenuItem.Size = new Size(207, 22); + removeAllToolStripMenuItem.Text = "Remove all"; + removeAllToolStripMenuItem.Click += OnRemoveAllToolStripMenuItemClick; + // + // makePermanentToolStripMenuItem + // + makePermanentToolStripMenuItem.Name = "makePermanentToolStripMenuItem"; + makePermanentToolStripMenuItem.Size = new Size(207, 22); + makePermanentToolStripMenuItem.Text = "Make all permanent"; + makePermanentToolStripMenuItem.Click += OnMakePermanentToolStripMenuItemClick; + // + // markCurrentFilterRangeToolStripMenuItem + // + markCurrentFilterRangeToolStripMenuItem.Name = "markCurrentFilterRangeToolStripMenuItem"; + markCurrentFilterRangeToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.R; + markCurrentFilterRangeToolStripMenuItem.Size = new Size(286, 22); + markCurrentFilterRangeToolStripMenuItem.Text = "Mark current filter range"; + markCurrentFilterRangeToolStripMenuItem.Click += OnMarkCurrentFilterRangeToolStripMenuItemClick; + // + // pluginSeparator + // + pluginSeparator.Name = "pluginSeparator"; + pluginSeparator.Size = new Size(283, 6); + // + // timeSpreadingControl + // + timeSpreadingControl.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Right; + timeSpreadingControl.Font = new Font("Verdana", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + timeSpreadingControl.ForeColor = Color.Teal; + timeSpreadingControl.Location = new Point(1842, 30); + timeSpreadingControl.Margin = new Padding(2, 0, 1, 0); + timeSpreadingControl.Name = "timeSpreadingControl"; + timeSpreadingControl.ReverseAlpha = false; + timeSpreadingControl.Size = new Size(16, 453); + timeSpreadingControl.TabIndex = 1; + // + // advancedBackPanel + // + advancedBackPanel.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + advancedBackPanel.Controls.Add(advancedFilterSplitContainer); + advancedBackPanel.Location = new Point(3, 48); + advancedBackPanel.Name = "advancedBackPanel"; + advancedBackPanel.Size = new Size(1855, 561); + advancedBackPanel.TabIndex = 3; + // + // advancedFilterSplitContainer + // + advancedFilterSplitContainer.Dock = DockStyle.Fill; + advancedFilterSplitContainer.Location = new Point(0, 0); + advancedFilterSplitContainer.Margin = new Padding(0); + advancedFilterSplitContainer.Name = "advancedFilterSplitContainer"; + advancedFilterSplitContainer.Orientation = Orientation.Horizontal; + // + // advancedFilterSplitContainer.Panel1 + // + advancedFilterSplitContainer.Panel1.Controls.Add(pnlProFilter); + advancedFilterSplitContainer.Panel1MinSize = 50; + // + // advancedFilterSplitContainer.Panel2 + // + advancedFilterSplitContainer.Panel2.Controls.Add(panelBackgroundAdvancedFilterSplitContainer); + advancedFilterSplitContainer.Panel2MinSize = 50; + advancedFilterSplitContainer.Size = new Size(1855, 561); + advancedFilterSplitContainer.SplitterDistance = 110; + advancedFilterSplitContainer.Panel2Collapsed = true; + advancedFilterSplitContainer.SplitterWidth = 2; + advancedFilterSplitContainer.TabIndex = 2; + // + // pnlProFilter + // + pnlProFilter.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + pnlProFilter.Controls.Add(columnButton); + pnlProFilter.Controls.Add(columnRestrictCheckBox); + pnlProFilter.Controls.Add(rangeCheckBox); + pnlProFilter.Controls.Add(filterRangeComboBox); + pnlProFilter.Controls.Add(columnNamesLabel); + pnlProFilter.Controls.Add(fuzzyLabel); + pnlProFilter.Controls.Add(fuzzyKnobControl); + pnlProFilter.Controls.Add(invertFilterCheckBox); + pnlProFilter.Controls.Add(pnlProFilterLabel); + pnlProFilter.Controls.Add(lblBackSpread); + pnlProFilter.Controls.Add(filterKnobBackSpread); + pnlProFilter.Controls.Add(lblForeSpread); + pnlProFilter.Controls.Add(filterKnobForeSpread); + pnlProFilter.Controls.Add(btnFilterToTab); + pnlProFilter.Location = new Point(0, 3); + pnlProFilter.Name = "pnlProFilter"; + pnlProFilter.Size = new Size(1852, 80); + pnlProFilter.TabIndex = 0; + // + // columnButton + // + columnButton.Enabled = false; + columnButton.Location = new Point(750, 41); + columnButton.Name = "columnButton"; + columnButton.Size = new Size(85, 35); + columnButton.TabIndex = 15; + columnButton.Text = "Columns..."; + helpToolTip.SetToolTip(columnButton, "Choose columns for 'Column restrict'"); + columnButton.UseVisualStyleBackColor = true; + columnButton.Click += OnColumnButtonClick; + // + // columnRestrictCheckBox + // + columnRestrictCheckBox.AutoSize = true; + columnRestrictCheckBox.Location = new Point(594, 38); + columnRestrictCheckBox.Name = "columnRestrictCheckBox"; + columnRestrictCheckBox.Size = new Size(95, 17); + columnRestrictCheckBox.TabIndex = 14; + columnRestrictCheckBox.Text = "Column restrict"; + helpToolTip.SetToolTip(columnRestrictCheckBox, "Restrict search to columns"); + columnRestrictCheckBox.UseVisualStyleBackColor = true; + columnRestrictCheckBox.CheckedChanged += OnColumnRestrictCheckBoxCheckedChanged; + // + // rangeCheckBox + // + rangeCheckBox.AutoSize = true; + rangeCheckBox.Location = new Point(73, 38); + rangeCheckBox.Name = "rangeCheckBox"; + rangeCheckBox.Size = new Size(93, 17); + rangeCheckBox.TabIndex = 13; + rangeCheckBox.Text = "Range search"; + helpToolTip.SetToolTip(rangeCheckBox, "Enable a special search mode which filters all content between the 2 given search terms."); + rangeCheckBox.UseVisualStyleBackColor = true; + rangeCheckBox.CheckedChanged += OnRangeCheckBoxCheckedChanged; + // + // filterRangeComboBox + // + filterRangeComboBox.Enabled = false; + filterRangeComboBox.FormattingEnabled = true; + filterRangeComboBox.Location = new Point(73, 11); + filterRangeComboBox.Name = "filterRangeComboBox"; + filterRangeComboBox.Size = new Size(207, 21); + filterRangeComboBox.TabIndex = 12; + helpToolTip.SetToolTip(filterRangeComboBox, "2nd search string ('end string') when using the range search"); + filterRangeComboBox.TextChanged += OnFilterRangeComboBoxTextChanged; + // + // columnNamesLabel + // + columnNamesLabel.AutoSize = true; + columnNamesLabel.Location = new Point(841, 41); + columnNamesLabel.Name = "columnNamesLabel"; + columnNamesLabel.Size = new Size(75, 13); + columnNamesLabel.TabIndex = 11; + columnNamesLabel.Text = "column names"; + // + // fuzzyLabel + // + fuzzyLabel.AutoSize = true; + fuzzyLabel.Location = new Point(502, 38); + fuzzyLabel.Name = "fuzzyLabel"; + fuzzyLabel.Size = new Size(56, 13); + fuzzyLabel.TabIndex = 11; + fuzzyLabel.Text = "Fuzzyness"; + // + // fuzzyKnobControl + // + fuzzyKnobControl.DragSensitivity = 6; + fuzzyKnobControl.Font = new Font("Verdana", 6F, FontStyle.Regular, GraphicsUnit.Point, 0); + fuzzyKnobControl.Location = new Point(521, 7); + fuzzyKnobControl.Margin = new Padding(2); + fuzzyKnobControl.MaxValue = 0; + fuzzyKnobControl.MinValue = 0; + fuzzyKnobControl.Name = "fuzzyKnobControl"; + fuzzyKnobControl.Size = new Size(17, 29); + fuzzyKnobControl.TabIndex = 10; + helpToolTip.SetToolTip(fuzzyKnobControl, "Fuzzy search level (0 = fuzzy off)"); + fuzzyKnobControl.Value = 0; + fuzzyKnobControl.ValueChanged += OnFuzzyKnobControlValueChanged; + // + // invertFilterCheckBox + // + invertFilterCheckBox.AutoSize = true; + invertFilterCheckBox.Location = new Point(594, 7); + invertFilterCheckBox.Name = "invertFilterCheckBox"; + invertFilterCheckBox.Size = new Size(86, 17); + invertFilterCheckBox.TabIndex = 8; + invertFilterCheckBox.Text = "Invert Match"; + helpToolTip.SetToolTip(invertFilterCheckBox, "Invert the search result"); + invertFilterCheckBox.UseVisualStyleBackColor = true; + invertFilterCheckBox.CheckedChanged += OnInvertFilterCheckBoxCheckedChanged; + // + // pnlProFilterLabel + // + pnlProFilterLabel.BackgroundImage = LogExpert.Resources.Pro_Filter; + pnlProFilterLabel.BackgroundImageLayout = ImageLayout.Center; + pnlProFilterLabel.Location = new Point(5, 7); + pnlProFilterLabel.Name = "pnlProFilterLabel"; + pnlProFilterLabel.Size = new Size(60, 44); + pnlProFilterLabel.TabIndex = 7; + // + // lblBackSpread + // + lblBackSpread.AutoSize = true; + lblBackSpread.Location = new Point(287, 38); + lblBackSpread.Name = "lblBackSpread"; + lblBackSpread.Size = new Size(72, 13); + lblBackSpread.TabIndex = 6; + lblBackSpread.Text = "Back Spread "; + // + // filterKnobBackSpread + // + filterKnobBackSpread.DragSensitivity = 3; + filterKnobBackSpread.Font = new Font("Verdana", 6F, FontStyle.Regular, GraphicsUnit.Point, 0); + filterKnobBackSpread.Location = new Point(313, 7); + filterKnobBackSpread.Margin = new Padding(2); + filterKnobBackSpread.MaxValue = 0; + filterKnobBackSpread.MinValue = 0; + filterKnobBackSpread.Name = "filterKnobBackSpread"; + filterKnobBackSpread.Size = new Size(17, 29); + filterKnobBackSpread.TabIndex = 5; + helpToolTip.SetToolTip(filterKnobBackSpread, "Add preceding lines to search result (Drag up/down, press Shift for finer pitch)"); + filterKnobBackSpread.Value = 0; + // + // lblForeSpread + // + lblForeSpread.AutoSize = true; + lblForeSpread.Location = new Point(397, 38); + lblForeSpread.Name = "lblForeSpread"; + lblForeSpread.Size = new Size(65, 13); + lblForeSpread.TabIndex = 2; + lblForeSpread.Text = "Fore Spread"; + // + // filterKnobForeSpread + // + filterKnobForeSpread.DragSensitivity = 3; + filterKnobForeSpread.Font = new Font("Verdana", 6F, FontStyle.Regular, GraphicsUnit.Point, 0); + filterKnobForeSpread.Location = new Point(420, 7); + filterKnobForeSpread.Margin = new Padding(2); + filterKnobForeSpread.MaxValue = 0; + filterKnobForeSpread.MinValue = 0; + filterKnobForeSpread.Name = "filterKnobForeSpread"; + filterKnobForeSpread.Size = new Size(17, 29); + filterKnobForeSpread.TabIndex = 1; + helpToolTip.SetToolTip(filterKnobForeSpread, "Add following lines to search result (Drag up/down, press Shift for finer pitch)"); + filterKnobForeSpread.Value = 0; + // + // btnFilterToTab + // + btnFilterToTab.Location = new Point(750, 3); + btnFilterToTab.Name = "btnFilterToTab"; + btnFilterToTab.Size = new Size(85, 35); + btnFilterToTab.TabIndex = 0; + btnFilterToTab.Text = "Filter to Tab"; + helpToolTip.SetToolTip(btnFilterToTab, "Launch a new tab with filtered content"); + btnFilterToTab.UseVisualStyleBackColor = true; + btnFilterToTab.Click += OnFilterToTabButtonClick; + // + // panelBackgroundAdvancedFilterSplitContainer + // + panelBackgroundAdvancedFilterSplitContainer.Controls.Add(btnToggleHighlightPanel); + panelBackgroundAdvancedFilterSplitContainer.Controls.Add(highlightSplitContainer); + panelBackgroundAdvancedFilterSplitContainer.Dock = DockStyle.Fill; + panelBackgroundAdvancedFilterSplitContainer.Location = new Point(0, 0); + panelBackgroundAdvancedFilterSplitContainer.Name = "panelBackgroundAdvancedFilterSplitContainer"; + panelBackgroundAdvancedFilterSplitContainer.Size = new Size(1855, 474); + panelBackgroundAdvancedFilterSplitContainer.TabIndex = 7; + // + // btnToggleHighlightPanel + // + btnToggleHighlightPanel.Anchor = AnchorStyles.Top | AnchorStyles.Right; + btnToggleHighlightPanel.Image = LogExpert.Resources.Arrow_menu_open; + btnToggleHighlightPanel.Location = new Point(1832, 1); + btnToggleHighlightPanel.Name = "btnToggleHighlightPanel"; + btnToggleHighlightPanel.Size = new Size(20, 21); + btnToggleHighlightPanel.TabIndex = 6; + helpToolTip.SetToolTip(btnToggleHighlightPanel, "Open or close a list with saved filters"); + btnToggleHighlightPanel.UseVisualStyleBackColor = true; + btnToggleHighlightPanel.SizeChanged += OnButtonSizeChanged; + btnToggleHighlightPanel.Click += OnToggleHighlightPanelButtonClick; + // + // highlightSplitContainer + // + highlightSplitContainer.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right; + highlightSplitContainer.BorderStyle = BorderStyle.FixedSingle; + highlightSplitContainer.FixedPanel = FixedPanel.Panel2; + highlightSplitContainer.Location = new Point(0, 3); + highlightSplitContainer.Name = "highlightSplitContainer"; + // + // highlightSplitContainer.Panel1 + // + highlightSplitContainer.Panel1.Controls.Add(filterGridView); + highlightSplitContainer.Panel1MinSize = 100; + // + // highlightSplitContainer.Panel2 + // + highlightSplitContainer.Panel2.Controls.Add(highlightSplitContainerBackPanel); + highlightSplitContainer.Panel2MinSize = 350; + highlightSplitContainer.Size = new Size(1829, 471); + highlightSplitContainer.SplitterDistance = 1475; + highlightSplitContainer.TabIndex = 2; + // + // filterGridView + // + filterGridView.AllowUserToAddRows = false; + filterGridView.AllowUserToDeleteRows = false; + filterGridView.AllowUserToOrderColumns = true; + filterGridView.AllowUserToResizeRows = false; + filterGridView.BackgroundColor = SystemColors.Window; + filterGridView.BorderStyle = BorderStyle.None; + filterGridView.CellBorderStyle = DataGridViewCellBorderStyle.None; + filterGridView.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText; + filterGridView.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + filterGridView.ContextMenuStrip = filterContextMenuStrip; + filterGridView.Dock = DockStyle.Fill; + filterGridView.EditMode = DataGridViewEditMode.EditProgrammatically; + filterGridView.EditModeMenuStrip = null; + filterGridView.ImeMode = ImeMode.Disable; + filterGridView.Location = new Point(0, 0); + filterGridView.Margin = new Padding(0); + filterGridView.Name = "filterGridView"; + filterGridView.PaintWithOverlays = false; + filterGridView.ReadOnly = true; + filterGridView.RowHeadersVisible = false; + filterGridView.RowHeadersWidth = 62; + filterGridView.RowTemplate.Height = 15; + filterGridView.RowTemplate.ReadOnly = true; + filterGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + filterGridView.ShowCellErrors = false; + filterGridView.ShowCellToolTips = false; + filterGridView.ShowEditingIcon = false; + filterGridView.ShowRowErrors = false; + filterGridView.Size = new Size(1473, 469); + filterGridView.TabIndex = 1; + filterGridView.VirtualMode = true; + filterGridView.CellContextMenuStripNeeded += OnFilterGridViewCellContextMenuStripNeeded; + filterGridView.CellDoubleClick += OnFilterGridViewCellDoubleClick; + filterGridView.ColumnDividerDoubleClick += OnFilterGridViewColumnDividerDoubleClick; + filterGridView.RowHeightInfoNeeded += OnFilterGridViewRowHeightInfoNeeded; + filterGridView.Enter += OnFilterGridViewEnter; + filterGridView.KeyDown += OnFilterGridViewKeyDown; + filterGridView.Leave += OnFilterGridViewLeave; + // + // filterContextMenuStrip + // + filterContextMenuStrip.ImageScalingSize = new Size(24, 24); + filterContextMenuStrip.Items.AddRange(new ToolStripItem[] { setBookmarksOnSelectedLinesToolStripMenuItem, filterToTabToolStripMenuItem, markFilterHitsInLogViewToolStripMenuItem }); + filterContextMenuStrip.Name = "filterContextMenuStrip"; + filterContextMenuStrip.Size = new Size(243, 70); + // + // setBookmarksOnSelectedLinesToolStripMenuItem + // + setBookmarksOnSelectedLinesToolStripMenuItem.Name = "setBookmarksOnSelectedLinesToolStripMenuItem"; + setBookmarksOnSelectedLinesToolStripMenuItem.Size = new Size(242, 22); + setBookmarksOnSelectedLinesToolStripMenuItem.Text = "Set bookmarks on selected lines"; + setBookmarksOnSelectedLinesToolStripMenuItem.Click += OnSetBookmarksOnSelectedLinesToolStripMenuItemClick; + // + // filterToTabToolStripMenuItem + // + filterToTabToolStripMenuItem.Name = "filterToTabToolStripMenuItem"; + filterToTabToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.Shift | Keys.T; + filterToTabToolStripMenuItem.Size = new Size(242, 22); + filterToTabToolStripMenuItem.Text = "Filter to new tab"; + filterToTabToolStripMenuItem.Click += OnFilterToTabToolStripMenuItemClick; + // + // markFilterHitsInLogViewToolStripMenuItem + // + markFilterHitsInLogViewToolStripMenuItem.Name = "markFilterHitsInLogViewToolStripMenuItem"; + markFilterHitsInLogViewToolStripMenuItem.Size = new Size(242, 22); + markFilterHitsInLogViewToolStripMenuItem.Text = "Mark filter hits in log view"; + markFilterHitsInLogViewToolStripMenuItem.Click += OnMarkFilterHitsInLogViewToolStripMenuItemClick; + // + // highlightSplitContainerBackPanel + // + highlightSplitContainerBackPanel.Controls.Add(hideFilterListOnLoadCheckBox); + highlightSplitContainerBackPanel.Controls.Add(filterDownButton); + highlightSplitContainerBackPanel.Controls.Add(filterUpButton); + highlightSplitContainerBackPanel.Controls.Add(filterOnLoadCheckBox); + highlightSplitContainerBackPanel.Controls.Add(saveFilterButton); + highlightSplitContainerBackPanel.Controls.Add(deleteFilterButton); + highlightSplitContainerBackPanel.Controls.Add(filterListBox); + highlightSplitContainerBackPanel.Dock = DockStyle.Fill; + highlightSplitContainerBackPanel.Location = new Point(0, 0); + highlightSplitContainerBackPanel.Name = "highlightSplitContainerBackPanel"; + highlightSplitContainerBackPanel.Size = new Size(348, 469); + highlightSplitContainerBackPanel.TabIndex = 1; + // + // hideFilterListOnLoadCheckBox + // + hideFilterListOnLoadCheckBox.AutoSize = true; + hideFilterListOnLoadCheckBox.Location = new Point(258, 147); + hideFilterListOnLoadCheckBox.Name = "hideFilterListOnLoadCheckBox"; + hideFilterListOnLoadCheckBox.Size = new Size(71, 17); + hideFilterListOnLoadCheckBox.TabIndex = 20; + hideFilterListOnLoadCheckBox.Text = "Auto hide"; + helpToolTip.SetToolTip(hideFilterListOnLoadCheckBox, "Hides the filter list after loading a filter"); + hideFilterListOnLoadCheckBox.UseVisualStyleBackColor = true; + hideFilterListOnLoadCheckBox.MouseClick += OnHideFilterListOnLoadCheckBoxMouseClick; + // + // filterDownButton + // + filterDownButton.BackgroundImage = LogExpert.Resources.ArrowDown; + filterDownButton.BackgroundImageLayout = ImageLayout.Stretch; + filterDownButton.Location = new Point(296, 85); + filterDownButton.Name = "filterDownButton"; + filterDownButton.Size = new Size(35, 35); + filterDownButton.TabIndex = 19; + helpToolTip.SetToolTip(filterDownButton, "Move the selected entry down in the list"); + filterDownButton.UseVisualStyleBackColor = true; + filterDownButton.SizeChanged += OnButtonSizeChanged; + filterDownButton.Click += OnFilterDownButtonClick; + // + // filterUpButton + // + filterUpButton.BackgroundImage = LogExpert.Resources.ArrowUp; + filterUpButton.BackgroundImageLayout = ImageLayout.Stretch; + filterUpButton.Location = new Point(258, 85); + filterUpButton.Name = "filterUpButton"; + filterUpButton.Size = new Size(35, 35); + filterUpButton.TabIndex = 18; + helpToolTip.SetToolTip(filterUpButton, "Move the selected entry up in the list"); + filterUpButton.UseVisualStyleBackColor = true; + filterUpButton.SizeChanged += OnButtonSizeChanged; + filterUpButton.Click += OnFilterUpButtonClick; + // + // filterOnLoadCheckBox + // + filterOnLoadCheckBox.AutoSize = true; + filterOnLoadCheckBox.Location = new Point(258, 123); + filterOnLoadCheckBox.Name = "filterOnLoadCheckBox"; + filterOnLoadCheckBox.Size = new Size(71, 17); + filterOnLoadCheckBox.TabIndex = 17; + filterOnLoadCheckBox.Text = "Auto start"; + helpToolTip.SetToolTip(filterOnLoadCheckBox, "Start immediate filtering after loading a saved filter"); + filterOnLoadCheckBox.UseVisualStyleBackColor = true; + filterOnLoadCheckBox.KeyPress += OnFilterOnLoadCheckBoxKeyPress; + filterOnLoadCheckBox.MouseClick += OnFilterOnLoadCheckBoxMouseClick; + // + // saveFilterButton + // + saveFilterButton.Location = new Point(258, 11); + saveFilterButton.Name = "saveFilterButton"; + saveFilterButton.Size = new Size(75, 35); + saveFilterButton.TabIndex = 16; + saveFilterButton.Text = "Save filter"; + saveFilterButton.UseVisualStyleBackColor = true; + saveFilterButton.Click += OnSaveFilterButtonClick; + // + // deleteFilterButton + // + deleteFilterButton.Location = new Point(258, 47); + deleteFilterButton.Name = "deleteFilterButton"; + deleteFilterButton.Size = new Size(75, 35); + deleteFilterButton.TabIndex = 3; + deleteFilterButton.Text = "Delete"; + deleteFilterButton.UseVisualStyleBackColor = true; + deleteFilterButton.Click += OnDeleteFilterButtonClick; + // + // filterListBox + // + filterListBox.ContextMenuStrip = filterListContextMenuStrip; + filterListBox.Dock = DockStyle.Left; + filterListBox.DrawMode = DrawMode.OwnerDrawFixed; + filterListBox.Font = new Font("Courier New", 12F, FontStyle.Regular, GraphicsUnit.Point, 0); + filterListBox.FormattingEnabled = true; + filterListBox.IntegralHeight = false; + filterListBox.ItemHeight = 25; + filterListBox.Location = new Point(0, 0); + filterListBox.Name = "filterListBox"; + filterListBox.Size = new Size(252, 469); + filterListBox.TabIndex = 0; + helpToolTip.SetToolTip(filterListBox, "Doubleclick to load a saved filter"); + filterListBox.DrawItem += OnFilterListBoxDrawItem; + filterListBox.MouseDoubleClick += OnFilterListBoxMouseDoubleClick; + // + // filterListContextMenuStrip + // + filterListContextMenuStrip.ImageScalingSize = new Size(24, 24); + filterListContextMenuStrip.Items.AddRange(new ToolStripItem[] { colorToolStripMenuItem }); + filterListContextMenuStrip.Name = "filterListContextMenuStrip"; + filterListContextMenuStrip.Size = new Size(113, 26); + // + // colorToolStripMenuItem + // + colorToolStripMenuItem.Name = "colorToolStripMenuItem"; + colorToolStripMenuItem.Size = new Size(112, 22); + colorToolStripMenuItem.Text = "Color..."; + colorToolStripMenuItem.Click += OnColorToolStripMenuItemClick; + // + // pnlFilterInput + // + pnlFilterInput.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + pnlFilterInput.Controls.Add(filterSplitContainer); + pnlFilterInput.Location = new Point(3, 2); + pnlFilterInput.Name = "pnlFilterInput"; + pnlFilterInput.Size = new Size(1855, 46); + pnlFilterInput.TabIndex = 0; + // + // filterSplitContainer + // + filterSplitContainer.Dock = DockStyle.Fill; + filterSplitContainer.Location = new Point(0, 0); + filterSplitContainer.Name = "filterSplitContainer"; + // + // filterSplitContainer.Panel1 + // + filterSplitContainer.Panel1.Controls.Add(filterComboBox); + filterSplitContainer.Panel1.Controls.Add(lblTextFilter); + filterSplitContainer.Panel1MinSize = 200; + // + // filterSplitContainer.Panel2 + // + filterSplitContainer.Panel2.Controls.Add(advancedButton); + filterSplitContainer.Panel2.Controls.Add(syncFilterCheckBox); + filterSplitContainer.Panel2.Controls.Add(lblFilterCount); + filterSplitContainer.Panel2.Controls.Add(filterTailCheckBox); + filterSplitContainer.Panel2.Controls.Add(filterRegexCheckBox); + filterSplitContainer.Panel2.Controls.Add(filterCaseSensitiveCheckBox); + filterSplitContainer.Panel2.Controls.Add(filterSearchButton); + filterSplitContainer.Panel2MinSize = 550; + filterSplitContainer.Size = new Size(1855, 46); + filterSplitContainer.SplitterDistance = 518; + filterSplitContainer.TabIndex = 11; + filterSplitContainer.MouseDoubleClick += OnFilterSplitContainerMouseDoubleClick; + filterSplitContainer.MouseDown += OnFilterSplitContainerMouseDown; + filterSplitContainer.MouseMove += OnFilterSplitContainerMouseMove; + filterSplitContainer.MouseUp += OnFilterSplitContainerMouseUp; + // + // filterComboBox + // + filterComboBox.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + filterComboBox.Font = new Font("Courier New", 12F, FontStyle.Regular, GraphicsUnit.Point, 0); + filterComboBox.FormattingEnabled = true; + filterComboBox.Location = new Point(89, 5); + filterComboBox.Name = "filterComboBox"; + filterComboBox.Size = new Size(426, 26); + filterComboBox.TabIndex = 4; + helpToolTip.SetToolTip(filterComboBox, "Search string for the filter"); + filterComboBox.TextChanged += OnFilterComboBoxTextChanged; + filterComboBox.KeyDown += OnFilterComboBoxKeyDown; + // + // lblTextFilter + // + lblTextFilter.AutoSize = true; + lblTextFilter.Location = new Point(5, 5); + lblTextFilter.Name = "lblTextFilter"; + lblTextFilter.Size = new Size(53, 13); + lblTextFilter.TabIndex = 3; + lblTextFilter.Text = "Text &filter:"; + // + // advancedButton + // + advancedButton.DialogResult = DialogResult.Cancel; + advancedButton.Image = (Image)resources.GetObject("advancedButton.Image"); + advancedButton.ImageAlign = ContentAlignment.MiddleRight; + advancedButton.Location = new Point(539, 5); + advancedButton.Name = "advancedButton"; + advancedButton.Size = new Size(110, 35); + advancedButton.TabIndex = 17; + advancedButton.Text = "Show advanced..."; + helpToolTip.SetToolTip(advancedButton, "Toggel the advanced filter options panel"); + advancedButton.UseVisualStyleBackColor = true; + advancedButton.Click += OnAdvancedButtonClick; + // + // syncFilterCheckBox + // + syncFilterCheckBox.AutoSize = true; + syncFilterCheckBox.Location = new Point(467, 5); + syncFilterCheckBox.Name = "syncFilterCheckBox"; + syncFilterCheckBox.Size = new Size(50, 17); + syncFilterCheckBox.TabIndex = 16; + syncFilterCheckBox.Text = "Sync"; + helpToolTip.SetToolTip(syncFilterCheckBox, "Sync the current selected line in the filter view to the selection in the log file view"); + syncFilterCheckBox.UseVisualStyleBackColor = true; + syncFilterCheckBox.CheckedChanged += OnSyncFilterCheckBoxCheckedChanged; + // + // lblFilterCount + // + lblFilterCount.Anchor = AnchorStyles.Right; + lblFilterCount.BorderStyle = BorderStyle.Fixed3D; + lblFilterCount.Location = new Point(1259, 8); + lblFilterCount.Name = "lblFilterCount"; + lblFilterCount.Size = new Size(71, 21); + lblFilterCount.TabIndex = 15; + lblFilterCount.Text = "0"; + lblFilterCount.TextAlign = ContentAlignment.MiddleRight; + // + // filterTailCheckBox + // + filterTailCheckBox.AutoSize = true; + filterTailCheckBox.Location = new Point(367, 5); + filterTailCheckBox.Name = "filterTailCheckBox"; + filterTailCheckBox.Size = new Size(64, 17); + filterTailCheckBox.TabIndex = 14; + filterTailCheckBox.Text = "Filter tail"; + helpToolTip.SetToolTip(filterTailCheckBox, "Filter tailed file content (keeps filter view up to date on file changes)"); + filterTailCheckBox.UseVisualStyleBackColor = true; + // + // filterRegexCheckBox + // + filterRegexCheckBox.AutoSize = true; + filterRegexCheckBox.Location = new Point(283, 5); + filterRegexCheckBox.Name = "filterRegexCheckBox"; + filterRegexCheckBox.Size = new Size(57, 17); + filterRegexCheckBox.TabIndex = 13; + filterRegexCheckBox.Text = "Regex"; + helpToolTip.SetToolTip(filterRegexCheckBox, "Use regular expressions. (right-click for RegEx helper window)"); + filterRegexCheckBox.UseVisualStyleBackColor = true; + filterRegexCheckBox.CheckedChanged += OnFilterRegexCheckBoxCheckedChanged; + filterRegexCheckBox.MouseUp += OnFilterRegexCheckBoxMouseUp; + // + // filterCaseSensitiveCheckBox + // + filterCaseSensitiveCheckBox.AutoSize = true; + filterCaseSensitiveCheckBox.Location = new Point(137, 5); + filterCaseSensitiveCheckBox.Name = "filterCaseSensitiveCheckBox"; + filterCaseSensitiveCheckBox.Size = new Size(94, 17); + filterCaseSensitiveCheckBox.TabIndex = 12; + filterCaseSensitiveCheckBox.Text = "Case sensitive"; + helpToolTip.SetToolTip(filterCaseSensitiveCheckBox, "Makes the filter case sensitive"); + filterCaseSensitiveCheckBox.UseVisualStyleBackColor = true; + filterCaseSensitiveCheckBox.CheckedChanged += OnFilterCaseSensitiveCheckBoxCheckedChanged; + // + // filterSearchButton + // + filterSearchButton.Image = (Image)resources.GetObject("filterSearchButton.Image"); + filterSearchButton.ImageAlign = ContentAlignment.MiddleRight; + filterSearchButton.Location = new Point(3, 5); + filterSearchButton.Name = "filterSearchButton"; + filterSearchButton.Size = new Size(128, 35); + filterSearchButton.TabIndex = 11; + filterSearchButton.Text = "Search"; + helpToolTip.SetToolTip(filterSearchButton, "Start the filter search"); + filterSearchButton.UseVisualStyleBackColor = true; + filterSearchButton.Click += OnFilterSearchButtonClick; + // + // bookmarkContextMenuStrip + // + bookmarkContextMenuStrip.ImageScalingSize = new Size(24, 24); + bookmarkContextMenuStrip.Items.AddRange(new ToolStripItem[] { deleteBookmarksToolStripMenuItem }); + bookmarkContextMenuStrip.Name = "bookmarkContextMenuStrip"; + bookmarkContextMenuStrip.Size = new Size(68, 26); + // + // deleteBookmarksToolStripMenuItem + // + deleteBookmarksToolStripMenuItem.Name = "deleteBookmarksToolStripMenuItem"; + deleteBookmarksToolStripMenuItem.Size = new Size(67, 22); + // + // columnContextMenuStrip + // + 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, 176); + columnContextMenuStrip.Opening += OnColumnContextMenuStripOpening; + // + // freezeLeftColumnsUntilHereToolStripMenuItem + // + freezeLeftColumnsUntilHereToolStripMenuItem.Name = "freezeLeftColumnsUntilHereToolStripMenuItem"; + freezeLeftColumnsUntilHereToolStripMenuItem.Size = new Size(229, 22); + freezeLeftColumnsUntilHereToolStripMenuItem.Text = "Freeze left columns until here"; + freezeLeftColumnsUntilHereToolStripMenuItem.Click += OnFreezeLeftColumnsUntilHereToolStripMenuItemClick; + // + // menuToolStripSeparator4 + // + menuToolStripSeparator4.Name = "menuToolStripSeparator4"; + menuToolStripSeparator4.Size = new Size(226, 6); + // + // moveToLastColumnToolStripMenuItem + // + moveToLastColumnToolStripMenuItem.Name = "moveToLastColumnToolStripMenuItem"; + moveToLastColumnToolStripMenuItem.Size = new Size(229, 22); + moveToLastColumnToolStripMenuItem.Text = "Move to last column"; + moveToLastColumnToolStripMenuItem.ToolTipText = "Move this column to the last position"; + moveToLastColumnToolStripMenuItem.Click += OnMoveToLastColumnToolStripMenuItemClick; + // + // moveLeftToolStripMenuItem + // + moveLeftToolStripMenuItem.Name = "moveLeftToolStripMenuItem"; + moveLeftToolStripMenuItem.Size = new Size(229, 22); + moveLeftToolStripMenuItem.Text = "Move left"; + moveLeftToolStripMenuItem.Click += OnMoveLeftToolStripMenuItemClick; + // + // moveRightToolStripMenuItem + // + moveRightToolStripMenuItem.Name = "moveRightToolStripMenuItem"; + moveRightToolStripMenuItem.Size = new Size(229, 22); + moveRightToolStripMenuItem.Text = "Move right"; + moveRightToolStripMenuItem.Click += OnMoveRightToolStripMenuItemClick; + // + // menuToolStripSeparator5 + // + menuToolStripSeparator5.Name = "menuToolStripSeparator5"; + menuToolStripSeparator5.Size = new Size(226, 6); + // + // hideColumnToolStripMenuItem + // + hideColumnToolStripMenuItem.Name = "hideColumnToolStripMenuItem"; + hideColumnToolStripMenuItem.Size = new Size(229, 22); + hideColumnToolStripMenuItem.Text = "Hide column"; + hideColumnToolStripMenuItem.ToolTipText = "Hide this column"; + hideColumnToolStripMenuItem.Click += OnHideColumnToolStripMenuItemClick; + // + // restoreColumnsToolStripMenuItem + // + restoreColumnsToolStripMenuItem.Name = "restoreColumnsToolStripMenuItem"; + restoreColumnsToolStripMenuItem.Size = new Size(229, 22); + restoreColumnsToolStripMenuItem.Text = "Restore columns"; + restoreColumnsToolStripMenuItem.Click += OnRestoreColumnsToolStripMenuItemClick; + // + // menuToolStripSeparator6 + // + menuToolStripSeparator6.Name = "menuToolStripSeparator6"; + menuToolStripSeparator6.Size = new Size(226, 6); + // + // allColumnsToolStripMenuItem + // + allColumnsToolStripMenuItem.Name = "allColumnsToolStripMenuItem"; + allColumnsToolStripMenuItem.Size = new Size(229, 22); + allColumnsToolStripMenuItem.Text = "Scroll to column..."; + // + // editModeContextMenuStrip + // + editModeContextMenuStrip.ImageScalingSize = new Size(24, 24); + editModeContextMenuStrip.Items.AddRange(new ToolStripItem[] { editModecopyToolStripMenuItem, highlightSelectionInLogFileToolStripMenuItem, highlightSelectionInLogFilewordModeToolStripMenuItem, filterForSelectionToolStripMenuItem, setSelectedTextAsBookmarkCommentToolStripMenuItem }); + editModeContextMenuStrip.Name = "editModeContextMenuStrip"; + editModeContextMenuStrip.Size = new Size(344, 114); + // + // editModecopyToolStripMenuItem + // + editModecopyToolStripMenuItem.Name = "editModecopyToolStripMenuItem"; + editModecopyToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.C; + editModecopyToolStripMenuItem.Size = new Size(343, 22); + editModecopyToolStripMenuItem.Text = "Copy"; + editModecopyToolStripMenuItem.Click += OnEditModeCopyToolStripMenuItemClick; + // + // highlightSelectionInLogFileToolStripMenuItem + // + highlightSelectionInLogFileToolStripMenuItem.Name = "highlightSelectionInLogFileToolStripMenuItem"; + highlightSelectionInLogFileToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.H; + highlightSelectionInLogFileToolStripMenuItem.Size = new Size(343, 22); + highlightSelectionInLogFileToolStripMenuItem.Text = "Highlight selection in log file (full line)"; + highlightSelectionInLogFileToolStripMenuItem.Click += OnHighlightSelectionInLogFileToolStripMenuItemClick; + // + // highlightSelectionInLogFilewordModeToolStripMenuItem + // + highlightSelectionInLogFilewordModeToolStripMenuItem.Name = "highlightSelectionInLogFilewordModeToolStripMenuItem"; + highlightSelectionInLogFilewordModeToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.W; + highlightSelectionInLogFilewordModeToolStripMenuItem.Size = new Size(343, 22); + highlightSelectionInLogFilewordModeToolStripMenuItem.Text = "Highlight selection in log file (word mode)"; + highlightSelectionInLogFilewordModeToolStripMenuItem.Click += OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick; + // + // filterForSelectionToolStripMenuItem + // + filterForSelectionToolStripMenuItem.Name = "filterForSelectionToolStripMenuItem"; + filterForSelectionToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F; + filterForSelectionToolStripMenuItem.Size = new Size(343, 22); + filterForSelectionToolStripMenuItem.Text = "Filter for selection"; + filterForSelectionToolStripMenuItem.Click += OnFilterForSelectionToolStripMenuItemClick; + // + // setSelectedTextAsBookmarkCommentToolStripMenuItem + // + setSelectedTextAsBookmarkCommentToolStripMenuItem.Name = "setSelectedTextAsBookmarkCommentToolStripMenuItem"; + setSelectedTextAsBookmarkCommentToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.B; + setSelectedTextAsBookmarkCommentToolStripMenuItem.Size = new Size(343, 22); + setSelectedTextAsBookmarkCommentToolStripMenuItem.Text = "Set selected text as bookmark comment"; + setSelectedTextAsBookmarkCommentToolStripMenuItem.Click += OnSetSelectedTextAsBookmarkCommentToolStripMenuItemClick; + // + // LogWindow + // + ClientSize = new Size(1862, 1104); + ControlBox = false; + Controls.Add(splitContainerLogWindow); + Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + FormBorderStyle = FormBorderStyle.None; + Icon = (Icon)resources.GetObject("$this.Icon"); + Margin = new Padding(0); + MaximizeBox = false; + MinimizeBox = false; + Name = "LogWindow"; + ShowIcon = false; + ShowInTaskbar = false; + SizeGripStyle = SizeGripStyle.Hide; + SizeChanged += OnLogWindowSizeChanged; + Enter += OnLogWindowEnter; + KeyDown += OnLogWindowKeyDown; + Leave += OnLogWindowLeave; + splitContainerLogWindow.Panel1.ResumeLayout(false); + splitContainerLogWindow.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)splitContainerLogWindow).EndInit(); + splitContainerLogWindow.ResumeLayout(false); + tableLayoutPanel1.ResumeLayout(false); + columnFinderPanel.ResumeLayout(false); + columnFinderPanel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridView).EndInit(); + dataGridContextMenuStrip.ResumeLayout(false); + advancedBackPanel.ResumeLayout(false); + advancedFilterSplitContainer.Panel1.ResumeLayout(false); + advancedFilterSplitContainer.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)advancedFilterSplitContainer).EndInit(); + advancedFilterSplitContainer.ResumeLayout(false); + pnlProFilter.ResumeLayout(false); + pnlProFilter.PerformLayout(); + panelBackgroundAdvancedFilterSplitContainer.ResumeLayout(false); + highlightSplitContainer.Panel1.ResumeLayout(false); + highlightSplitContainer.Panel2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)highlightSplitContainer).EndInit(); + highlightSplitContainer.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)filterGridView).EndInit(); + filterContextMenuStrip.ResumeLayout(false); + highlightSplitContainerBackPanel.ResumeLayout(false); + highlightSplitContainerBackPanel.PerformLayout(); + filterListContextMenuStrip.ResumeLayout(false); + pnlFilterInput.ResumeLayout(false); + filterSplitContainer.Panel1.ResumeLayout(false); + filterSplitContainer.Panel1.PerformLayout(); + filterSplitContainer.Panel2.ResumeLayout(false); + filterSplitContainer.Panel2.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)filterSplitContainer).EndInit(); + filterSplitContainer.ResumeLayout(false); + bookmarkContextMenuStrip.ResumeLayout(false); + columnContextMenuStrip.ResumeLayout(false); + editModeContextMenuStrip.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.SplitContainer splitContainerLogWindow; + private System.Windows.Forms.Panel pnlFilterInput; + private BufferedDataGridView dataGridView; + private BufferedDataGridView filterGridView; + private System.Windows.Forms.SplitContainer advancedFilterSplitContainer; + private System.Windows.Forms.Panel pnlProFilter; + private System.Windows.Forms.Button btnFilterToTab; + private KnobControl filterKnobForeSpread; + private System.Windows.Forms.Label lblForeSpread; + private KnobControl filterKnobBackSpread; + private System.Windows.Forms.Label lblBackSpread; + private System.Windows.Forms.Panel pnlProFilterLabel; + private System.Windows.Forms.CheckBox invertFilterCheckBox; + private System.Windows.Forms.Label fuzzyLabel; + private KnobControl fuzzyKnobControl; + private System.Windows.Forms.CheckBox rangeCheckBox; + private System.Windows.Forms.ComboBox filterRangeComboBox; + private System.Windows.Forms.ContextMenuStrip dataGridContextMenuStrip; + private System.Windows.Forms.ToolStripMenuItem copyToTabToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem scrollAllTabsToTimestampToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem locateLineInOriginalFileToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem toggleBoomarkToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem markEditModeToolStripMenuItem; + private System.Windows.Forms.ContextMenuStrip bookmarkContextMenuStrip; + private System.Windows.Forms.ToolStripMenuItem deleteBookmarksToolStripMenuItem; + private System.Windows.Forms.CheckBox columnRestrictCheckBox; + private System.Windows.Forms.Button columnButton; + private System.Windows.Forms.ContextMenuStrip columnContextMenuStrip; + private System.Windows.Forms.ToolStripMenuItem freezeLeftColumnsUntilHereToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem moveToLastColumnToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem moveLeftToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem moveRightToolStripMenuItem; + private TimeSpreadingControl timeSpreadingControl; + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; + private System.Windows.Forms.ToolStripMenuItem bookmarkCommentToolStripMenuItem; + private System.Windows.Forms.ContextMenuStrip editModeContextMenuStrip; + private System.Windows.Forms.ToolStripMenuItem highlightSelectionInLogFileToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem editModecopyToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem tempHighlightsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem removeAllToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem makePermanentToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem filterForSelectionToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem setSelectedTextAsBookmarkCommentToolStripMenuItem; + private System.Windows.Forms.ToolTip helpToolTip; + private System.Windows.Forms.SplitContainer highlightSplitContainer; + private System.Windows.Forms.Button btnToggleHighlightPanel; + private System.Windows.Forms.Panel highlightSplitContainerBackPanel; + private System.Windows.Forms.Button saveFilterButton; + private System.Windows.Forms.Button deleteFilterButton; + private System.Windows.Forms.ListBox filterListBox; + private System.Windows.Forms.ContextMenuStrip filterContextMenuStrip; + private System.Windows.Forms.ToolStripMenuItem setBookmarksOnSelectedLinesToolStripMenuItem; + private System.Windows.Forms.CheckBox filterOnLoadCheckBox; + private System.Windows.Forms.ToolStripMenuItem markCurrentFilterRangeToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem syncTimestampsToToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem freeThisWindowFromTimeSyncToolStripMenuItem; + private System.Windows.Forms.Button filterDownButton; + private System.Windows.Forms.Button filterUpButton; + private System.Windows.Forms.ContextMenuStrip filterListContextMenuStrip; + private System.Windows.Forms.ToolStripMenuItem colorToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem filterToTabToolStripMenuItem; + private System.Windows.Forms.CheckBox hideFilterListOnLoadCheckBox; + private System.Windows.Forms.Panel advancedBackPanel; + private System.Windows.Forms.ToolStripMenuItem markFilterHitsInLogViewToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem highlightSelectionInLogFilewordModeToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem hideColumnToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem restoreColumnsToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem allColumnsToolStripMenuItem; + private System.Windows.Forms.Label columnNamesLabel; + private System.Windows.Forms.Panel columnFinderPanel; + private System.Windows.Forms.ComboBox columnComboBox; + private System.Windows.Forms.Label lblColumnName; + private System.Windows.Forms.SplitContainer filterSplitContainer; + private System.Windows.Forms.Label lblTextFilter; + private System.Windows.Forms.ComboBox filterComboBox; + private System.Windows.Forms.Button advancedButton; + private System.Windows.Forms.CheckBox syncFilterCheckBox; + private System.Windows.Forms.Label lblFilterCount; + private System.Windows.Forms.CheckBox filterTailCheckBox; + private System.Windows.Forms.CheckBox filterRegexCheckBox; + private System.Windows.Forms.CheckBox filterCaseSensitiveCheckBox; + private System.Windows.Forms.Button filterSearchButton; + private System.Windows.Forms.Panel panelBackgroundAdvancedFilterSplitContainer; + 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/Dialogs/AllowOnlyOneInstanceErrorDialog.resx b/src/LogExpert.UI/Controls/LogWindow/LogWindow.resx similarity index 100% rename from src/LogExpert/Dialogs/AllowOnlyOneInstanceErrorDialog.resx rename to src/LogExpert.UI/Controls/LogWindow/LogWindow.resx diff --git a/src/LogExpert/Controls/PatternWindow.Designer.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.Designer.cs similarity index 94% rename from src/LogExpert/Controls/PatternWindow.Designer.cs rename to src/LogExpert.UI/Controls/LogWindow/PatternWindow.Designer.cs index 7b211e99..a40a078f 100644 --- a/src/LogExpert/Controls/PatternWindow.Designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.Designer.cs @@ -1,430 +1,430 @@ -namespace LogExpert.Controls -{ - partial class PatternWindow - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PatternWindow)); - this.splitContainer1 = new System.Windows.Forms.SplitContainer(); - this.panel3 = new System.Windows.Forms.Panel(); - this.splitContainer2 = new System.Windows.Forms.SplitContainer(); - this.panel2 = new System.Windows.Forms.Panel(); - this.blockCountLabel = new System.Windows.Forms.Label(); - this.label1 = new System.Windows.Forms.Label(); - this.panel1 = new System.Windows.Forms.Panel(); - this.label2 = new System.Windows.Forms.Label(); - this.blockLinesLabel = new System.Windows.Forms.Label(); - this.panel4 = new System.Windows.Forms.Panel(); - this.setRangeButton = new System.Windows.Forms.Button(); - this.label7 = new System.Windows.Forms.Label(); - this.recalcButton = new System.Windows.Forms.Button(); - this.label6 = new System.Windows.Forms.Label(); - this.label5 = new System.Windows.Forms.Label(); - this.label4 = new System.Windows.Forms.Label(); - this.label3 = new System.Windows.Forms.Label(); - this.rangeLabel = new System.Windows.Forms.Label(); - this.weigthKnobControl = new KnobControl(); - this.maxMissesKnobControl = new KnobControl(); - this.maxDiffKnobControl = new KnobControl(); - this.fuzzyKnobControl = new KnobControl(); - this.patternHitsDataGridView = new LogExpert.Dialogs.BufferedDataGridView(); - this.contentDataGridView = new LogExpert.Dialogs.BufferedDataGridView(); - this.splitContainer1.Panel1.SuspendLayout(); - this.splitContainer1.Panel2.SuspendLayout(); - this.splitContainer1.SuspendLayout(); - this.splitContainer2.Panel1.SuspendLayout(); - this.splitContainer2.Panel2.SuspendLayout(); - this.splitContainer2.SuspendLayout(); - this.panel2.SuspendLayout(); - this.panel1.SuspendLayout(); - this.panel4.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.patternHitsDataGridView)).BeginInit(); - ((System.ComponentModel.ISupportInitialize)(this.contentDataGridView)).BeginInit(); - this.SuspendLayout(); - // - // splitContainer1 - // - this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.splitContainer1.BackColor = System.Drawing.SystemColors.Control; - this.splitContainer1.IsSplitterFixed = true; - this.splitContainer1.Location = new System.Drawing.Point(2, 1); - this.splitContainer1.Name = "splitContainer1"; - this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; - // - // splitContainer1.Panel1 - // - this.splitContainer1.Panel1.Controls.Add(this.panel3); - this.splitContainer1.Panel1Collapsed = true; - this.splitContainer1.Panel1MinSize = 0; - // - // splitContainer1.Panel2 - // - this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); - this.splitContainer1.Panel2MinSize = 0; - this.splitContainer1.Size = new System.Drawing.Size(795, 106); - this.splitContainer1.SplitterDistance = 106; - this.splitContainer1.TabIndex = 3; - // - // panel3 - // - this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; - this.panel3.Location = new System.Drawing.Point(0, 0); - this.panel3.Name = "panel3"; - this.panel3.Size = new System.Drawing.Size(150, 106); - this.panel3.TabIndex = 1; - // - // splitContainer2 - // - this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; - this.splitContainer2.Location = new System.Drawing.Point(0, 0); - this.splitContainer2.Name = "splitContainer2"; - // - // splitContainer2.Panel1 - // - this.splitContainer2.Panel1.Controls.Add(this.panel2); - // - // splitContainer2.Panel2 - // - this.splitContainer2.Panel2.Controls.Add(this.panel1); - this.splitContainer2.Size = new System.Drawing.Size(795, 106); - this.splitContainer2.SplitterDistance = 294; - this.splitContainer2.TabIndex = 2; - // - // panel2 - // - this.panel2.Controls.Add(this.blockCountLabel); - this.panel2.Controls.Add(this.label1); - this.panel2.Controls.Add(this.patternHitsDataGridView); - this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; - this.panel2.Location = new System.Drawing.Point(0, 0); - this.panel2.Name = "panel2"; - this.panel2.Size = new System.Drawing.Size(294, 106); - this.panel2.TabIndex = 2; - // - // blockCountLabel - // - this.blockCountLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.blockCountLabel.AutoSize = true; - this.blockCountLabel.Location = new System.Drawing.Point(184, 89); - this.blockCountLabel.Name = "blockCountLabel"; - this.blockCountLabel.Size = new System.Drawing.Size(13, 13); - this.blockCountLabel.TabIndex = 3; - this.blockCountLabel.Text = "0"; - // - // label1 - // - this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(0, 89); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(175, 13); - this.label1.TabIndex = 2; - this.label1.Text = "Number of blocks (pattern variants):"; - // - // panel1 - // - this.panel1.Controls.Add(this.label2); - this.panel1.Controls.Add(this.blockLinesLabel); - this.panel1.Controls.Add(this.contentDataGridView); - this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; - this.panel1.Location = new System.Drawing.Point(0, 0); - this.panel1.Name = "panel1"; - this.panel1.Size = new System.Drawing.Size(497, 106); - this.panel1.TabIndex = 1; - // - // label2 - // - this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.label2.AutoSize = true; - this.label2.Location = new System.Drawing.Point(3, 89); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(61, 13); - this.label2.TabIndex = 2; - this.label2.Text = "Block lines:"; - // - // blockLinesLabel - // - this.blockLinesLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.blockLinesLabel.Location = new System.Drawing.Point(70, 89); - this.blockLinesLabel.Name = "blockLinesLabel"; - this.blockLinesLabel.Size = new System.Drawing.Size(69, 13); - this.blockLinesLabel.TabIndex = 1; - this.blockLinesLabel.Text = "0"; - // - // panel4 - // - this.panel4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.panel4.Controls.Add(this.setRangeButton); - this.panel4.Controls.Add(this.label7); - this.panel4.Controls.Add(this.recalcButton); - this.panel4.Controls.Add(this.weigthKnobControl); - this.panel4.Controls.Add(this.label6); - this.panel4.Controls.Add(this.maxMissesKnobControl); - this.panel4.Controls.Add(this.label5); - this.panel4.Controls.Add(this.maxDiffKnobControl); - this.panel4.Controls.Add(this.label4); - this.panel4.Controls.Add(this.fuzzyKnobControl); - this.panel4.Location = new System.Drawing.Point(3, 106); - this.panel4.Name = "panel4"; - this.panel4.Size = new System.Drawing.Size(345, 57); - this.panel4.TabIndex = 5; - // - // setRangeButton - // - this.setRangeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.setRangeButton.Location = new System.Drawing.Point(267, 5); - this.setRangeButton.Name = "setRangeButton"; - this.setRangeButton.Size = new System.Drawing.Size(75, 23); - this.setRangeButton.TabIndex = 12; - this.setRangeButton.Text = "Set range"; - this.setRangeButton.UseVisualStyleBackColor = true; - this.setRangeButton.Click += new System.EventHandler(this.setRangeButton_Click); - // - // label7 - // - this.label7.AutoSize = true; - this.label7.Location = new System.Drawing.Point(192, 41); - this.label7.Name = "label7"; - this.label7.Size = new System.Drawing.Size(41, 13); - this.label7.TabIndex = 11; - this.label7.Text = "Weigth"; - // - // recalcButton - // - this.recalcButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.recalcButton.Location = new System.Drawing.Point(267, 30); - this.recalcButton.Name = "recalcButton"; - this.recalcButton.Size = new System.Drawing.Size(75, 23); - this.recalcButton.TabIndex = 6; - this.recalcButton.Text = "Recalc"; - this.recalcButton.UseVisualStyleBackColor = true; - this.recalcButton.Click += new System.EventHandler(this.recalcButton_Click); - // - // label6 - // - this.label6.AutoSize = true; - this.label6.Location = new System.Drawing.Point(113, 41); - this.label6.Name = "label6"; - this.label6.Size = new System.Drawing.Size(61, 13); - this.label6.TabIndex = 9; - this.label6.Text = "Max misses"; - // - // label5 - // - this.label5.AutoSize = true; - this.label5.Location = new System.Drawing.Point(57, 41); - this.label5.Name = "label5"; - this.label5.Size = new System.Drawing.Size(44, 13); - this.label5.TabIndex = 7; - this.label5.Text = "Max diff"; - // - // label4 - // - this.label4.AutoSize = true; - this.label4.Location = new System.Drawing.Point(6, 41); - this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(34, 13); - this.label4.TabIndex = 5; - this.label4.Text = "Fuzzy"; - // - // label3 - // - this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.label3.Location = new System.Drawing.Point(483, 110); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(303, 49); - this.label3.TabIndex = 12; - this.label3.Text = "This feature is pre-beta and does not work :)\r\nUsage: Select a range in the log w" + - "indow and press \"Recalc\". \r\nThis will search for text ranges similar to the sele" + - "cted one."; - // - // rangeLabel - // - this.rangeLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.rangeLabel.Location = new System.Drawing.Point(352, 114); - this.rangeLabel.Name = "rangeLabel"; - this.rangeLabel.Size = new System.Drawing.Size(125, 42); - this.rangeLabel.TabIndex = 13; - this.rangeLabel.Text = "(no range set)"; - // - // weigthKnobControl - // - this.weigthKnobControl.Location = new System.Drawing.Point(202, 5); - this.weigthKnobControl.MaxValue = 30; - this.weigthKnobControl.MinValue = 1; - this.weigthKnobControl.Name = "weigthKnobControl"; - this.weigthKnobControl.Size = new System.Drawing.Size(21, 35); - this.weigthKnobControl.TabIndex = 10; - this.weigthKnobControl.Value = 0; - // - // maxMissesKnobControl - // - this.maxMissesKnobControl.Location = new System.Drawing.Point(134, 5); - this.maxMissesKnobControl.MaxValue = 30; - this.maxMissesKnobControl.MinValue = 0; - this.maxMissesKnobControl.Name = "maxMissesKnobControl"; - this.maxMissesKnobControl.Size = new System.Drawing.Size(22, 35); - this.maxMissesKnobControl.TabIndex = 8; - this.maxMissesKnobControl.Value = 0; - // - // maxDiffKnobControl - // - this.maxDiffKnobControl.Location = new System.Drawing.Point(69, 5); - this.maxDiffKnobControl.MaxValue = 30; - this.maxDiffKnobControl.MinValue = 0; - this.maxDiffKnobControl.Name = "maxDiffKnobControl"; - this.maxDiffKnobControl.Size = new System.Drawing.Size(21, 35); - this.maxDiffKnobControl.TabIndex = 6; - this.maxDiffKnobControl.Value = 0; - // - // fuzzyKnobControl - // - this.fuzzyKnobControl.Location = new System.Drawing.Point(9, 5); - this.fuzzyKnobControl.MaxValue = 20; - this.fuzzyKnobControl.MinValue = 0; - this.fuzzyKnobControl.Name = "fuzzyKnobControl"; - this.fuzzyKnobControl.Size = new System.Drawing.Size(22, 35); - this.fuzzyKnobControl.TabIndex = 4; - this.fuzzyKnobControl.Value = 0; - // - // patternHitsDataGridView - // - this.patternHitsDataGridView.AllowUserToAddRows = false; - this.patternHitsDataGridView.AllowUserToDeleteRows = false; - this.patternHitsDataGridView.AllowUserToResizeRows = false; - this.patternHitsDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.patternHitsDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; - this.patternHitsDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; - this.patternHitsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.patternHitsDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; - this.patternHitsDataGridView.EditModeMenuStrip = null; - this.patternHitsDataGridView.Location = new System.Drawing.Point(3, 3); - this.patternHitsDataGridView.MultiSelect = false; - this.patternHitsDataGridView.Name = "patternHitsDataGridView"; - this.patternHitsDataGridView.ReadOnly = true; - this.patternHitsDataGridView.RowHeadersVisible = false; - this.patternHitsDataGridView.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.patternHitsDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; - this.patternHitsDataGridView.ShowCellToolTips = false; - 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); - // - // contentDataGridView - // - this.contentDataGridView.AllowUserToAddRows = false; - this.contentDataGridView.AllowUserToDeleteRows = false; - this.contentDataGridView.AllowUserToResizeRows = false; - this.contentDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.contentDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; - this.contentDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; - this.contentDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.contentDataGridView.EditModeMenuStrip = null; - this.contentDataGridView.Location = new System.Drawing.Point(3, 3); - this.contentDataGridView.Name = "contentDataGridView"; - this.contentDataGridView.ReadOnly = true; - this.contentDataGridView.RowHeadersVisible = false; - this.contentDataGridView.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.contentDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; - this.contentDataGridView.ShowCellToolTips = false; - 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); - // - // PatternWindow - // - this.ClientSize = new System.Drawing.Size(798, 165); - this.Controls.Add(this.rangeLabel); - this.Controls.Add(this.label3); - this.Controls.Add(this.panel4); - this.Controls.Add(this.splitContainer1); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.Name = "PatternWindow"; - this.Text = "Patterns"; - this.splitContainer1.Panel1.ResumeLayout(false); - this.splitContainer1.Panel2.ResumeLayout(false); - this.splitContainer1.ResumeLayout(false); - this.splitContainer2.Panel1.ResumeLayout(false); - this.splitContainer2.Panel2.ResumeLayout(false); - this.splitContainer2.ResumeLayout(false); - this.panel2.ResumeLayout(false); - this.panel2.PerformLayout(); - this.panel1.ResumeLayout(false); - this.panel1.PerformLayout(); - this.panel4.ResumeLayout(false); - this.panel4.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)(this.patternHitsDataGridView)).EndInit(); - ((System.ComponentModel.ISupportInitialize)(this.contentDataGridView)).EndInit(); - this.ResumeLayout(false); - - } - - #endregion - - private LogExpert.Dialogs.BufferedDataGridView patternHitsDataGridView; - private System.Windows.Forms.SplitContainer splitContainer1; - private System.Windows.Forms.SplitContainer splitContainer2; - private LogExpert.Dialogs.BufferedDataGridView contentDataGridView; - private System.Windows.Forms.Panel panel1; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Label blockLinesLabel; - private System.Windows.Forms.Panel panel2; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label blockCountLabel; - private System.Windows.Forms.Panel panel3; - private KnobControl fuzzyKnobControl; - private System.Windows.Forms.Panel panel4; - private System.Windows.Forms.Label label4; - private System.Windows.Forms.Label label5; - private KnobControl maxDiffKnobControl; - private System.Windows.Forms.Label label6; - private KnobControl maxMissesKnobControl; - private System.Windows.Forms.Label label7; - private KnobControl weigthKnobControl; - private System.Windows.Forms.Button recalcButton; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.Button setRangeButton; - private System.Windows.Forms.Label rangeLabel; - } +namespace LogExpert.UI.Controls.LogWindow +{ + partial class PatternWindow + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PatternWindow)); + this.splitContainer1 = new System.Windows.Forms.SplitContainer(); + this.panel3 = new System.Windows.Forms.Panel(); + this.splitContainer2 = new System.Windows.Forms.SplitContainer(); + this.panel2 = new System.Windows.Forms.Panel(); + this.blockCountLabel = new System.Windows.Forms.Label(); + this.label1 = new System.Windows.Forms.Label(); + this.panel1 = new System.Windows.Forms.Panel(); + this.label2 = new System.Windows.Forms.Label(); + this.blockLinesLabel = new System.Windows.Forms.Label(); + this.panel4 = new System.Windows.Forms.Panel(); + this.setRangeButton = new System.Windows.Forms.Button(); + this.label7 = new System.Windows.Forms.Label(); + this.recalcButton = new System.Windows.Forms.Button(); + this.label6 = new System.Windows.Forms.Label(); + this.label5 = new System.Windows.Forms.Label(); + this.label4 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.rangeLabel = new System.Windows.Forms.Label(); + this.weigthKnobControl = new KnobControl(); + this.maxMissesKnobControl = new KnobControl(); + this.maxDiffKnobControl = new KnobControl(); + this.fuzzyKnobControl = new KnobControl(); + this.patternHitsDataGridView = new LogExpert.Dialogs.BufferedDataGridView(); + this.contentDataGridView = new LogExpert.Dialogs.BufferedDataGridView(); + this.splitContainer1.Panel1.SuspendLayout(); + this.splitContainer1.Panel2.SuspendLayout(); + this.splitContainer1.SuspendLayout(); + this.splitContainer2.Panel1.SuspendLayout(); + this.splitContainer2.Panel2.SuspendLayout(); + this.splitContainer2.SuspendLayout(); + this.panel2.SuspendLayout(); + this.panel1.SuspendLayout(); + this.panel4.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.patternHitsDataGridView)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.contentDataGridView)).BeginInit(); + this.SuspendLayout(); + // + // splitContainer1 + // + this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.splitContainer1.BackColor = System.Drawing.SystemColors.Control; + this.splitContainer1.IsSplitterFixed = true; + this.splitContainer1.Location = new System.Drawing.Point(2, 1); + this.splitContainer1.Name = "splitContainer1"; + this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal; + // + // splitContainer1.Panel1 + // + this.splitContainer1.Panel1.Controls.Add(this.panel3); + this.splitContainer1.Panel1Collapsed = true; + this.splitContainer1.Panel1MinSize = 0; + // + // splitContainer1.Panel2 + // + this.splitContainer1.Panel2.Controls.Add(this.splitContainer2); + this.splitContainer1.Panel2MinSize = 0; + this.splitContainer1.Size = new System.Drawing.Size(795, 106); + this.splitContainer1.SplitterDistance = 106; + this.splitContainer1.TabIndex = 3; + // + // panel3 + // + this.panel3.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel3.Location = new System.Drawing.Point(0, 0); + this.panel3.Name = "panel3"; + this.panel3.Size = new System.Drawing.Size(150, 106); + this.panel3.TabIndex = 1; + // + // splitContainer2 + // + this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill; + this.splitContainer2.Location = new System.Drawing.Point(0, 0); + this.splitContainer2.Name = "splitContainer2"; + // + // splitContainer2.Panel1 + // + this.splitContainer2.Panel1.Controls.Add(this.panel2); + // + // splitContainer2.Panel2 + // + this.splitContainer2.Panel2.Controls.Add(this.panel1); + this.splitContainer2.Size = new System.Drawing.Size(795, 106); + this.splitContainer2.SplitterDistance = 294; + this.splitContainer2.TabIndex = 2; + // + // panel2 + // + this.panel2.Controls.Add(this.blockCountLabel); + this.panel2.Controls.Add(this.label1); + this.panel2.Controls.Add(this.patternHitsDataGridView); + this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel2.Location = new System.Drawing.Point(0, 0); + this.panel2.Name = "panel2"; + this.panel2.Size = new System.Drawing.Size(294, 106); + this.panel2.TabIndex = 2; + // + // blockCountLabel + // + this.blockCountLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.blockCountLabel.AutoSize = true; + this.blockCountLabel.Location = new System.Drawing.Point(184, 89); + this.blockCountLabel.Name = "blockCountLabel"; + this.blockCountLabel.Size = new System.Drawing.Size(13, 13); + this.blockCountLabel.TabIndex = 3; + this.blockCountLabel.Text = "0"; + // + // label1 + // + this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(0, 89); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(175, 13); + this.label1.TabIndex = 2; + this.label1.Text = "Number of blocks (pattern variants):"; + // + // panel1 + // + this.panel1.Controls.Add(this.label2); + this.panel1.Controls.Add(this.blockLinesLabel); + this.panel1.Controls.Add(this.contentDataGridView); + this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; + this.panel1.Location = new System.Drawing.Point(0, 0); + this.panel1.Name = "panel1"; + this.panel1.Size = new System.Drawing.Size(497, 106); + this.panel1.TabIndex = 1; + // + // label2 + // + this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(3, 89); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(61, 13); + this.label2.TabIndex = 2; + this.label2.Text = "Block lines:"; + // + // blockLinesLabel + // + this.blockLinesLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.blockLinesLabel.Location = new System.Drawing.Point(70, 89); + this.blockLinesLabel.Name = "blockLinesLabel"; + this.blockLinesLabel.Size = new System.Drawing.Size(69, 13); + this.blockLinesLabel.TabIndex = 1; + this.blockLinesLabel.Text = "0"; + // + // panel4 + // + this.panel4.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.panel4.Controls.Add(this.setRangeButton); + this.panel4.Controls.Add(this.label7); + this.panel4.Controls.Add(this.recalcButton); + this.panel4.Controls.Add(this.weigthKnobControl); + this.panel4.Controls.Add(this.label6); + this.panel4.Controls.Add(this.maxMissesKnobControl); + this.panel4.Controls.Add(this.label5); + this.panel4.Controls.Add(this.maxDiffKnobControl); + this.panel4.Controls.Add(this.label4); + this.panel4.Controls.Add(this.fuzzyKnobControl); + this.panel4.Location = new System.Drawing.Point(3, 106); + this.panel4.Name = "panel4"; + this.panel4.Size = new System.Drawing.Size(345, 57); + this.panel4.TabIndex = 5; + // + // setRangeButton + // + this.setRangeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.setRangeButton.Location = new System.Drawing.Point(267, 5); + this.setRangeButton.Name = "setRangeButton"; + this.setRangeButton.Size = new System.Drawing.Size(75, 23); + this.setRangeButton.TabIndex = 12; + this.setRangeButton.Text = "Set range"; + this.setRangeButton.UseVisualStyleBackColor = true; + this.setRangeButton.Click += new System.EventHandler(this.OnSetRangeButtonClick); + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(192, 41); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(41, 13); + this.label7.TabIndex = 11; + this.label7.Text = "Weigth"; + // + // recalcButton + // + this.recalcButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.recalcButton.Location = new System.Drawing.Point(267, 30); + this.recalcButton.Name = "recalcButton"; + this.recalcButton.Size = new System.Drawing.Size(75, 23); + this.recalcButton.TabIndex = 6; + this.recalcButton.Text = "Recalc"; + this.recalcButton.UseVisualStyleBackColor = true; + this.recalcButton.Click += new System.EventHandler(this.OnRecalcButtonClick); + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(113, 41); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(61, 13); + this.label6.TabIndex = 9; + this.label6.Text = "Max misses"; + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(57, 41); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(44, 13); + this.label5.TabIndex = 7; + this.label5.Text = "Max diff"; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(6, 41); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(34, 13); + this.label4.TabIndex = 5; + this.label4.Text = "Fuzzy"; + // + // label3 + // + this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.label3.Location = new System.Drawing.Point(483, 110); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(303, 49); + this.label3.TabIndex = 12; + this.label3.Text = "This feature is pre-beta and does not work :)\r\nUsage: Select a range in the log w" + + "indow and press \"Recalc\". \r\nThis will search for text ranges similar to the sele" + + "cted one."; + // + // rangeLabel + // + this.rangeLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.rangeLabel.Location = new System.Drawing.Point(352, 114); + this.rangeLabel.Name = "rangeLabel"; + this.rangeLabel.Size = new System.Drawing.Size(125, 42); + this.rangeLabel.TabIndex = 13; + this.rangeLabel.Text = "(no range set)"; + // + // weigthKnobControl + // + this.weigthKnobControl.Location = new System.Drawing.Point(202, 5); + this.weigthKnobControl.MaxValue = 30; + this.weigthKnobControl.MinValue = 1; + this.weigthKnobControl.Name = "weigthKnobControl"; + this.weigthKnobControl.Size = new System.Drawing.Size(21, 35); + this.weigthKnobControl.TabIndex = 10; + this.weigthKnobControl.Value = 0; + // + // maxMissesKnobControl + // + this.maxMissesKnobControl.Location = new System.Drawing.Point(134, 5); + this.maxMissesKnobControl.MaxValue = 30; + this.maxMissesKnobControl.MinValue = 0; + this.maxMissesKnobControl.Name = "maxMissesKnobControl"; + this.maxMissesKnobControl.Size = new System.Drawing.Size(22, 35); + this.maxMissesKnobControl.TabIndex = 8; + this.maxMissesKnobControl.Value = 0; + // + // maxDiffKnobControl + // + this.maxDiffKnobControl.Location = new System.Drawing.Point(69, 5); + this.maxDiffKnobControl.MaxValue = 30; + this.maxDiffKnobControl.MinValue = 0; + this.maxDiffKnobControl.Name = "maxDiffKnobControl"; + this.maxDiffKnobControl.Size = new System.Drawing.Size(21, 35); + this.maxDiffKnobControl.TabIndex = 6; + this.maxDiffKnobControl.Value = 0; + // + // fuzzyKnobControl + // + this.fuzzyKnobControl.Location = new System.Drawing.Point(9, 5); + this.fuzzyKnobControl.MaxValue = 20; + this.fuzzyKnobControl.MinValue = 0; + this.fuzzyKnobControl.Name = "fuzzyKnobControl"; + this.fuzzyKnobControl.Size = new System.Drawing.Size(22, 35); + this.fuzzyKnobControl.TabIndex = 4; + this.fuzzyKnobControl.Value = 0; + // + // patternHitsDataGridView + // + this.patternHitsDataGridView.AllowUserToAddRows = false; + this.patternHitsDataGridView.AllowUserToDeleteRows = false; + this.patternHitsDataGridView.AllowUserToResizeRows = false; + this.patternHitsDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.patternHitsDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; + this.patternHitsDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; + this.patternHitsDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.patternHitsDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; + this.patternHitsDataGridView.EditModeMenuStrip = null; + this.patternHitsDataGridView.Location = new System.Drawing.Point(3, 3); + this.patternHitsDataGridView.MultiSelect = false; + this.patternHitsDataGridView.Name = "patternHitsDataGridView"; + this.patternHitsDataGridView.ReadOnly = true; + this.patternHitsDataGridView.RowHeadersVisible = false; + this.patternHitsDataGridView.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.patternHitsDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.patternHitsDataGridView.ShowCellToolTips = false; + 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.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 + // + this.contentDataGridView.AllowUserToAddRows = false; + this.contentDataGridView.AllowUserToDeleteRows = false; + this.contentDataGridView.AllowUserToResizeRows = false; + this.contentDataGridView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.contentDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; + this.contentDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; + this.contentDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.contentDataGridView.EditModeMenuStrip = null; + this.contentDataGridView.Location = new System.Drawing.Point(3, 3); + this.contentDataGridView.Name = "contentDataGridView"; + this.contentDataGridView.ReadOnly = true; + this.contentDataGridView.RowHeadersVisible = false; + this.contentDataGridView.RowTemplate.DefaultCellStyle.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.contentDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.contentDataGridView.ShowCellToolTips = false; + 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.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 + // + this.ClientSize = new System.Drawing.Size(798, 165); + this.Controls.Add(this.rangeLabel); + this.Controls.Add(this.label3); + this.Controls.Add(this.panel4); + this.Controls.Add(this.splitContainer1); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.Name = "PatternWindow"; + this.Text = "Patterns"; + this.splitContainer1.Panel1.ResumeLayout(false); + this.splitContainer1.Panel2.ResumeLayout(false); + this.splitContainer1.ResumeLayout(false); + this.splitContainer2.Panel1.ResumeLayout(false); + this.splitContainer2.Panel2.ResumeLayout(false); + this.splitContainer2.ResumeLayout(false); + this.panel2.ResumeLayout(false); + this.panel2.PerformLayout(); + this.panel1.ResumeLayout(false); + this.panel1.PerformLayout(); + this.panel4.ResumeLayout(false); + this.panel4.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.patternHitsDataGridView)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.contentDataGridView)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private LogExpert.Dialogs.BufferedDataGridView patternHitsDataGridView; + private System.Windows.Forms.SplitContainer splitContainer1; + private System.Windows.Forms.SplitContainer splitContainer2; + private LogExpert.Dialogs.BufferedDataGridView contentDataGridView; + private System.Windows.Forms.Panel panel1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label blockLinesLabel; + private System.Windows.Forms.Panel panel2; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label blockCountLabel; + private System.Windows.Forms.Panel panel3; + private KnobControl fuzzyKnobControl; + private System.Windows.Forms.Panel panel4; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.Label label5; + private KnobControl maxDiffKnobControl; + private System.Windows.Forms.Label label6; + private KnobControl maxMissesKnobControl; + private System.Windows.Forms.Label label7; + private KnobControl weigthKnobControl; + private System.Windows.Forms.Button recalcButton; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Button setRangeButton; + private System.Windows.Forms.Label rangeLabel; + } } \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs new file mode 100644 index 00000000..7e784b6d --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.cs @@ -0,0 +1,368 @@ +using System.Runtime.Versioning; + +using LogExpert.Core.Classes; +using LogExpert.Core.EventArguments; +using LogExpert.Dialogs; + +namespace LogExpert.UI.Controls.LogWindow; + +[SupportedOSPlatform("windows")] +internal partial class PatternWindow : Form //TODO: Can this be changed to UserControl? +{ + #region Fields + + private readonly List> _blockList = []; + private PatternBlock _currentBlock; + private List _currentList; + + private readonly LogWindow _logWindow; + private PatternArgs _patternArgs = new(); + + #endregion + + #region cTor + + public PatternWindow () + { + InitializeComponent(); + } + + public PatternWindow (LogWindow logWindow) + { + _logWindow = logWindow; + InitializeComponent(); + recalcButton.Enabled = false; + } + + #endregion + + #region Properties + + public int Fuzzy + { + set => fuzzyKnobControl.Value = value; + get => fuzzyKnobControl.Value; + } + + public int MaxDiff + { + set => maxDiffKnobControl.Value = value; + get => maxDiffKnobControl.Value; + } + + public int MaxMisses + { + set => maxMissesKnobControl.Value = value; + get => maxMissesKnobControl.Value; + } + + public int Weight + { + set => weigthKnobControl.Value = value; + get => weigthKnobControl.Value; + } + + #endregion + + #region Public methods + + public void SetBlockList (List flatBlockList, PatternArgs patternArgs) + { + _patternArgs = patternArgs; + _blockList.Clear(); + List singeList = []; + //int blockId = -1; + + for (var i = 0; i < flatBlockList.Count; ++i) + { + var block = flatBlockList[i]; + singeList.Add(block); + //if (block.blockId != blockId) + //{ + // singeList = new List(); + // PatternBlock selfRefBlock = new PatternBlock(); + // selfRefBlock.targetStart = block.startLine; + // selfRefBlock.targetEnd = block.endLine; + // selfRefBlock.blockId = block.blockId; + // singeList.Add(selfRefBlock); + // singeList.Add(block); + // this.blockList.Add(singeList); + // blockId = block.blockId; + //} + //else + //{ + // singeList.Add(block); + //} + } + + _blockList.Add(singeList); + Invoke(new MethodInvoker(SetBlockListGuiStuff)); + } + + + public void SetColumnizer (ILogLineColumnizer columnizer) + { + _logWindow.SetColumnizer(columnizer, patternHitsDataGridView); + _logWindow.SetColumnizer(columnizer, contentDataGridView); + patternHitsDataGridView.Columns[0].Width = 20; + contentDataGridView.Columns[0].Width = 20; + + 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); + } + + 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); + + patternHitsDataGridView.DefaultCellStyle.Font = font; + contentDataGridView.DefaultCellStyle.Font = font; + //this.lineHeight = font.Height + 4; + patternHitsDataGridView.RowTemplate.Height = font.Height + 4; + contentDataGridView.RowTemplate.Height = font.Height + 4; + } + + #endregion + + #region Private Methods + + private void SetBlockListGuiStuff () + { + patternHitsDataGridView.RowCount = 0; + blockCountLabel.Text = "0"; + contentDataGridView.RowCount = 0; + blockLinesLabel.Text = "0"; + recalcButton.Enabled = true; + setRangeButton.Enabled = true; + if (_blockList.Count > 0) + { + SetCurrentList(_blockList[0]); + } + } + + private void SetCurrentList (List patternList) + { + patternHitsDataGridView.RowCount = 0; + _currentList = patternList; + patternHitsDataGridView.RowCount = _currentList.Count; + patternHitsDataGridView.Refresh(); + blockCountLabel.Text = "" + _currentList.Count; + } + + private int GetLineForHitGrid (int rowIndex) + { + int line; + line = _currentList[rowIndex].TargetStart; + return line; + } + + private int GetLineForContentGrid (int rowIndex) + { + int line; + line = _currentBlock.TargetStart + rowIndex; + return line; + } + + #endregion + + #region Events handler + + 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; + } + else + { + if (colIndex > 1) + { + colIndex--; // correct the additional inserted col + } + + e.Value = _logWindow.GetCellValue(rowIndex, colIndex); + } + } + + private void OnPatternHitsDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) + { + if (_currentList == null || e.RowIndex < 0) + { + return; + } + + if (e.ColumnIndex == 1) + { + e.PaintBackground(e.CellBounds, false); + var selCount = _patternArgs.EndLine - _patternArgs.StartLine; + 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); + + using var brush = new SolidBrush(Color.FromArgb(alpha, 170, 180, 150));//gray green + rect.Inflate(-2, -1); + e.Graphics.FillRectangle(brush, rect); + } + + e.PaintContent(e.CellBounds); + e.Handled = true; + } + else + { + var gridView = (BufferedDataGridView)sender; + var rowIndex = GetLineForHitGrid(e.RowIndex); + _logWindow.CellPainting(gridView.Focused, rowIndex, e.ColumnIndex, false, e); + } + } + + private void OnPatternHitsDataGridViewMouseDoubleClick (object sender, MouseEventArgs e) + { + //if (this.currentList == null || patternHitsDataGridView.CurrentRow == null) + // return; + //int rowIndex = GetLineForHitGrid(patternHitsDataGridView.CurrentRow.Index); + + //this.logWindow.SelectLogLine(rowIndex); + } + + private void OnPatternHitsDataGridViewCurrentCellChanged (object sender, EventArgs e) + { + if (_currentList == null || patternHitsDataGridView.CurrentRow == null) + { + return; + } + + if (patternHitsDataGridView.CurrentRow.Index > _currentList.Count - 1) + { + return; + } + + contentDataGridView.RowCount = 0; + _currentBlock = _currentList[patternHitsDataGridView.CurrentRow.Index]; + contentDataGridView.RowCount = _currentBlock.TargetEnd - _currentBlock.TargetStart + 1; + contentDataGridView.Refresh(); + contentDataGridView.CurrentCell = contentDataGridView.Rows[0].Cells[0]; + blockLinesLabel.Text = $"{contentDataGridView.RowCount}"; + } + + 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) + { + e.Value = _currentBlock.QualityInfoList.TryGetValue(rowIndex, out var qi) + ? qi.Quality + : string.Empty; + } + else + { + if (colIndex != 0) + { + colIndex--; // adjust the inserted column + } + + e.Value = _logWindow.GetCellValue(rowIndex, colIndex); + } + } + + 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.Focused, rowIndex, e.ColumnIndex, false, 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 OnRecalcButtonClick (object sender, EventArgs e) + { + _patternArgs.Fuzzy = fuzzyKnobControl.Value; + _patternArgs.MaxDiffInBlock = maxDiffKnobControl.Value; + _patternArgs.MaxMisses = maxMissesKnobControl.Value; + _patternArgs.MinWeight = weigthKnobControl.Value; + _logWindow.PatternStatistic(_patternArgs); + recalcButton.Enabled = false; + setRangeButton.Enabled = false; + } + + private void OnCloseButtonClick (object sender, EventArgs e) + { + Close(); + } + + private void OnContentDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) + { + e.Handled = true; + contentDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + } + + private void OnPatternHitsDataGridViewColumnDividerDoubleClick (object sender, DataGridViewColumnDividerDoubleClickEventArgs e) + { + e.Handled = true; + patternHitsDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + } + + private void OnSetRangeButtonClick (object sender, EventArgs e) + { + _logWindow.PatternStatisticSelectRange(_patternArgs); + recalcButton.Enabled = true; + rangeLabel.Text = $"Start: {_patternArgs.StartLine}\nEnd: {_patternArgs.EndLine}"; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Controls/PatternWindow.resx b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.resx similarity index 98% rename from src/LogExpert/Controls/PatternWindow.resx rename to src/LogExpert.UI/Controls/LogWindow/PatternWindow.resx index 20cf2a6f..e97451d5 100644 --- a/src/LogExpert/Controls/PatternWindow.resx +++ b/src/LogExpert.UI/Controls/LogWindow/PatternWindow.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + + 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/RangeFinder.cs b/src/LogExpert.UI/Controls/LogWindow/RangeFinder.cs new file mode 100644 index 00000000..68b4d258 --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/RangeFinder.cs @@ -0,0 +1,107 @@ +using System.Globalization; + +using LogExpert.Core.Callback; +using LogExpert.Core.Classes; +using LogExpert.Core.Classes.Filter; +using LogExpert.Core.Entities; + +using NLog; + +using Range = LogExpert.Core.Entities.Range; + +namespace LogExpert.UI.Controls.LogWindow; + +/// +/// Delivers the range (from..to) that matches the current range filter settings starting from a given line. +/// +internal class RangeFinder(FilterParams filterParams, ColumnizerCallback callback) +{ + #region Fields + + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + private readonly FilterParams _filterParams = filterParams.CloneWithCurrentColumnizer(); + + #endregion + + #region Public methods + + public Range FindRange(int startLine) + { + _logger.Info($"Starting range search for {_filterParams.SearchText} ... {_filterParams.RangeSearchText}"); + + if (_filterParams.RangeSearchText == null || _filterParams.RangeSearchText.Trim().Length == 0) + { + _logger.Info(CultureInfo.InvariantCulture, "Range search text not set. Cancelling range search."); + return null; + } + if (_filterParams.SearchText == null || _filterParams.SearchText.Trim().Length == 0) + { + _logger.Info(CultureInfo.InvariantCulture, "Search text not set. Cancelling range search."); + return null; + } + + _filterParams.IsRangeSearch = false; + _filterParams.IsInRange = false; + + var lineCount = callback.GetLineCount(); + var lineNum = startLine; + var foundStartLine = false; + + Range range = new(); + FilterParams tmpParam = _filterParams.CloneWithCurrentColumnizer(); + + tmpParam.SearchText = _filterParams.RangeSearchText; + + // search backward for starting keyword + var line = callback.GetLogLine(lineNum); + + while (lineNum >= 0) + { + callback.LineNum = lineNum; + + if (Util.TestFilterCondition(_filterParams, line, callback)) + { + foundStartLine = true; + break; + } + lineNum--; + line = callback.GetLogLine(lineNum); + + if (lineNum < 0 || Util.TestFilterCondition(tmpParam, line, callback)) // do not crash on Ctrl+R when there is not start line found + { + // lower range bound found --> we are not in between a valid range + break; + } + } + + if (!foundStartLine) + { + _logger.Info(CultureInfo.InvariantCulture, "Range start not found"); + return null; + } + + range.StartLine = lineNum; + _filterParams.IsRangeSearch = true; + _filterParams.IsInRange = true; + lineNum++; + + while (lineNum < lineCount) + { + line = callback.GetLogLine(lineNum); + callback.LineNum = lineNum; + if (!Util.TestFilterCondition(_filterParams, line, callback)) + { + break; + } + lineNum++; + } + lineNum--; + range.EndLine = lineNum; + + _logger.Info($"Range search finished. Found {range.EndLine - range.StartLine} lines"); + + return range; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs new file mode 100644 index 00000000..ab326b5d --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadCalculator.cs @@ -0,0 +1,428 @@ +using System.Globalization; + +using LogExpert.Core.Callback; +using LogExpert.Core.Classes; +using LogExpert.Core.Interface; + +using NLog; + +namespace LogExpert.UI.Controls.LogWindow; + +internal class TimeSpreadCalculator +{ + #region Fields + + private const int INACTIVITY_TIME = 2000; + + private const int MAX_CONTRAST = 1300; + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + + private readonly EventWaitHandle _calcEvent = new ManualResetEvent(false); + private readonly ColumnizerCallback _callback; + + private readonly object _diffListLock = new(); + private readonly EventWaitHandle _lineCountEvent = new ManualResetEvent(false); + + //TODO Refactor that it does not need LogWindow + private readonly ILogWindow _logWindow; + + // for DoCalc_via_Time + private double _average; + + private int _contrast = 400; + private int _displayHeight; + private bool _enabled; + private DateTime _endTimestamp; + private int _lineCount; + private int _maxDiff; + private bool _shouldStop; + private readonly CancellationTokenSource _cts = new(); + private DateTime _startTimestamp; + + private bool _timeMode = true; + + // for DoCalc + private int _timePerLine; + + #endregion + + #region cTor + + public TimeSpreadCalculator (ILogWindow logWindow) + { + _logWindow = logWindow; + _callback = new ColumnizerCallback(_logWindow); + + _ = Task.Run(WorkerFx, _cts.Token); + } + + #endregion + + #region Events + + public EventHandler CalcDone; + public EventHandler StartCalc; + + #endregion + + #region Properties + + public bool Enabled + { + get => _enabled; + set + { + _enabled = value; + if (_enabled) + { + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); + } + } + } + + public bool TimeMode + { + get => _timeMode; + set + { + _timeMode = value; + if (_enabled) + { + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); + } + } + } + + public int Contrast + { + set + { + _contrast = value; + if (_contrast < 0) + { + _contrast = 0; + } + else if (_contrast > MAX_CONTRAST) + { + _contrast = MAX_CONTRAST; + } + + if (TimeMode) + { + CalcValuesViaTime(_maxDiff, _average); + } + else + { + _ = CalcValuesViaLines(_timePerLine); + } + + OnCalcDone(EventArgs.Empty); + } + + get => _contrast; + } + + public List DiffList { get; set; } = []; + + #endregion + + #region Public methods + + public void Stop () + { + _shouldStop = true; + _ = _lineCountEvent.Set(); + + _cts.Cancel(); + } + + public void SetLineCount (int count) + { + _lineCount = count; + if (Enabled) + { + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); + } + } + + public void SetDisplayHeight (int height) + { + _displayHeight = height; + if (Enabled) + { + _ = _calcEvent.Set(); + _ = _lineCountEvent.Set(); + } + } + + #endregion + + #region Private Methods + + private void WorkerFx () + { + //Thread.CurrentThread.Name = "TimeSpreadCalculator Worker"; + //Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; + + while (!_shouldStop) + { + // wait for wakeup + _ = _lineCountEvent.WaitOne(); + + while (!_shouldStop) + { + // wait for unbusy moments + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator: wait for unbusy moments"); + var signaled = _calcEvent.WaitOne(INACTIVITY_TIME, false); + if (signaled == false) + { + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator: unbusy. starting calc."); + if (TimeMode) + { + DoCalc_via_Time(); + } + else + { + DoCalc(); + } + + break; + } + + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator: signalled. no calc."); + _ = _calcEvent.Reset(); + } + + _ = _lineCountEvent.Reset(); + } + } + + private void DoCalc () + { + OnStartCalc(EventArgs.Empty); + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() begin"); + + if (_callback.GetLineCount() < 1) + { + OnCalcDone(EventArgs.Empty); + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() end because of line count < 1"); + return; + } + + var lineNum = 0; + var lastLineNum = _callback.GetLineCount() - 1; + _startTimestamp = _logWindow.GetTimestampForLineForward(ref lineNum, false); + _endTimestamp = _logWindow.GetTimestampForLine(ref lastLineNum, false); + + var timePerLineSum = 0; + + if (_startTimestamp != DateTime.MinValue && _endTimestamp != DateTime.MinValue) + { + var overallSpan = _endTimestamp - _startTimestamp; + var overallSpanMillis = (int)(overallSpan.Ticks / TimeSpan.TicksPerMillisecond); + _timePerLine = (int)Math.Round(overallSpanMillis / (double)_lineCount); + 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); + + List newDiffList = []; + List maxList = []; + lineNum++; + + for (var i = lineNum; i < lastLineNum; i += step) + { + var currLineNum = i; + var time = _logWindow.GetTimestampForLineForward(ref currLineNum, false); + if (time != DateTime.MinValue) + { + var span = time - oldTime; + maxList.Add(span); + timePerLineSum += (int)(span.Ticks / TimeSpan.TicksPerMillisecond); + newDiffList.Add(new SpreadEntry(i, 0, time)); + oldTime = time; + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() time diff {0}", span); + } + } + + if (maxList.Count > 3) + { + maxList.Sort(); + } + + lock (_diffListLock) + { + DiffList = newDiffList; + _timePerLine = (int)Math.Round(timePerLineSum / ((double)(lastLineNum + 1) / step)); + _ = CalcValuesViaLines(_timePerLine); + OnCalcDone(EventArgs.Empty); + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() end"); + } + } + } + + //TODO Refactor this method + private void DoCalc_via_Time () + { + OnStartCalc(EventArgs.Empty); + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc_via_Time() begin"); + + if (_callback.GetLineCount() < 1) + { + OnCalcDone(EventArgs.Empty); + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() end because of line count < 1"); + return; + } + + var lineNum = 0; + var lastLineNum = _callback.GetLineCount() - 1; + _startTimestamp = _logWindow.GetTimestampForLineForward(ref lineNum, false); + _endTimestamp = _logWindow.GetTimestampForLine(ref lastLineNum, false); + + if (_startTimestamp != DateTime.MinValue && _endTimestamp != DateTime.MinValue) + { + var overallSpan = _endTimestamp - _startTimestamp; + var overallSpanMillis = overallSpan.Ticks / TimeSpan.TicksPerMillisecond; + //int timePerLine = (int)Math.Round((double)overallSpanMillis / (double)this.lineCount); + + 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; + var searchTimeStamp = _startTimestamp; + var oldLineNum = lineNum; + var loopCount = 0; + var lineDiffSum = 0; + var minDiff = int.MaxValue; + _maxDiff = 0; + List maxList = []; + List newDiffList = []; + + while (searchTimeStamp.CompareTo(_endTimestamp) <= 0) + { + lineNum = _logWindow.FindTimestampLineInternal(lineNum, lineNum, lastLineNum, searchTimeStamp, false); + if (lineNum < 0) + { + lineNum = -lineNum; + } + var lineDiff = lineNum - oldLineNum; + + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc_via_Time() test time {0:HH:mm:ss.fff} line diff={1}", searchTimeStamp, lineDiff); + + if (lineDiff >= 0) + { + lineDiffSum += lineDiff; + newDiffList.Add(new SpreadEntry(lineNum, lineDiff, searchTimeStamp)); + + if (lineDiff < minDiff) + { + minDiff = lineDiff; + } + + if (lineDiff > _maxDiff) + { + _maxDiff = lineDiff; + } + maxList.Add(lineDiff); + loopCount++; + } + + searchTimeStamp = searchTimeStamp.AddMilliseconds(step); + oldLineNum = lineNum; + //lineNum++; + } + + if (maxList.Count > 3) + { + maxList.Sort(); + _maxDiff = maxList[^3]; + } + + _average = lineDiffSum / (double)loopCount; + //double average = maxList[maxList.Count / 2]; + _logger.Debug(CultureInfo.InvariantCulture, "Average diff={0} minDiff={1} maxDiff={2}", _average, minDiff, _maxDiff); + + lock (_diffListLock) + { + if (newDiffList.Count > 0) + { + newDiffList.RemoveAt(0); + } + + if (newDiffList.Count > 0) + { + newDiffList.RemoveAt(0); + } + + DiffList = newDiffList; + CalcValuesViaTime(_maxDiff, _average); + OnCalcDone(EventArgs.Empty); + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc_via_Time() end"); + } + } + } + + private DateTime CalcValuesViaLines (int timePerLine) + { + var oldTime = DateTime.MinValue; + + if (DiffList.Count > 0) + { + oldTime = DiffList[0].Timestamp; + + foreach (var entry in DiffList) + { + var span = entry.Timestamp - oldTime; + double diffFromAverage = (int)(span.Ticks / TimeSpan.TicksPerMillisecond) - timePerLine; + + if (diffFromAverage < 0) + { + diffFromAverage = 0; + } + + var value = (int)(diffFromAverage / (timePerLine / TimeSpan.TicksPerMillisecond) * _contrast); + entry.Value = 255 - value; + oldTime = entry.Timestamp; + } + } + + return oldTime; + } + + private void CalcValuesViaTime (int maxDiff, double average) + { + foreach (var entry in DiffList) + { + var lineDiff = entry.Diff; + var diffFromAverage = entry.Diff - average; + + if (diffFromAverage < 0) + { + diffFromAverage = 0; + } + + var value = (int)(diffFromAverage / maxDiff * _contrast); + entry.Value = 255 - value; + + _logger.Debug(CultureInfo.InvariantCulture, "TimeSpreadCalculator.DoCalc() test time {0:HH:mm:ss.fff} line diff={1} value={2}", entry.Timestamp, lineDiff, value); + } + } + + private void OnCalcDone (EventArgs e) + { + CalcDone?.Invoke(this, e); + } + + private void OnStartCalc (EventArgs e) + { + StartCalc?.Invoke(this, e); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/TimeSpreadigControl.Designer.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs similarity index 72% rename from src/LogExpert/Dialogs/TimeSpreadigControl.Designer.cs rename to src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs index 5f8d1dc8..48595990 100644 --- a/src/LogExpert/Dialogs/TimeSpreadigControl.Designer.cs +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.Designer.cs @@ -1,49 +1,50 @@ -namespace LogExpert.Dialogs -{ - partial class TimeSpreadingControl - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.SuspendLayout(); - // - // TimeSpreadingControl - // - 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.ResumeLayout(false); - - } - - #endregion - } -} +namespace LogExpert.UI.Controls.LogWindow +{ + partial class TimeSpreadingControl + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.SuspendLayout(); + // + // TimeSpreadingControl + // + this.Name = "TimeSpreadingControl"; + this.Size = new System.Drawing.Size(26, 324); + 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); + + } + + #endregion + } +} diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs new file mode 100644 index 00000000..41c94c8d --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.cs @@ -0,0 +1,305 @@ +using System.Globalization; +using System.Runtime.Versioning; + +using LogExpert.Core.Classes; +using LogExpert.Core.EventArguments; +using LogExpert.UI.Extensions; + +using NLog; + +namespace LogExpert.UI.Controls.LogWindow; + +[SupportedOSPlatform("windows")] +internal partial class TimeSpreadingControl : UserControl +{ + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + #region Fields + + private Bitmap _bitmap = new(1, 1); + private int _displayHeight = 1; + private readonly int _edgeOffset = (int)NativeMethods.GetSystemMetricsForDpi(NativeMethods.SM_CYVSCROLL); + private int _lastMouseY; + private readonly object _monitor = new(); + private int _rectHeight = 1; + + private TimeSpreadCalculator _timeSpreadCalc; + private readonly ToolTip _toolTip; + + #endregion + + #region cTor + + public TimeSpreadingControl () + { + InitializeComponent(); + _toolTip = new ToolTip(); + Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); + _toolTip.InitialDelay = 0; + _toolTip.ReshowDelay = 0; + _toolTip.ShowAlways = true; + DoubleBuffered = false; + } + + #endregion + + #region Delegates + + #endregion + + #region Events + + public EventHandler LineSelected; + + #endregion + + #region Properties + + public bool ReverseAlpha { get; set; } + + internal TimeSpreadCalculator TimeSpreadCalc + { + get => _timeSpreadCalc; + set + { + //timeSpreadCalc.CalcDone -= timeSpreadCalc_CalcDone; + _timeSpreadCalc = value; + _timeSpreadCalc.CalcDone += OnTimeSpreadCalcCalcDone; + _timeSpreadCalc.StartCalc += OnTimeSpreadCalcStartCalc; + } + } + + #endregion + + #region Overrides + + protected override void OnPaint (PaintEventArgs e) + { + base.OnPaint(e); + lock (_monitor) + { + if (DesignMode) + { + using var bgBrush = new SolidBrush(Color.FromKnownColor(KnownColor.LightSkyBlue)); + var rect = ClientRectangle; + rect.Inflate(0, -_edgeOffset); + e.Graphics.FillRectangle(bgBrush, rect); + } + else + { + e.Graphics.DrawImage(_bitmap, 0, _edgeOffset); + } + } + } + + #endregion + + #region Private Methods + + private SpreadEntry GetEntryForMouse (MouseEventArgs e) + { + var list = TimeSpreadCalc.DiffList; + var y = e.Y - _edgeOffset; + if (y < 0) + { + y = 0; + } + else if (y >= ClientRectangle.Height - (_edgeOffset * 3)) + { + y = list.Count - 1; + } + else + { + y /= _rectHeight; + } + + lock (_monitor) + { + return y >= list.Count || y < 0 + ? null + : list[y]; + } + } + + private void DragContrast (MouseEventArgs e) + { + if (_lastMouseY == 0) + { + _lastMouseY = _lastMouseY = e.Y; + return; + } + + _timeSpreadCalc.Contrast += (_lastMouseY - e.Y) * 5; + _lastMouseY = e.Y; + } + + private void OnLineSelected (SelectLineEventArgs e) + { + LineSelected?.Invoke(this, e); + } + + #endregion + + #region Events handler + + private void OnTimeSpreadCalcCalcDone (object sender, EventArgs e) + { + _logger.Debug(CultureInfo.InvariantCulture, "timeSpreadCalc_CalcDone()"); + + lock (_monitor) + { + Invalidate(); + var rect = ClientRectangle; + rect.Size = new Size(rect.Width, rect.Height - (_edgeOffset * 3)); + + if (rect.Height < 1) + { + return; + } + + _bitmap = new Bitmap(rect.Width, rect.Height); + using var gfx = Graphics.FromImage(_bitmap); + using var bgBrush = new SolidBrush(BackColor); + gfx.FillRectangle(bgBrush, rect); + + var list = TimeSpreadCalc.DiffList; + int step; + + if (list.Count >= _displayHeight) + { + step = (int)Math.Round(list.Count / (double)_displayHeight); + _rectHeight = 1; + } + else + { + step = 1; + _rectHeight = (int)Math.Round(_displayHeight / (double)list.Count); + } + + Rectangle fillRect = new(0, 0, rect.Width, _rectHeight); + + lock (list) + { + for (var i = 0; i < list.Count; i += step) + { + var entry = list[i]; + var color = ReverseAlpha ? entry.Value : 255 - entry.Value; + + if (color > 255) + { + color = 255; + } + + if (color < 0) + { + color = 0; + } + + using var brush = new SolidBrush(Color.FromArgb(color, ForeColor)); + gfx.FillRectangle(brush, fillRect); + fillRect.Offset(0, _rectHeight); + } + } + } + + BeginInvoke(new MethodInvoker(Refresh)); + } + + private void OnTimeSpreadCalcStartCalc (object sender, EventArgs e) + { + lock (_monitor) + { + Invalidate(); + var rect = ClientRectangle; + rect.Size = new Size(rect.Width, rect.Height - (_edgeOffset * 3)); + + if (rect.Height < 1) + { + return; + } + + //this.bmp = new Bitmap(rect.Width, rect.Height); + var gfx = Graphics.FromImage(_bitmap); + + using var bgBrush = new SolidBrush(BackColor); + using var fgBrush = new SolidBrush(ForeColor); + //gfx.FillRectangle(bgBrush, rect); + + StringFormat format = new(StringFormatFlags.DirectionVertical | StringFormatFlags.NoWrap) + { + LineAlignment = StringAlignment.Center, + Alignment = StringAlignment.Center + }; + + RectangleF rectf = new(rect.Left, rect.Top, rect.Width, rect.Height); + + gfx.DrawString("Calculating time spread view...", Font, fgBrush, rectf, format); + } + + BeginInvoke(new MethodInvoker(Refresh)); + } + + private void OnTimeSpreadingControlSizeChanged (object sender, EventArgs e) + { + if (TimeSpreadCalc != null) + { + _displayHeight = ClientRectangle.Height - (_edgeOffset * 3); + TimeSpreadCalc.SetDisplayHeight(_displayHeight); + } + } + + private void OnTimeSpreadingControlMouseDown (object sender, MouseEventArgs e) + { + } + + private void OnTimeSpreadingControlMouseUp (object sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Left) + { + var entry = GetEntryForMouse(e); + if (entry == null) + { + return; + } + + OnLineSelected(new SelectLineEventArgs(entry.LineNum)); + } + } + + private void OnTimeSpreadingControlMouseEnter (object sender, EventArgs e) + { + _toolTip.Active = true; + } + + private void OnTimeSpreadingControlMouseLeave (object sender, EventArgs e) + { + _toolTip.Active = false; + } + + private void OnTimeSpreadingControlMouseMove (object sender, MouseEventArgs e) + { + if (e.Y == _lastMouseY) + { + return; + } + + if (e.Button == MouseButtons.Right) + { + DragContrast(e); + return; + } + + var entry = GetEntryForMouse(e); + + if (entry == null) + { + return; + } + + _lastMouseY = e.Y; + var dts = $"{entry.Timestamp:dd.MM.yyyy HH:mm:ss}"; + _toolTip.SetToolTip(this, "Line " + (entry.LineNum + 1) + "\n" + dts); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/TimeSpreadigControl.resx b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.resx similarity index 97% rename from src/LogExpert/Dialogs/TimeSpreadigControl.resx rename to src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.resx index ff31a6db..19dc0dd8 100644 --- a/src/LogExpert/Dialogs/TimeSpreadigControl.resx +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSpreadigControl.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + \ No newline at end of file diff --git a/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs b/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs new file mode 100644 index 00000000..fe51937b --- /dev/null +++ b/src/LogExpert.UI/Controls/LogWindow/TimeSyncList.cs @@ -0,0 +1,100 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Controls.LogWindow; + +/// +/// Holds all windows which are in sync via timestamp +/// +internal class TimeSyncList +{ + #region Fields + + private readonly IList logWindowList = []; + + #endregion + + #region Delegates + + public delegate void WindowRemovedEventHandler (object sender, EventArgs e); + + #endregion + + #region Events + + public event WindowRemovedEventHandler WindowRemoved; + + #endregion + + #region Properties + + public DateTime CurrentTimestamp { get; set; } + + [SupportedOSPlatform("windows")] + public int Count => logWindowList.Count; + + #endregion + + #region Public methods + + [SupportedOSPlatform("windows")] + public void AddWindow (LogWindow logWindow) + { + lock (logWindowList) + { + if (!logWindowList.Contains(logWindow)) + { + logWindowList.Add(logWindow); + } + } + } + + [SupportedOSPlatform("windows")] + public void RemoveWindow (LogWindow logWindow) + { + lock (logWindowList) + { + logWindowList.Remove(logWindow); + } + + OnWindowRemoved(); + } + + + /// + /// Scrolls all LogWindows to the given timestamp + /// + /// + /// + [SupportedOSPlatform("windows")] + public void NavigateToTimestamp (DateTime timestamp, LogWindow sender) + { + CurrentTimestamp = timestamp; + lock (logWindowList) + { + foreach (LogWindow logWindow in logWindowList) + { + if (sender != logWindow) + { + logWindow.ScrollToTimestamp(timestamp, false, false); + } + } + } + } + + [SupportedOSPlatform("windows")] + public bool Contains (LogWindow logWindow) + { + return logWindowList.Contains(logWindow); + } + + #endregion + + #region Private Methods + + private void OnWindowRemoved () + { + WindowRemoved?.Invoke(this, new EventArgs()); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/AboutBox.Designer.cs b/src/LogExpert.UI/Dialogs/AboutBox.Designer.cs new file mode 100644 index 00000000..c303fc7c --- /dev/null +++ b/src/LogExpert.UI/Dialogs/AboutBox.Designer.cs @@ -0,0 +1,203 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +partial class AboutBox + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent () + { + tableLayoutPanel = new TableLayoutPanel(); + logoPictureBox = new PictureBox(); + labelProductName = new Label(); + labelVersion = new Label(); + labelCopyright = new Label(); + linkLabelURL = new LinkLabel(); + okPanel = new Panel(); + okButton = new Button(); + usedComponentsDataGrid = new DataGridView(); + tableLayoutPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)logoPictureBox).BeginInit(); + okPanel.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)usedComponentsDataGrid).BeginInit(); + SuspendLayout(); + // + // tableLayoutPanel + // + tableLayoutPanel.ColumnCount = 2; + tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 34.25484F)); + tableLayoutPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 65.74516F)); + tableLayoutPanel.Controls.Add(logoPictureBox, 0, 0); + tableLayoutPanel.Controls.Add(labelProductName, 1, 0); + tableLayoutPanel.Controls.Add(labelVersion, 1, 1); + tableLayoutPanel.Controls.Add(labelCopyright, 1, 2); + tableLayoutPanel.Controls.Add(linkLabelURL, 1, 3); + tableLayoutPanel.Controls.Add(okPanel, 1, 5); + tableLayoutPanel.Controls.Add(usedComponentsDataGrid, 1, 4); + tableLayoutPanel.Dock = DockStyle.Fill; + tableLayoutPanel.Location = new Point(14, 14); + tableLayoutPanel.Margin = new Padding(4, 5, 4, 5); + tableLayoutPanel.Name = "tableLayoutPanel"; + tableLayoutPanel.RowCount = 6; + tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 9.912043F)); + tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 9.912043F)); + tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 9.47226F)); + tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 11.84032F)); + tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 46.68471F)); + tableLayoutPanel.RowStyles.Add(new RowStyle(SizeType.Percent, 12.17862F)); + tableLayoutPanel.Size = new Size(914, 649); + tableLayoutPanel.TabIndex = 0; + // + // logoPictureBox + // + logoPictureBox.Dock = DockStyle.Fill; + logoPictureBox.Location = new Point(4, 5); + logoPictureBox.Margin = new Padding(4, 5, 4, 5); + logoPictureBox.Name = "logoPictureBox"; + tableLayoutPanel.SetRowSpan(logoPictureBox, 6); + logoPictureBox.Size = new Size(305, 639); + logoPictureBox.SizeMode = PictureBoxSizeMode.CenterImage; + logoPictureBox.TabIndex = 12; + logoPictureBox.TabStop = false; + // + // labelProductName + // + labelProductName.Dock = DockStyle.Fill; + labelProductName.Font = new Font("Microsoft Sans Serif", 10F, FontStyle.Bold, GraphicsUnit.Point, 0); + labelProductName.Location = new Point(322, 0); + labelProductName.Margin = new Padding(9, 0, 4, 0); + labelProductName.MaximumSize = new Size(0, 26); + labelProductName.Name = "labelProductName"; + labelProductName.Size = new Size(588, 26); + labelProductName.TabIndex = 19; + labelProductName.Text = "Product Name"; + labelProductName.TextAlign = ContentAlignment.MiddleLeft; + // + // labelVersion + // + labelVersion.Dock = DockStyle.Fill; + labelVersion.Location = new Point(322, 64); + labelVersion.Margin = new Padding(9, 0, 4, 0); + labelVersion.MaximumSize = new Size(0, 26); + labelVersion.Name = "labelVersion"; + labelVersion.Size = new Size(588, 26); + labelVersion.TabIndex = 0; + labelVersion.Text = "Version"; + labelVersion.TextAlign = ContentAlignment.MiddleLeft; + // + // labelCopyright + // + labelCopyright.Dock = DockStyle.Fill; + labelCopyright.Location = new Point(322, 128); + labelCopyright.Margin = new Padding(9, 0, 4, 0); + labelCopyright.Name = "labelCopyright"; + labelCopyright.Size = new Size(588, 61); + labelCopyright.TabIndex = 21; + labelCopyright.Text = "Copyright"; + labelCopyright.TextAlign = ContentAlignment.MiddleLeft; + // + // linkLabelURL + // + linkLabelURL.AutoSize = true; + linkLabelURL.Dock = DockStyle.Fill; + linkLabelURL.Location = new Point(317, 189); + linkLabelURL.Margin = new Padding(4, 0, 4, 0); + linkLabelURL.Name = "linkLabelURL"; + linkLabelURL.Size = new Size(593, 76); + linkLabelURL.TabIndex = 25; + linkLabelURL.TabStop = true; + linkLabelURL.Text = "https://github.com/LogExperts/LogExpert"; + linkLabelURL.TextAlign = ContentAlignment.MiddleLeft; + linkLabelURL.LinkClicked += OnLinkLabelURLClicked; + // + // okPanel + // + okPanel.Controls.Add(okButton); + okPanel.Dock = DockStyle.Fill; + okPanel.Location = new Point(317, 572); + okPanel.Margin = new Padding(4, 5, 4, 5); + okPanel.Name = "okPanel"; + okPanel.Size = new Size(593, 72); + okPanel.TabIndex = 26; + // + // okButton + // + okButton.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + okButton.DialogResult = DialogResult.OK; + okButton.Location = new Point(475, 32); + okButton.Margin = new Padding(4, 5, 4, 5); + okButton.Name = "okButton"; + okButton.Size = new Size(114, 35); + okButton.TabIndex = 0; + okButton.Text = "&OK"; + okButton.UseVisualStyleBackColor = true; + // + // usedComponentsDataGrid + // + usedComponentsDataGrid.AllowUserToAddRows = false; + usedComponentsDataGrid.AllowUserToDeleteRows = false; + usedComponentsDataGrid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells; + usedComponentsDataGrid.BackgroundColor = SystemColors.Control; + usedComponentsDataGrid.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize; + usedComponentsDataGrid.Dock = DockStyle.Fill; + usedComponentsDataGrid.Location = new Point(316, 268); + usedComponentsDataGrid.Name = "usedComponentsDataGrid"; + usedComponentsDataGrid.ReadOnly = true; + usedComponentsDataGrid.Size = new Size(595, 296); + usedComponentsDataGrid.TabIndex = 27; + // + // AboutBox + // + ClientSize = new Size(942, 677); + Controls.Add(tableLayoutPanel); + Margin = new Padding(4, 5, 4, 5); + MaximizeBox = false; + MinimizeBox = false; + Name = "AboutBox"; + Padding = new Padding(14); + ShowIcon = false; + ShowInTaskbar = false; + StartPosition = FormStartPosition.CenterParent; + Text = "AboutBox"; + tableLayoutPanel.ResumeLayout(false); + tableLayoutPanel.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)logoPictureBox).EndInit(); + okPanel.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)usedComponentsDataGrid).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.TableLayoutPanel tableLayoutPanel; + private System.Windows.Forms.PictureBox logoPictureBox; + private System.Windows.Forms.Label labelProductName; + private System.Windows.Forms.Label labelVersion; + private System.Windows.Forms.Label labelCopyright; + private System.Windows.Forms.LinkLabel linkLabelURL; + private System.Windows.Forms.Panel okPanel; + private System.Windows.Forms.Button okButton; + private DataGridView usedComponentsDataGrid; +} diff --git a/src/LogExpert.UI/Dialogs/AboutBox.cs b/src/LogExpert.UI/Dialogs/AboutBox.cs new file mode 100644 index 00000000..37afa730 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/AboutBox.cs @@ -0,0 +1,145 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.Versioning; + +using LogExpert.Core.Classes; + +using Newtonsoft.Json; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class AboutBox : Form +{ + #region Fields + + private readonly Assembly _assembly; + + #endregion + + #region cTor + + public AboutBox () + { + InitializeComponent(); + + LoadResources(); + usedComponentsDataGrid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill; + _assembly = Assembly.GetExecutingAssembly(); + + Text = $@"About {AssemblyTitle}"; + labelProductName.Text = AssemblyProduct; + labelVersion.Text = AssemblyVersion; + labelCopyright.Text = AssemblyCopyright; + var link = "https://github.com/LogExperts/LogExpert"; + _ = linkLabelURL.Links.Add(new LinkLabel.Link(0, link.Length, link)); + LoadUsedComponents(); + } + + //Name, Version, License, Download, Source + + private void LoadUsedComponents () + { + var json = File.ReadAllText($"{Application.StartupPath}files\\json\\usedComponents.json"); + var usedComponents = JsonConvert.DeserializeObject(json); + usedComponents = usedComponents?.OrderBy(x => x.PackageId).ToArray(); + usedComponentsDataGrid.DataSource = usedComponents; + + } + + + private void LoadResources () + { + logoPictureBox.Image = Resources.LogLover; + } + + #endregion + + #region Properties + + public string AssemblyTitle + { + get + { + var attributes = _assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); + if (attributes.Length > 0) + { + var titleAttribute = (AssemblyTitleAttribute)attributes[0]; + if (!string.IsNullOrEmpty(titleAttribute.Title)) + { + return titleAttribute.Title; + } + } + return Path.GetFileNameWithoutExtension(_assembly.Location); + } + } + + public string AssemblyVersion + { + get + { + var assembly = _assembly.GetName(); + + return assembly.Version != null + ? $"{assembly.Version.Major}.{assembly.Version.Minor}.{assembly.Version.Build}.{assembly.Version.Revision}" + : "0.0.0.0"; + } + + } + + public string AssemblyDescription + { + get + { + var attributes = _assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); + + return attributes.Length == 0 + ? string.Empty + : ((AssemblyDescriptionAttribute)attributes[0]).Description; + } + } + + public string AssemblyProduct + { + get + { + var attributes = _assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); + return attributes.Length == 0 + ? string.Empty + : ((AssemblyProductAttribute)attributes[0]).Product; + } + } + + public string AssemblyCopyright + { + get + { + var attributes = _assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); + return attributes.Length == 0 + ? string.Empty + : ((AssemblyCopyrightAttribute)attributes[0]).Copyright; + } + } + + #endregion + + #region Events handler + + private void OnLinkLabelURLClicked (object sender, LinkLabelLinkClickedEventArgs e) + { + var target = string.Empty; + + if (e.Link != null) + { + target = e.Link.LinkData as string; + } + + _ = Process.Start(new ProcessStartInfo + { + UseShellExecute = true, + FileName = target, + }); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/AboutBox.resx b/src/LogExpert.UI/Dialogs/AboutBox.resx similarity index 97% rename from src/LogExpert/Dialogs/AboutBox.resx rename to src/LogExpert.UI/Dialogs/AboutBox.resx index 4f24d55c..8b2ff64a 100644 --- a/src/LogExpert/Dialogs/AboutBox.resx +++ b/src/LogExpert.UI/Dialogs/AboutBox.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Dialogs/AllowOnlyOneInstanceErrorDialog.Designer.cs b/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.Designer.cs new file mode 100644 index 00000000..6a07b9df --- /dev/null +++ b/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.Designer.cs @@ -0,0 +1,98 @@ +namespace LogExpert.Dialogs; + +partial class AllowOnlyOneInstanceErrorDialog +{ + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + this.checkBoxIgnoreMessage = new System.Windows.Forms.CheckBox(); + this.buttonOk = new System.Windows.Forms.Button(); + this.labelErrorText = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // checkBoxIgnoreMessage + // + this.checkBoxIgnoreMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.checkBoxIgnoreMessage.AutoSize = true; + this.checkBoxIgnoreMessage.Location = new System.Drawing.Point(9, 56); + this.checkBoxIgnoreMessage.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.checkBoxIgnoreMessage.Name = "checkBoxIgnoreMessage"; + this.checkBoxIgnoreMessage.Size = new System.Drawing.Size(177, 17); + this.checkBoxIgnoreMessage.TabIndex = 0; + this.checkBoxIgnoreMessage.Text = "Show this message only once\\?"; + this.checkBoxIgnoreMessage.UseVisualStyleBackColor = true; + // + // buttonOk + // + this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(209, 53); + this.buttonOk.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(74, 23); + this.buttonOk.TabIndex = 1; + this.buttonOk.Text = "Ok"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); + // + // labelErrorText + // + this.labelErrorText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.labelErrorText.AutoEllipsis = true; + this.labelErrorText.Location = new System.Drawing.Point(9, 8); + this.labelErrorText.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); + this.labelErrorText.Name = "labelErrorText"; + this.labelErrorText.Size = new System.Drawing.Size(273, 43); + this.labelErrorText.TabIndex = 2; + this.labelErrorText.Text = "Only one instance allowed, uncheck \\\"View Settings => Allow only 1 Instances\\\" to" + +" start multiple instances!"; + // + // AllowOnlyOneInstanceErrorDialog + // + this.ClientSize = new System.Drawing.Size(293, 84); + this.Controls.Add(this.labelErrorText); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.checkBoxIgnoreMessage); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); + this.MaximizeBox = false; + this.Name = "AllowOnlyOneInstanceErrorDialog"; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.Text = "AllowOnlyOneInstanceErrorDialog"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.CheckBox checkBoxIgnoreMessage; + private System.Windows.Forms.Button buttonOk; + private System.Windows.Forms.Label labelErrorText; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.cs b/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.cs new file mode 100644 index 00000000..3c046848 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/AllowOnlyOneInstanceErrorDialog.cs @@ -0,0 +1,25 @@ +using System.Runtime.Versioning; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +public partial class AllowOnlyOneInstanceErrorDialog : Form +{ + public bool DoNotShowThisMessageAgain { get; private set; } + + public AllowOnlyOneInstanceErrorDialog () + { + InitializeComponent(); + SetText(); + } + + private void SetText () + { + labelErrorText.Text = @"Only one instance allowed, uncheck ""View Settings => Allow only 1 Instances"" to start multiple instances!"; + } + + private void OnButtonOkClick (object sender, System.EventArgs e) + { + DoNotShowThisMessageAgain = checkBoxIgnoreMessage.Checked; + } +} diff --git a/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.Designer.cs b/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.Designer.cs new file mode 100644 index 00000000..06aa2968 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.Designer.cs @@ -0,0 +1,89 @@ +namespace LogExpert.Dialogs; + +partial class BookmarkCommentDlg +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BookmarkCommentDlg)); + this.okButton = new System.Windows.Forms.Button(); + this.cancelButton = new System.Windows.Forms.Button(); + this.commentTextBox = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // okButton + // + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okButton.Location = new System.Drawing.Point(150, 86); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(75, 23); + this.okButton.TabIndex = 1; + this.okButton.Text = "OK"; + this.okButton.UseVisualStyleBackColor = true; + // + // cancelButton + // + this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.cancelButton.Location = new System.Drawing.Point(241, 86); + this.cancelButton.Name = "cancelButton"; + this.cancelButton.Size = new System.Drawing.Size(75, 23); + this.cancelButton.TabIndex = 2; + this.cancelButton.Text = "&Cancel"; + this.cancelButton.UseVisualStyleBackColor = true; + // + // commentTextBox + // + this.commentTextBox.Dock = System.Windows.Forms.DockStyle.Top; + this.commentTextBox.Location = new System.Drawing.Point(0, 0); + this.commentTextBox.Multiline = true; + this.commentTextBox.Name = "commentTextBox"; + this.commentTextBox.Size = new System.Drawing.Size(324, 80); + this.commentTextBox.TabIndex = 0; + // + // BookmarkCommentDlg + // + this.AcceptButton = this.okButton; + this.CancelButton = this.cancelButton; + this.ClientSize = new System.Drawing.Size(324, 115); + this.Controls.Add(this.commentTextBox); + this.Controls.Add(this.cancelButton); + this.Controls.Add(this.okButton); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.Name = "BookmarkCommentDlg"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Bookmark comment"; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Button okButton; +private System.Windows.Forms.Button cancelButton; +private System.Windows.Forms.TextBox commentTextBox; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.cs b/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.cs new file mode 100644 index 00000000..7949c604 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.cs @@ -0,0 +1,29 @@ +using System.Runtime.Versioning; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class BookmarkCommentDlg : Form +{ + #region cTor + + public BookmarkCommentDlg() + { + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + InitializeComponent(); + } + + #endregion + + #region Properties + + public string Comment + { + set => commentTextBox.Text = value; + get => commentTextBox.Text; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/BookmarkCommentDlg.resx b/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.resx similarity index 98% rename from src/LogExpert/Dialogs/BookmarkCommentDlg.resx rename to src/LogExpert.UI/Dialogs/BookmarkCommentDlg.resx index 20cf2a6f..e97451d5 100644 --- a/src/LogExpert/Dialogs/BookmarkCommentDlg.resx +++ b/src/LogExpert.UI/Dialogs/BookmarkCommentDlg.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + + 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/Dialogs/BookmarkWindow.Designer.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.Designer.cs new file mode 100644 index 00000000..9467414c --- /dev/null +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.Designer.cs @@ -0,0 +1,195 @@ +namespace LogExpert.Dialogs; +partial class BookmarkWindow { +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() { + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BookmarkWindow)); + this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); + this.deleteBookmarkssToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.removeCommentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); + this.bookmarkTextBox = new System.Windows.Forms.TextBox(); + this.splitContainer1 = new System.Windows.Forms.SplitContainer(); + this.bookmarkDataGridView = new LogExpert.Dialogs.BufferedDataGridView(); + this.commentColumnCheckBox = new System.Windows.Forms.CheckBox(); + this.label1 = new System.Windows.Forms.Label(); + this.contextMenuStrip1.SuspendLayout(); + this.splitContainer1.Panel1.SuspendLayout(); + this.splitContainer1.Panel2.SuspendLayout(); + this.splitContainer1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.bookmarkDataGridView)).BeginInit(); + this.SuspendLayout(); + // + // contextMenuStrip1 + // + this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { + this.deleteBookmarkssToolStripMenuItem, + this.removeCommentsToolStripMenuItem}); + this.contextMenuStrip1.Name = "contextMenuStrip1"; + this.contextMenuStrip1.Size = new System.Drawing.Size(186, 48); + // + // deleteBookmarkssToolStripMenuItem + // + 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.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.OnRemoveCommentsToolStripMenuItemClick); + // + // bookmarkTextBox + // + this.bookmarkTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.bookmarkTextBox.Location = new System.Drawing.Point(0, 20); + this.bookmarkTextBox.Multiline = true; + this.bookmarkTextBox.Name = "bookmarkTextBox"; + 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.OnBookmarkTextBoxTextChanged); + // + // splitContainer1 + // + this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; + this.splitContainer1.Location = new System.Drawing.Point(0, 0); + this.splitContainer1.Name = "splitContainer1"; + // + // splitContainer1.Panel1 + // + this.splitContainer1.Panel1.Controls.Add(this.bookmarkDataGridView); + this.splitContainer1.Panel1MinSize = 40; + // + // splitContainer1.Panel2 + // + this.splitContainer1.Panel2.Controls.Add(this.commentColumnCheckBox); + this.splitContainer1.Panel2.Controls.Add(this.label1); + this.splitContainer1.Panel2.Controls.Add(this.bookmarkTextBox); + this.splitContainer1.Size = new System.Drawing.Size(717, 158); + this.splitContainer1.SplitterDistance = 517; + this.splitContainer1.TabIndex = 7; + // + // bookmarkDataGridView + // + this.bookmarkDataGridView.AllowUserToAddRows = false; + this.bookmarkDataGridView.AllowUserToDeleteRows = false; + this.bookmarkDataGridView.AllowUserToOrderColumns = true; + this.bookmarkDataGridView.AllowUserToResizeRows = false; + this.bookmarkDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; + this.bookmarkDataGridView.BorderStyle = System.Windows.Forms.BorderStyle.None; + this.bookmarkDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; + this.bookmarkDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.bookmarkDataGridView.ContextMenuStrip = this.contextMenuStrip1; + this.bookmarkDataGridView.Dock = System.Windows.Forms.DockStyle.Fill; + this.bookmarkDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; + this.bookmarkDataGridView.EditModeMenuStrip = null; + this.bookmarkDataGridView.Location = new System.Drawing.Point(0, 0); + this.bookmarkDataGridView.Margin = new System.Windows.Forms.Padding(0); + this.bookmarkDataGridView.Name = "bookmarkDataGridView"; + this.bookmarkDataGridView.PaintWithOverlays = false; + this.bookmarkDataGridView.ReadOnly = true; + this.bookmarkDataGridView.RowHeadersVisible = false; + this.bookmarkDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; + this.bookmarkDataGridView.Size = new System.Drawing.Size(517, 158); + this.bookmarkDataGridView.TabIndex = 0; + this.bookmarkDataGridView.VirtualMode = true; + 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 + // + this.commentColumnCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.commentColumnCheckBox.AutoSize = true; + this.commentColumnCheckBox.Location = new System.Drawing.Point(7, 138); + this.commentColumnCheckBox.Name = "commentColumnCheckBox"; + this.commentColumnCheckBox.Size = new System.Drawing.Size(136, 17); + this.commentColumnCheckBox.TabIndex = 8; + this.commentColumnCheckBox.Text = "Show comment column"; + this.commentColumnCheckBox.UseVisualStyleBackColor = true; + this.commentColumnCheckBox.CheckedChanged += new System.EventHandler(this.OnCommentColumnCheckBoxCheckedChanged); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(4, 4); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(104, 13); + this.label1.TabIndex = 7; + this.label1.Text = "Bookmark comment:"; + // + // BookmarkWindow + // + this.ClientSize = new System.Drawing.Size(717, 158); + this.ControlBox = false; + this.Controls.Add(this.splitContainer1); + this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)(((((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft) + | WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight) + | WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop) + | WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom))); + this.DoubleBuffered = true; + this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "BookmarkWindow"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.Text = "Bookmarks"; + this.ClientSizeChanged += new System.EventHandler(this.BookmarkWindow_ClientSizeChanged); + this.SizeChanged += new System.EventHandler(this.OnBookmarkWindowSizeChanged); + this.contextMenuStrip1.ResumeLayout(false); + this.splitContainer1.Panel1.ResumeLayout(false); + this.splitContainer1.Panel2.ResumeLayout(false); + this.splitContainer1.Panel2.PerformLayout(); + this.splitContainer1.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.bookmarkDataGridView)).EndInit(); + this.ResumeLayout(false); +} + +#endregion + +private BufferedDataGridView bookmarkDataGridView; +private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; +private System.Windows.Forms.ToolStripMenuItem deleteBookmarkssToolStripMenuItem; +private System.Windows.Forms.TextBox bookmarkTextBox; +private System.Windows.Forms.SplitContainer splitContainer1; +private System.Windows.Forms.Label label1; +private System.Windows.Forms.ToolStripMenuItem removeCommentsToolStripMenuItem; +private System.Windows.Forms.CheckBox commentColumnCheckBox; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/BookmarkWindow.cs b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs new file mode 100644 index 00000000..6b08cef7 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.cs @@ -0,0 +1,610 @@ +using System.Runtime.Versioning; + +using LogExpert.Core.Config; +using LogExpert.Core.Entities; +using LogExpert.Core.Enums; +using LogExpert.Core.Interface; +using LogExpert.UI.Entities; +using LogExpert.UI.Interface; + +using NLog; + +using WeifenLuo.WinFormsUI.Docking; + +namespace LogExpert.Dialogs; + +//TODO can be moved to Logexpert.UI if the PaintHelper has been refactored +[SupportedOSPlatform("windows")] +internal partial class BookmarkWindow : DockContent, ISharedToolWindow, IBookmarkView +{ + #region Fields + + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + private readonly object paintLock = new(); + + private IBookmarkData _bookmarkData; + private ILogPaintContextUI _logPaintContext; + private ILogView _logView; + + #endregion + + #region cTor + + public BookmarkWindow () + { + InitializeComponent(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + bookmarkDataGridView.CellValueNeeded += OnBoomarkDataGridViewCellValueNeeded; + bookmarkDataGridView.CellPainting += OnBoomarkDataGridViewCellPainting; + } + + #endregion + + #region Properties + + public bool LineColumnVisible + { + set => bookmarkDataGridView.Columns[2].Visible = value; + } + + public bool ShowBookmarkCommentColumn + { + get => commentColumnCheckBox.Checked; + set + { + commentColumnCheckBox.Checked = value; + ShowCommentColumn(value); + } + } + + #endregion + + #region Public methods + + public void SetColumnizer (ILogLineColumnizer columnizer) + { + PaintHelper.SetColumnizer(columnizer, bookmarkDataGridView); + + if (bookmarkDataGridView.ColumnCount > 0) + { + bookmarkDataGridView.Columns[0].Width = 20; + } + + 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(); + } + + /// + /// Called from LogWindow after reloading and when double clicking a header divider. + /// + public void ResizeColumns () + { + // this.bookmarkDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + for (var i = 2; i < bookmarkDataGridView.ColumnCount; ++i) + { + bookmarkDataGridView.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.DisplayedCells); + } + } + + public void UpdateView () + { + bookmarkDataGridView.RowCount = _bookmarkData?.Bookmarks.Count ?? 0; + ResizeColumns(); + bookmarkDataGridView.Refresh(); + } + + /// + /// Called from LogWindow if the bookmark text was changed via popup window + /// + /// + public void BookmarkTextChanged (Bookmark bookmark) + { + var rowIndex = bookmarkDataGridView.CurrentCellAddress.Y; + + if (rowIndex == -1) + { + return; + } + + if (_bookmarkData.Bookmarks[rowIndex] == bookmark) + { + bookmarkTextBox.Text = bookmark.Text; + } + + bookmarkDataGridView.Refresh(); + } + + public void SelectBookmark (int lineNum) + { + if (_bookmarkData.IsBookmarkAtLine(lineNum)) + { + 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); + bookmarkDataGridView.CurrentCell = bookmarkDataGridView.Rows[row].Cells[0]; + } + } + + public void SetBookmarkData (IBookmarkData bookmarkData) + { + _bookmarkData = bookmarkData; + bookmarkDataGridView.RowCount = bookmarkData?.Bookmarks.Count ?? 0; + HideIfNeeded(); + } + + public void PreferencesChanged (string fontName, float fontSize, bool setLastColumnWidth, int lastColumnWidth, SettingsFlags flags) + { + if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) + { + SetFont(fontName, fontSize); + if (bookmarkDataGridView.Columns.Count > 1 && setLastColumnWidth) + { + bookmarkDataGridView.Columns[bookmarkDataGridView.Columns.Count - 1].MinimumWidth = lastColumnWidth; + } + + PaintHelper.ApplyDataGridViewPrefs(bookmarkDataGridView, setLastColumnWidth, lastColumnWidth); + } + } + + public void SetCurrentFile (IFileViewContext ctx) + { + if (ctx != null) + { + _logger.Debug($"Current file changed to {ctx.LogView.FileName}"); + lock (paintLock) + { + _logView = ctx.LogView; + _logPaintContext = (ILogPaintContextUI)ctx.LogPaintContext; + } + + SetColumnizer(ctx.LogView.CurrentColumnizer); + } + else + { + _logView = null; + _logPaintContext = null; + } + + UpdateView(); + } + + public void FileChanged () + { + // nothing to do + } + + #endregion + + #region Overrides + + protected override string GetPersistString () + { + return WindowTypes.BookmarkWindow.ToString(); + } + + protected override void OnPaint (PaintEventArgs e) + { + if (!splitContainer1.Visible) + { + e.Graphics.FillRectangle(SystemBrushes.ControlLight, ClientRectangle); + + StringFormat sf = new() + { + Alignment = StringAlignment.Center, + LineAlignment = StringAlignment.Center + }; + + e.Graphics.DrawString("No bookmarks in current file", SystemFonts.DialogFont, SystemBrushes.WindowText, ClientRectangle, sf); + } + else + { + base.OnPaint(e); + } + } + + #endregion + + #region Private Methods + + private void SetFont (string fontName, float fontSize) + { + Font font = new(new FontFamily(fontName), fontSize); + bookmarkDataGridView.DefaultCellStyle.Font = font; + bookmarkDataGridView.RowTemplate.Height = font.Height + 4; + bookmarkDataGridView.Refresh(); + } + + private void CommentPainting (BufferedDataGridView gridView, DataGridViewCellPaintingEventArgs e) + { + 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 = Color.White; + e.PaintBackground(e.CellBounds, false); + } + + e.PaintContent(e.CellBounds); + } + + private void DeleteSelectedBookmarks () + { + List lineNumList = []; + foreach (DataGridViewRow row in bookmarkDataGridView.SelectedRows) + { + if (row.Index != -1) + { + lineNumList.Add(_bookmarkData.Bookmarks[row.Index].LineNum); + } + } + + _logView?.DeleteBookmarks(lineNumList); + } + + private static void InvalidateCurrentRow (BufferedDataGridView gridView) + { + if (gridView.CurrentCellAddress.Y > -1) + { + gridView.InvalidateRow(gridView.CurrentCellAddress.Y); + } + } + + private void CurrentRowChanged (int rowIndex) + { + if (rowIndex == -1) + { + // multiple selection or no selection at all + bookmarkTextBox.Enabled = false; + + // disable the control first so that changes made to it won't propagate to the bookmark item + bookmarkTextBox.Text = string.Empty; + } + else + { + bookmarkTextBox.Text = _bookmarkData.Bookmarks[rowIndex].Text; + bookmarkTextBox.Enabled = true; + } + } + + private void ShowCommentColumn (bool show) + { + bookmarkDataGridView.Columns[1].Visible = show; + } + + private void HideIfNeeded () + { + splitContainer1.Visible = bookmarkDataGridView.RowCount > 0; + } + + #endregion + + #region Events handler + + private void OnBoomarkDataGridViewCellPainting (object sender, DataGridViewCellPaintingEventArgs e) + { + if (_bookmarkData == null) + { + return; + } + + lock (paintLock) + { + try + { + if (e.RowIndex < 0 || e.ColumnIndex < 0 || _bookmarkData.Bookmarks.Count <= e.RowIndex) + { + e.Handled = false; + return; + } + + var lineNum = _bookmarkData.Bookmarks[e.RowIndex].LineNum; + + // if (e.ColumnIndex == 1) + // { + // CommentPainting(this.bookmarkDataGridView, lineNum, e); + // } + //{ + // else + PaintHelper.CellPainting(_logPaintContext, bookmarkDataGridView.Focused, lineNum, e.ColumnIndex, e); + //} + } + catch (Exception ex) + { + _logger.Error(ex); + } + } + } + + private void OnBoomarkDataGridViewCellValueNeeded (object sender, DataGridViewCellValueEventArgs e) + { + if (_bookmarkData == null) + { + return; + } + + if (e.RowIndex < 0 || e.ColumnIndex < 0 || _bookmarkData.Bookmarks.Count <= e.RowIndex) + { + e.Value = string.Empty; + return; + } + + var bookmarkForLine = _bookmarkData.Bookmarks[e.RowIndex]; + var lineNum = bookmarkForLine.LineNum; + if (e.ColumnIndex == 1) + { + e.Value = bookmarkForLine.Text?.Replace('\n', ' ').Replace('\r', ' '); + } + else + { + var columnIndex = e.ColumnIndex > 1 ? e.ColumnIndex - 1 : e.ColumnIndex; + e.Value = _logPaintContext.GetCellValue(lineNum, columnIndex); + } + } + + + private void OnBoomarkDataGridViewMouseDoubleClick (object sender, MouseEventArgs e) + { + // if (this.bookmarkDataGridView.CurrentRow != null) + // { + // int lineNum = this.BookmarkList.Values[this.bookmarkDataGridView.CurrentRow.Index].LineNum; + // this.logWindow.SelectLogLine(lineNum); + // } + } + + private void OnBoomarkDataGridViewColumnDividerDoubleClick (object sender, + DataGridViewColumnDividerDoubleClickEventArgs e) + { + e.Handled = true; + ResizeColumns(); + } + + private void OnBookmarkGridViewKeyDown (object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Enter) + { + if (bookmarkDataGridView.CurrentCellAddress.Y >= 0 && + bookmarkDataGridView.CurrentCellAddress.Y < _bookmarkData.Bookmarks.Count) + { + var lineNum = _bookmarkData.Bookmarks[bookmarkDataGridView.CurrentCellAddress.Y].LineNum; + _logView.SelectLogLine(lineNum); + } + + e.Handled = true; + } + + if (e.KeyCode == Keys.Delete && e.Modifiers == Keys.None) + { + DeleteSelectedBookmarks(); + } + + if (e.KeyCode == Keys.Tab) + { + if (bookmarkDataGridView.Focused) + { + bookmarkTextBox.Focus(); + e.Handled = true; + } + } + } + + private void OnBookmarkGridViewEnter (object sender, EventArgs e) + { + InvalidateCurrentRow(bookmarkDataGridView); + } + + private void OnBookmarkGridViewLeave (object sender, EventArgs e) + { + InvalidateCurrentRow(bookmarkDataGridView); + } + + private void OnDeleteBookmarksToolStripMenuItemClick (object sender, EventArgs e) + { + DeleteSelectedBookmarks(); + } + + private void OnBookmarkTextBoxTextChanged (object sender, EventArgs e) + { + if (!bookmarkTextBox.Enabled) + { + return; // ignore all changes done while the control is disabled + } + + var rowIndex = bookmarkDataGridView.CurrentCellAddress.Y; + if (rowIndex == -1) + { + return; + } + + if (_bookmarkData.Bookmarks.Count <= rowIndex) + { + return; + } + + var bookmark = _bookmarkData.Bookmarks[rowIndex]; + bookmark.Text = bookmarkTextBox.Text; + _logView?.RefreshLogView(); + } + + private void OnBookmarkDataGridViewSelectionChanged (object sender, EventArgs e) + { + if (bookmarkDataGridView.SelectedRows.Count != 1 + || bookmarkDataGridView.SelectedRows[0].Index >= _bookmarkData.Bookmarks.Count) + { + CurrentRowChanged(-1); + } + else + { + CurrentRowChanged(bookmarkDataGridView.SelectedRows[0].Index); + } + } + + private void OnBookmarkDataGridViewPreviewKeyDown (object sender, PreviewKeyDownEventArgs e) + { + if (e.KeyCode == Keys.Tab) + { + e.IsInputKey = true; + } + } + + private void OnBookmarkDataGridViewCellToolTipTextNeeded (object sender, + DataGridViewCellToolTipTextNeededEventArgs e) + { + if (e.ColumnIndex != 0 || e.RowIndex <= -1 || e.RowIndex >= _bookmarkData.Bookmarks.Count) + { + return; + } + + var bookmark = _bookmarkData.Bookmarks[e.RowIndex]; + if (!string.IsNullOrEmpty(bookmark.Text)) + { + e.ToolTipText = bookmark.Text; + return; + } + } + + 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) + { + var index = bookmarkDataGridView.CurrentRow.Index; + 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; + bookmarkDataGridView.RowCount = boomarkCount; + + if (index < boomarkCount) + { + bookmarkDataGridView.CurrentCell = bookmarkDataGridView.Rows[index].Cells[0]; + } + else + { + if (boomarkCount > 0) + { + bookmarkDataGridView.CurrentCell = + bookmarkDataGridView.Rows[boomarkCount - 1].Cells[0]; + } + } + + if (boomarkCount > index) + { + CurrentRowChanged(index); + } + else + { + if (boomarkCount > 0) + { + CurrentRowChanged(bookmarkDataGridView.RowCount - 1); + } + else + { + CurrentRowChanged(-1); + } + } + + return; + } + + if (bookmarkDataGridView.CurrentRow != null && e.RowIndex >= 0) + { + var lineNum = _bookmarkData.Bookmarks[bookmarkDataGridView.CurrentRow.Index].LineNum; + _logView.SelectAndEnsureVisible(lineNum, true); + } + } + + private void OnRemoveCommentsToolStripMenuItemClick (object sender, EventArgs e) + { + if (MessageBox.Show("Really remove bookmark comments for selected lines?", "LogExpert", MessageBoxButtons.YesNo) == DialogResult.Yes) + { + foreach (DataGridViewRow row in bookmarkDataGridView.SelectedRows) + { + if (row.Index != -1) + { + _bookmarkData.Bookmarks[row.Index].Text = string.Empty; + } + } + + bookmarkTextBox.Text = string.Empty; + bookmarkDataGridView.Refresh(); + _logView.RefreshLogView(); + } + } + + private void OnCommentColumnCheckBoxCheckedChanged (object sender, EventArgs e) + { + ShowCommentColumn(commentColumnCheckBox.Checked); + } + + private void BookmarkWindow_ClientSizeChanged (object sender, EventArgs e) + { + if (Width > 0 && Height > 0) + { + if (Width > Height) + { + splitContainer1.Orientation = Orientation.Vertical; + var distance = Width - 200; + splitContainer1.SplitterDistance = distance > splitContainer1.Panel1MinSize + ? distance + : splitContainer1.Panel1MinSize; + } + else + { + splitContainer1.Orientation = Orientation.Horizontal; + var distance = Height - 200; + splitContainer1.SplitterDistance = distance > splitContainer1.Panel1MinSize + ? distance + : splitContainer1.Panel1MinSize; + } + } + + if (!splitContainer1.Visible) + { + // redraw the "no bookmarks" display + Invalidate(); + } + } + + private void OnBookmarkDataGridViewRowsAdded (object sender, DataGridViewRowsAddedEventArgs e) + { + HideIfNeeded(); + } + + private void OnBookmarkDataGridViewRowsRemoved (object sender, DataGridViewRowsRemovedEventArgs e) + { + HideIfNeeded(); + } + + private void OnBookmarkWindowSizeChanged (object sender, EventArgs e) + { + // if (!this.splitContainer1.Visible) + // { + // // redraw the "no bookmarks" display + // Invalidate(); + // } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/BookmarkWindow.resx b/src/LogExpert.UI/Dialogs/BookmarkWindow.resx similarity index 98% rename from src/LogExpert/Dialogs/BookmarkWindow.resx rename to src/LogExpert.UI/Dialogs/BookmarkWindow.resx index 5815d62c..4963f92b 100644 --- a/src/LogExpert/Dialogs/BookmarkWindow.resx +++ b/src/LogExpert.UI/Dialogs/BookmarkWindow.resx @@ -1,151 +1,151 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - - - AAABAAEADg4AAAEACABABQAAFgAAACgAAAAOAAAAHAAAAAEACAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAA - AADrw3EA7MNxAP7+/gD01ZQA4q9LANmdKAD64asA1JERAPTUkwDi4+IA2Z4oAP39/QDw8O8A5ebmAPf4 - +ADz8/IA8fLyAOOvSwDr6ukA6enoAPDx8QD7+/wA9PTzAP79/QD+//4A9fb2AOKvSgDn5+YA4rBLAN/g - 3wD29vYA7e3tAPn5+QD7+vsA+/v7APf39wDr6+sA3t7dAO/v7gDa2tkA7OzsAOTk4wD8/PwAwcHBAC8v - LwB8fHwA////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA - AAAAAAAALy8vLy8vLywsLy8vLy8AAC0tLS0tLSwGBiwrLy8vAAAtLisrKywIAwMILC8vLwAALS4uLiwB - AAEBAAAsLy8AAC0uGC4sBBEsLBoEHCwvAAAtLhUCLiwsLi4sBQUKLAAALS4jIQsuLi4uKywHBywAAC0u - EBkgKgIuListLCwvAAAtLigMFg4iFy4rLS8vLwAALS4NEiYPHisrKy0vLy8AAC0uHSkTHxQtLS0tLy8v - AAAtLiclCRskLS4uLS8vLwAALS4uLi4uLi0uLS8vLy8AAC0tLS0tLS0tLS8vLy8vAAAAAAAAAAAAAAAA - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA== - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + + + AAABAAEADg4AAAEACABABQAAFgAAACgAAAAOAAAAHAAAAAEACAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAA + AADrw3EA7MNxAP7+/gD01ZQA4q9LANmdKAD64asA1JERAPTUkwDi4+IA2Z4oAP39/QDw8O8A5ebmAPf4 + +ADz8/IA8fLyAOOvSwDr6ukA6enoAPDx8QD7+/wA9PTzAP79/QD+//4A9fb2AOKvSgDn5+YA4rBLAN/g + 3wD29vYA7e3tAPn5+QD7+vsA+/v7APf39wDr6+sA3t7dAO/v7gDa2tkA7OzsAOTk4wD8/PwAwcHBAC8v + LwB8fHwA////AP///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA + AAAAAAAALy8vLy8vLywsLy8vLy8AAC0tLS0tLSwGBiwrLy8vAAAtLisrKywIAwMILC8vLwAALS4uLiwB + AAEBAAAsLy8AAC0uGC4sBBEsLBoEHCwvAAAtLhUCLiwsLi4sBQUKLAAALS4jIQsuLi4uKywHBywAAC0u + EBkgKgIuListLCwvAAAtLigMFg4iFy4rLS8vLwAALS4NEiYPHisrKy0vLy8AAC0uHSkTHxQtLS0tLy8v + AAAtLiclCRskLS4uLS8vLwAALS4uLi4uLi0uLS8vLy8AAC0tLS0tLS0tLS8vLy8vAAAAAAAAAAAAAAAA + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA== + + \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/ChooseIconDlg.Designer.cs b/src/LogExpert.UI/Dialogs/ChooseIconDlg.Designer.cs new file mode 100644 index 00000000..6700865c --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ChooseIconDlg.Designer.cs @@ -0,0 +1,124 @@ +namespace LogExpert.UI.Dialogs; + +partial class ChooseIconDlg +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ChooseIconDlg)); + this.iconListView = new System.Windows.Forms.ListView(); + this.iconFileLabel = new System.Windows.Forms.Label(); + this.buttonChooseIconFile = new System.Windows.Forms.Button(); + this.okButton = new System.Windows.Forms.Button(); + this.cancelButton = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // iconListView + // + this.iconListView.Alignment = System.Windows.Forms.ListViewAlignment.Left; + this.iconListView.AutoArrange = false; + this.iconListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; + this.iconListView.HideSelection = false; + this.iconListView.Location = new System.Drawing.Point(18, 63); + this.iconListView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.iconListView.MultiSelect = false; + this.iconListView.Name = "iconListView"; + this.iconListView.ShowGroups = false; + this.iconListView.Size = new System.Drawing.Size(529, 118); + this.iconListView.TabIndex = 0; + this.iconListView.UseCompatibleStateImageBehavior = false; + // + // iconFileLabel + // + this.iconFileLabel.Location = new System.Drawing.Point(18, 26); + this.iconFileLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + this.iconFileLabel.Name = "iconFileLabel"; + this.iconFileLabel.Size = new System.Drawing.Size(411, 35); + this.iconFileLabel.TabIndex = 1; + this.iconFileLabel.Text = "label1"; + // + // buttonChooseIconFile + // + this.buttonChooseIconFile.Location = new System.Drawing.Point(438, 18); + this.buttonChooseIconFile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.buttonChooseIconFile.Name = "buttonChooseIconFile"; + this.buttonChooseIconFile.Size = new System.Drawing.Size(112, 35); + this.buttonChooseIconFile.TabIndex = 2; + this.buttonChooseIconFile.Text = "Icon file..."; + this.buttonChooseIconFile.UseVisualStyleBackColor = true; + this.buttonChooseIconFile.Click += new System.EventHandler(this.OnButtonChooseIconFileClick); + // + // okButton + // + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okButton.Location = new System.Drawing.Point(316, 226); + this.okButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(112, 35); + this.okButton.TabIndex = 3; + this.okButton.Text = "OK"; + this.okButton.UseVisualStyleBackColor = true; + this.okButton.Click += new System.EventHandler(this.OnOkButtonClick); + // + // cancelButton + // + this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.cancelButton.Location = new System.Drawing.Point(440, 226); + this.cancelButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.cancelButton.Name = "cancelButton"; + this.cancelButton.Size = new System.Drawing.Size(112, 35); + this.cancelButton.TabIndex = 4; + this.cancelButton.Text = "Cancel"; + this.cancelButton.UseVisualStyleBackColor = true; + // + // ChooseIconDlg + // + this.ClientSize = new System.Drawing.Size(568, 278); + this.Controls.Add(this.cancelButton); + this.Controls.Add(this.okButton); + this.Controls.Add(this.buttonChooseIconFile); + this.Controls.Add(this.iconFileLabel); + this.Controls.Add(this.iconListView); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ChooseIconDlg"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Choose Icon"; + this.Load += new System.EventHandler(this.ChooseIconDlg_Load); + this.ResumeLayout(false); + +} + +#endregion + +private System.Windows.Forms.ListView iconListView; +private System.Windows.Forms.Label iconFileLabel; +private System.Windows.Forms.Button buttonChooseIconFile; +private System.Windows.Forms.Button okButton; +private System.Windows.Forms.Button cancelButton; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/ChooseIconDlg.cs b/src/LogExpert.UI/Dialogs/ChooseIconDlg.cs new file mode 100644 index 00000000..229f18e8 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ChooseIconDlg.cs @@ -0,0 +1,119 @@ +using LogExpert.UI.Extensions; +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class ChooseIconDlg : Form +{ + #region Fields + + #endregion + + #region cTor + + public ChooseIconDlg(string fileName) + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + FileName = fileName; + } + + #endregion + + #region Properties + + public string FileName { get; set; } + + public int IconIndex { get; set; } + + #endregion + + #region Private Methods + + private void FillIconList() + { + iconListView.Items.Clear(); + + Icon[,] icons = NativeMethods.ExtractIcons(FileName); + + if (icons == null) + { + return; + } + + ImageList imageList = new(); + + if (icons.GetLength(0) > 0) + { + imageList.ImageSize = icons[1, 0].Size; + iconListView.LargeImageList = imageList; + + for (var i = 0; i < icons.GetLength(1); ++i) + { + imageList.Images.Add(icons[1, i]); + ListViewItem item = new() + { + ImageIndex = i + }; + iconListView.Items.Add(item); + } + } + } + + private void DisposeIcons() + { + ImageList imageList = iconListView.LargeImageList; + iconListView.LargeImageList = null; + foreach (Image image in imageList.Images) + { + image.Dispose(); + } + } + + #endregion + + #region Events handler + + private void ChooseIconDlg_Load(object sender, EventArgs e) + { + FillIconList(); + iconFileLabel.Text = FileName; + } + + private void OnButtonChooseIconFileClick(object sender, EventArgs e) + { + OpenFileDialog dlg = new() + { + InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + }; + + if (string.IsNullOrEmpty(iconFileLabel.Text) == false) + { + FileInfo info = new(iconFileLabel.Text); + if (info.Directory != null && info.Directory.Exists) + { + dlg.InitialDirectory = info.DirectoryName; + } + } + + if (dlg.ShowDialog() == DialogResult.OK) + { + iconFileLabel.Text = dlg.FileName; + FileName = dlg.FileName; + FillIconList(); + } + } + + private void OnOkButtonClick(object sender, EventArgs e) + { + IconIndex = iconListView.SelectedIndices.Count > 0 ? iconListView.SelectedIndices[0] : -1; + + DisposeIcons(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ChooseIconDlg.resx b/src/LogExpert.UI/Dialogs/ChooseIconDlg.resx similarity index 98% rename from src/LogExpert/Dialogs/ChooseIconDlg.resx rename to src/LogExpert.UI/Dialogs/ChooseIconDlg.resx index 2de0ae4d..a43dafee 100644 --- a/src/LogExpert/Dialogs/ChooseIconDlg.resx +++ b/src/LogExpert.UI/Dialogs/ChooseIconDlg.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + 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/Dialogs/Eminus/Eminus.cs b/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs new file mode 100644 index 00000000..da5350c8 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/Eminus/Eminus.cs @@ -0,0 +1,304 @@ +using System.Net.Sockets; +using System.Runtime.Serialization; +using System.Runtime.Versioning; + +//using System.Windows.Forms; +using System.Xml; + +using Newtonsoft.Json; + +//TODO: This whole Eminus folder is not in use. Can be deleted? What is it? +//[assembly: SupportedOSPlatform("windows")] +namespace LogExpert.UI.Dialogs.Eminus; + +internal class Eminus : IContextMenuEntry, ILogExpertPluginConfigurator +{ + #region Fields + + private const string CFG_FILE_NAME = "eminus.json"; + private const string DOT = "."; + private const string DOUBLE_DOT = ":"; + private const string DISABLED = "_"; + + private EminusConfig _config = new(); + private EminusConfigDlg dlg; + private EminusConfig tmpConfig = new(); + + #endregion + + #region Properties + + public static string Text => "eminus"; + + #endregion + + #region Private Methods + + [SupportedOSPlatform("windows")] + private XmlDocument BuildParam (ILogLine line) + { + var fullLogLine = line.FullLine; + // no Java stacktrace but some special logging of our applications at work: + if (fullLogLine.Contains("Exception of type", StringComparison.CurrentCulture) || + fullLogLine.Contains("Nested:", StringComparison.CurrentCulture)) + { + var pos = fullLogLine.IndexOf("created in "); + + if (pos == -1) + { + return null; + } + + pos += "created in ".Length; + var endPos = fullLogLine.IndexOf(DOT, pos); + + if (endPos == -1) + { + return null; + } + + var className = fullLogLine[pos..endPos]; + pos = fullLogLine.IndexOf(DOUBLE_DOT, pos); + + if (pos == -1) + { + return null; + } + + var lineNum = fullLogLine[(pos + 1)..]; + XmlDocument doc = BuildXmlDocument(className, lineNum); + return doc; + } + + if (fullLogLine.Contains("at ", StringComparison.CurrentCulture)) + { + var str = fullLogLine.Trim(); + string className = null; + string lineNum = null; + var pos = str.IndexOf("at ") + 3; + str = str[pos..]; // remove 'at ' + var idx = str.IndexOfAny(['(', '$', '<']); + + if (idx != -1) + { + if (str[idx] == '$') + { + className = str[..idx]; + } + else + { + pos = str.LastIndexOf(DOT, idx); + if (pos == -1) + { + return null; + } + className = str[..pos]; + } + + idx = str.LastIndexOf(DOUBLE_DOT); + + if (idx == -1) + { + return null; + } + + pos = str.IndexOf(')', idx); + + if (pos == -1) + { + return null; + } + + lineNum = str.Substring(idx + 1, pos - idx - 1); + } + /* + * + + + + + + + */ + + XmlDocument doc = BuildXmlDocument(className, lineNum); + return doc; + } + return null; + } + + [SupportedOSPlatform("windows")] + private XmlDocument BuildXmlDocument (string className, string lineNum) + { + XmlDocument xmlDoc = new(); + xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", "yes"); + XmlElement rootElement = xmlDoc.CreateElement("eminus"); + xmlDoc.AppendChild(rootElement); + rootElement.SetAttribute("authKey", _config.Password); + + XmlElement loadElement = xmlDoc.CreateElement("loadclass"); + loadElement.SetAttribute("mode", "dialog"); + rootElement.AppendChild(loadElement); + + XmlElement elemClassName = xmlDoc.CreateElement("classname"); + XmlElement elemLineNum = xmlDoc.CreateElement("linenumber"); + elemClassName.InnerText = className; + elemLineNum.InnerText = lineNum; + loadElement.AppendChild(elemClassName); + loadElement.AppendChild(elemLineNum); + return xmlDoc; + } + + #endregion + + #region IContextMenuEntry Member + + public string GetMenuText (IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) + { + //not used + return string.Empty; + } + + [SupportedOSPlatform("windows")] + public string GetMenuText (int logLinesCount, ILogLineColumnizer columnizer, ILogLine logline) + { + return logLinesCount == 1 && BuildParam(logline) != null + ? "Load class in Eclipse" + : $"{DISABLED}Load class in Eclipse"; + } + + public void MenuSelected (IList logLines, ILogLineColumnizer columnizer, ILogExpertCallback callback) + { + //Not used + } + + [SupportedOSPlatform("windows")] + public void MenuSelected (int logLinesCount, ILogLineColumnizer columnizer, ILogLine logline) + { + if (logLinesCount != 1) + { + return; + } + + XmlDocument doc = BuildParam(logline); + + if (doc == null) + { + MessageBox.Show("Cannot parse Java stack trace line", "LogExpert"); + } + else + { + try + { + TcpClient client = new(_config.Host, _config.Port); + NetworkStream stream = client.GetStream(); + StreamWriter writer = new(stream); + doc.Save(writer); + writer.Flush(); + stream.Flush(); + writer.Close(); + stream.Close(500); + client.Close(); + } + catch (Exception e) + { + MessageBox.Show(e.Message, "LogExpert"); + } + } + } + + #endregion + + #region ILogExpertPluginConfigurator Member + + [SupportedOSPlatform("windows")] + public void LoadConfig (string configDir) + { + var configPath = configDir + CFG_FILE_NAME; + + FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + CFG_FILE_NAME); + + if (!File.Exists(configPath)) + { + _config = new EminusConfig(); + } + else + { + try + { + _config = JsonConvert.DeserializeObject(File.ReadAllText($"{fileInfo.FullName}")); + } + catch (SerializationException e) + { + MessageBox.Show(e.Message, "Deserialize"); + _config = new EminusConfig(); + } + } + } + + [SupportedOSPlatform("windows")] + public void SaveConfig (string configDir) + { + FileInfo fileInfo = new(configDir + Path.DirectorySeparatorChar + CFG_FILE_NAME); + + dlg?.ApplyChanges(); + + _config = tmpConfig.Clone(); + + using StreamWriter sw = new(fileInfo.Create()); + JsonSerializer serializer = new(); + serializer.Serialize(sw, _config); + } + + public bool HasEmbeddedForm () + { + return true; + } + + [SupportedOSPlatform("windows")] + public void ShowConfigForm (object panel) + { + dlg = new EminusConfigDlg(tmpConfig) + { + Parent = (Panel)panel + }; + dlg.Show(); + } + + /// + /// Implemented only for demonstration purposes. This function is called when the config button + /// is pressed (HasEmbeddedForm() must return false for this). + /// + /// + [SupportedOSPlatform("windows")] + public void ShowConfigDialog (object owner) + { + dlg = new EminusConfigDlg(tmpConfig) + { + TopLevel = true, + Owner = (Form)owner + }; + + dlg.ShowDialog(); + dlg.ApplyChanges(); + } + + [SupportedOSPlatform("windows")] + public void HideConfigForm () + { + if (dlg != null) + { + dlg.ApplyChanges(); + dlg.Hide(); + dlg.Dispose(); + dlg = null; + } + } + + public void StartConfig () + { + tmpConfig = _config.Clone(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/Eminus/EminusConfig.cs b/src/LogExpert.UI/Dialogs/Eminus/EminusConfig.cs new file mode 100644 index 00000000..12bda818 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/Eminus/EminusConfig.cs @@ -0,0 +1,26 @@ +namespace LogExpert.UI.Dialogs.Eminus; + +[Serializable] +internal class EminusConfig +{ + public string Host { get; set; } = "127.0.0.1"; + + public string Password { get; set; } = string.Empty; + + public int Port { get; set; } = 12345; + + #region Public methods + + public EminusConfig Clone () + { + EminusConfig config = new() + { + Host = Host, + Port = Port, + Password = Password + }; + return config; + } + + #endregion +} \ No newline at end of file diff --git a/src/DefaultPlugins/EminusConfigDlg.Designer.cs b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.Designer.cs similarity index 97% rename from src/DefaultPlugins/EminusConfigDlg.Designer.cs rename to src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.Designer.cs index 56617b77..267dc40d 100644 --- a/src/DefaultPlugins/EminusConfigDlg.Designer.cs +++ b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.Designer.cs @@ -1,135 +1,135 @@ -namespace LogExpert -{ - partial class EminusConfigDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EminusConfigDlg)); - this.hostTextBox = new System.Windows.Forms.TextBox(); - this.passwordTextBox = new System.Windows.Forms.TextBox(); - this.label1 = new System.Windows.Forms.Label(); - this.label2 = new System.Windows.Forms.Label(); - this.label3 = new System.Windows.Forms.Label(); - this.label4 = new System.Windows.Forms.Label(); - this.portTextBox = new System.Windows.Forms.MaskedTextBox(); - this.SuspendLayout(); - // - // hostTextBox - // - this.hostTextBox.Location = new System.Drawing.Point(76, 69); - this.hostTextBox.Name = "hostTextBox"; - this.hostTextBox.Size = new System.Drawing.Size(175, 20); - this.hostTextBox.TabIndex = 0; - // - // passwordTextBox - // - this.passwordTextBox.Location = new System.Drawing.Point(76, 122); - this.passwordTextBox.Name = "passwordTextBox"; - this.passwordTextBox.Size = new System.Drawing.Size(175, 20); - this.passwordTextBox.TabIndex = 2; - this.passwordTextBox.UseSystemPasswordChar = true; - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(17, 72); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(29, 13); - this.label1.TabIndex = 5; - this.label1.Text = "Host"; - // - // label2 - // - this.label2.AutoSize = true; - this.label2.Location = new System.Drawing.Point(17, 99); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(26, 13); - this.label2.TabIndex = 6; - this.label2.Text = "Port"; - // - // label3 - // - this.label3.AutoSize = true; - this.label3.Location = new System.Drawing.Point(17, 126); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(53, 13); - this.label3.TabIndex = 7; - this.label3.Text = "Password"; - // - // label4 - // - this.label4.Location = new System.Drawing.Point(13, 13); - this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(276, 41); - this.label4.TabIndex = 8; - this.label4.Text = "Enter the host and the port where the Eclipse plugin is listening to. If a passwo" + - "rd is configured, enter the password too."; - // - // portTextBox - // - this.portTextBox.Location = new System.Drawing.Point(76, 96); - this.portTextBox.Mask = "99999"; - this.portTextBox.Name = "portTextBox"; - this.portTextBox.Size = new System.Drawing.Size(100, 20); - this.portTextBox.TabIndex = 1; - // - // EminusConfigDlg - // - this.ClientSize = new System.Drawing.Size(295, 187); - this.ControlBox = false; - this.Controls.Add(this.portTextBox); - this.Controls.Add(this.label4); - this.Controls.Add(this.label3); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Controls.Add(this.passwordTextBox); - this.Controls.Add(this.hostTextBox); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "EminusConfigDlg"; - this.ShowIcon = false; - this.ShowInTaskbar = false; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Eclipse Remote Navigation"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.TextBox hostTextBox; - private System.Windows.Forms.TextBox passwordTextBox; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.Label label4; - private System.Windows.Forms.MaskedTextBox portTextBox; - } +namespace LogExpert +{ + partial class EminusConfigDlg + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(EminusConfigDlg)); + this.hostTextBox = new System.Windows.Forms.TextBox(); + this.passwordTextBox = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.label2 = new System.Windows.Forms.Label(); + this.label3 = new System.Windows.Forms.Label(); + this.label4 = new System.Windows.Forms.Label(); + this.portTextBox = new System.Windows.Forms.MaskedTextBox(); + this.SuspendLayout(); + // + // hostTextBox + // + this.hostTextBox.Location = new System.Drawing.Point(76, 69); + this.hostTextBox.Name = "hostTextBox"; + this.hostTextBox.Size = new System.Drawing.Size(175, 20); + this.hostTextBox.TabIndex = 0; + // + // passwordTextBox + // + this.passwordTextBox.Location = new System.Drawing.Point(76, 122); + this.passwordTextBox.Name = "passwordTextBox"; + this.passwordTextBox.Size = new System.Drawing.Size(175, 20); + this.passwordTextBox.TabIndex = 2; + this.passwordTextBox.UseSystemPasswordChar = true; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(17, 72); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(29, 13); + this.label1.TabIndex = 5; + this.label1.Text = "Host"; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(17, 99); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(26, 13); + this.label2.TabIndex = 6; + this.label2.Text = "Port"; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(17, 126); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(53, 13); + this.label3.TabIndex = 7; + this.label3.Text = "Password"; + // + // label4 + // + this.label4.Location = new System.Drawing.Point(13, 13); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(276, 41); + this.label4.TabIndex = 8; + this.label4.Text = "Enter the host and the port where the Eclipse plugin is listening to. If a passwo" + + "rd is configured, enter the password too."; + // + // portTextBox + // + this.portTextBox.Location = new System.Drawing.Point(76, 96); + this.portTextBox.Mask = "99999"; + this.portTextBox.Name = "portTextBox"; + this.portTextBox.Size = new System.Drawing.Size(100, 20); + this.portTextBox.TabIndex = 1; + // + // EminusConfigDlg + // + this.ClientSize = new System.Drawing.Size(295, 187); + this.ControlBox = false; + this.Controls.Add(this.portTextBox); + this.Controls.Add(this.label4); + this.Controls.Add(this.label3); + this.Controls.Add(this.label2); + this.Controls.Add(this.label1); + this.Controls.Add(this.passwordTextBox); + this.Controls.Add(this.hostTextBox); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "EminusConfigDlg"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Eclipse Remote Navigation"; + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.TextBox hostTextBox; + private System.Windows.Forms.TextBox passwordTextBox; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.MaskedTextBox portTextBox; + } } \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.cs b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.cs new file mode 100644 index 00000000..841a340a --- /dev/null +++ b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.cs @@ -0,0 +1,61 @@ +using System.Runtime.Versioning; + +using LogExpert.UI.Dialogs.Eminus; + +namespace LogExpert; + +[SupportedOSPlatform("windows")] +internal partial class EminusConfigDlg : Form +{ + #region Fields + + #endregion + + #region cTor + + public EminusConfigDlg (EminusConfig config) + { + SuspendLayout(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + InitializeComponent(); + + TopLevel = false; + Config = config; + + hostTextBox.Text = config.Host; + portTextBox.Text = string.Empty + config.Port; + passwordTextBox.Text = config.Password; + + ResumeLayout(); + } + + #endregion + + #region Properties + + public EminusConfig Config { get; set; } + + #endregion + + #region Public methods + + public void ApplyChanges () + { + Config.Host = hostTextBox.Text; + try + { + Config.Port = short.Parse(portTextBox.Text); + } + catch (FormatException) + { + Config.Port = 0; + } + + Config.Password = passwordTextBox.Text; + } + + #endregion +} \ No newline at end of file diff --git a/src/DefaultPlugins/EminusConfigDlg.resx b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.resx similarity index 98% rename from src/DefaultPlugins/EminusConfigDlg.resx rename to src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.resx index 20cf2a6f..e97451d5 100644 --- a/src/DefaultPlugins/EminusConfigDlg.resx +++ b/src/LogExpert.UI/Dialogs/Eminus/EminusConfigDlg.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + + + 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/Dialogs/ExceptionWindow.Designer.cs b/src/LogExpert.UI/Dialogs/ExceptionWindow.Designer.cs new file mode 100644 index 00000000..7c7b4c72 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ExceptionWindow.Designer.cs @@ -0,0 +1,107 @@ +namespace LogExpert.UI.Dialogs; + +partial class ExceptionWindow +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExceptionWindow)); + this.stackTraceTextBox = new System.Windows.Forms.TextBox(); + this.label1 = new System.Windows.Forms.Label(); + this.okButton = new System.Windows.Forms.Button(); + this.copyButton = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // stackTraceTextBox + // + this.stackTraceTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) + | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.stackTraceTextBox.Location = new System.Drawing.Point(12, 42); + this.stackTraceTextBox.Multiline = true; + this.stackTraceTextBox.Name = "stackTraceTextBox"; + this.stackTraceTextBox.ReadOnly = true; + this.stackTraceTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; + this.stackTraceTextBox.Size = new System.Drawing.Size(439, 205); + this.stackTraceTextBox.TabIndex = 0; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(13, 13); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(310, 13); + this.label1.TabIndex = 1; + this.label1.Text = "An unhandled error has occured. Please report to the developer."; + // + // okButton + // + this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okButton.Location = new System.Drawing.Point(376, 265); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(75, 23); + this.okButton.TabIndex = 2; + this.okButton.Text = "Close"; + this.okButton.UseVisualStyleBackColor = true; + // + // copyButton + // + this.copyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.copyButton.Location = new System.Drawing.Point(12, 265); + this.copyButton.Name = "copyButton"; + this.copyButton.Size = new System.Drawing.Size(117, 23); + this.copyButton.TabIndex = 4; + this.copyButton.Text = "Copy to clipboard"; + this.copyButton.UseVisualStyleBackColor = true; + this.copyButton.Click += new System.EventHandler(this.copyButton_Click); + // + // ExceptionWindow + // + this.CancelButton = this.okButton; + this.ClientSize = new System.Drawing.Size(464, 300); + this.Controls.Add(this.copyButton); + this.Controls.Add(this.okButton); + this.Controls.Add(this.label1); + this.Controls.Add(this.stackTraceTextBox); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ExceptionWindow"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "LogExpert Error"; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.TextBox stackTraceTextBox; +private System.Windows.Forms.Label label1; +private System.Windows.Forms.Button okButton; + private System.Windows.Forms.Button copyButton; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/ExceptionWindow.cs b/src/LogExpert.UI/Dialogs/ExceptionWindow.cs new file mode 100644 index 00000000..486f68b0 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ExceptionWindow.cs @@ -0,0 +1,53 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +public partial class ExceptionWindow : Form +{ + #region Fields + + private readonly string _errorText; + + private readonly string _stackTrace; + + #endregion + + #region cTor + + public ExceptionWindow (string errorText, string stackTrace) + { + SuspendLayout(); + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + _errorText = errorText; + _stackTrace = stackTrace; + + stackTraceTextBox.Text = _errorText + @"\n\n" + _stackTrace; + stackTraceTextBox.Select(0, 0); + ResumeLayout(); + } + + #endregion + + #region Private Methods + + private void CopyToClipboard () + { + Clipboard.SetText(_errorText + @"\n\n" + _stackTrace); + } + + #endregion + + #region Events handler + + private void copyButton_Click (object sender, EventArgs e) + { + CopyToClipboard(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ExceptionWindow.resx b/src/LogExpert.UI/Dialogs/ExceptionWindow.resx similarity index 98% rename from src/LogExpert/Dialogs/ExceptionWindow.resx rename to src/LogExpert.UI/Dialogs/ExceptionWindow.resx index 2de0ae4d..a43dafee 100644 --- a/src/LogExpert/Dialogs/ExceptionWindow.resx +++ b/src/LogExpert.UI/Dialogs/ExceptionWindow.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + 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/Dialogs/FilterColumnChooser.Designer.cs b/src/LogExpert.UI/Dialogs/FilterColumnChooser.Designer.cs new file mode 100644 index 00000000..484f8987 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/FilterColumnChooser.Designer.cs @@ -0,0 +1,217 @@ +namespace LogExpert.UI.Dialogs; + +partial class FilterColumnChooser +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FilterColumnChooser)); + this.columnListBox = new System.Windows.Forms.CheckedListBox(); + this.buttonOk = new System.Windows.Forms.Button(); + this.toolTipEmptyColumnNoHit = new System.Windows.Forms.ToolTip(this.components); + this.emptyColumnNoHitRadioButton = new System.Windows.Forms.RadioButton(); + this.toolTipListBox = new System.Windows.Forms.ToolTip(this.components); + this.checkBoxExactMatch = new System.Windows.Forms.CheckBox(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.emptyColumnUsePrevRadioButton = new System.Windows.Forms.RadioButton(); + this.emptyColumnHitRadioButton = new System.Windows.Forms.RadioButton(); + this.groupBoxExectMatch = new System.Windows.Forms.GroupBox(); + this.toolTipSearchHit = new System.Windows.Forms.ToolTip(this.components); + this.toolTipPrevContent = new System.Windows.Forms.ToolTip(this.components); + this.toolTipExactMatch = new System.Windows.Forms.ToolTip(this.components); + this.buttonCancel = new System.Windows.Forms.Button(); + this.groupBox1.SuspendLayout(); + this.groupBoxExectMatch.SuspendLayout(); + this.SuspendLayout(); + // + // columnListBox + // + this.columnListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.columnListBox.CheckOnClick = true; + this.columnListBox.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.columnListBox.FormattingEnabled = true; + this.columnListBox.Location = new System.Drawing.Point(3, 3); + this.columnListBox.Name = "columnListBox"; + this.columnListBox.Size = new System.Drawing.Size(177, 119); + this.columnListBox.TabIndex = 0; + this.toolTipListBox.SetToolTip(this.columnListBox, "Choose one ore more columns to restrict the search operations to the selected col" + + "umns."); + // + // buttonOk + // + this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(3, 309); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 2; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnOkButtonClick); + // + // toolTipEmptyColumnNoHit + // + this.toolTipEmptyColumnNoHit.ToolTipTitle = "Empty column"; + // + // emptyColumnNoHitRadioButton + // + this.emptyColumnNoHitRadioButton.AutoSize = true; + this.emptyColumnNoHitRadioButton.Location = new System.Drawing.Point(6, 21); + this.emptyColumnNoHitRadioButton.Name = "emptyColumnNoHitRadioButton"; + this.emptyColumnNoHitRadioButton.Size = new System.Drawing.Size(75, 24); + this.emptyColumnNoHitRadioButton.TabIndex = 0; + this.emptyColumnNoHitRadioButton.TabStop = true; + this.emptyColumnNoHitRadioButton.Text = "No hit"; + this.toolTipEmptyColumnNoHit.SetToolTip(this.emptyColumnNoHitRadioButton, "No search hit on empty columns"); + this.emptyColumnNoHitRadioButton.UseVisualStyleBackColor = true; + // + // toolTipListBox + // + this.toolTipListBox.ToolTipTitle = "Columns"; + // + // checkBoxExactMatch + // + this.checkBoxExactMatch.AutoSize = true; + this.checkBoxExactMatch.Location = new System.Drawing.Point(9, 11); + this.checkBoxExactMatch.Name = "checkBoxExactMatch"; + this.checkBoxExactMatch.Size = new System.Drawing.Size(123, 24); + this.checkBoxExactMatch.TabIndex = 4; + this.checkBoxExactMatch.Text = "Exact match"; + this.toolTipExactMatch.SetToolTip(this.checkBoxExactMatch, "If selected, the search string must match exactly (no substring search)"); + this.checkBoxExactMatch.UseVisualStyleBackColor = true; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.emptyColumnUsePrevRadioButton); + this.groupBox1.Controls.Add(this.emptyColumnHitRadioButton); + this.groupBox1.Controls.Add(this.emptyColumnNoHitRadioButton); + this.groupBox1.Location = new System.Drawing.Point(3, 177); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(177, 108); + this.groupBox1.TabIndex = 5; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "On empty columns"; + // + // emptyColumnUsePrevRadioButton + // + this.emptyColumnUsePrevRadioButton.AutoSize = true; + this.emptyColumnUsePrevRadioButton.Location = new System.Drawing.Point(6, 76); + this.emptyColumnUsePrevRadioButton.Name = "emptyColumnUsePrevRadioButton"; + this.emptyColumnUsePrevRadioButton.Size = new System.Drawing.Size(155, 24); + this.emptyColumnUsePrevRadioButton.TabIndex = 2; + this.emptyColumnUsePrevRadioButton.TabStop = true; + this.emptyColumnUsePrevRadioButton.Text = "Use prev content"; + this.toolTipPrevContent.SetToolTip(this.emptyColumnUsePrevRadioButton, "An empty column will be a search hit if the previous non-empty column was a searc" + + "h hit"); + this.emptyColumnUsePrevRadioButton.UseVisualStyleBackColor = true; + // + // emptyColumnHitRadioButton + // + this.emptyColumnHitRadioButton.AutoSize = true; + this.emptyColumnHitRadioButton.Location = new System.Drawing.Point(6, 49); + this.emptyColumnHitRadioButton.Name = "emptyColumnHitRadioButton"; + this.emptyColumnHitRadioButton.Size = new System.Drawing.Size(106, 24); + this.emptyColumnHitRadioButton.TabIndex = 1; + this.emptyColumnHitRadioButton.TabStop = true; + this.emptyColumnHitRadioButton.Text = "Search hit"; + this.toolTipSearchHit.SetToolTip(this.emptyColumnHitRadioButton, "An empty column will always be a search hit"); + this.emptyColumnHitRadioButton.UseVisualStyleBackColor = true; + // + // groupBoxExectMatch + // + this.groupBoxExectMatch.Controls.Add(this.checkBoxExactMatch); + this.groupBoxExectMatch.Location = new System.Drawing.Point(3, 130); + this.groupBoxExectMatch.Name = "groupBoxExectMatch"; + this.groupBoxExectMatch.Size = new System.Drawing.Size(177, 41); + this.groupBoxExectMatch.TabIndex = 6; + this.groupBoxExectMatch.TabStop = false; + // + // toolTipSearchHit + // + this.toolTipSearchHit.ToolTipTitle = "Empty column"; + // + // toolTipPrevContent + // + this.toolTipPrevContent.ToolTipTitle = "Empty column"; + // + // toolTipExactMatch + // + this.toolTipExactMatch.ToolTipTitle = "Exact match"; + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(104, 309); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 7; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // FilterColumnChooser + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(184, 335); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.groupBoxExectMatch); + this.Controls.Add(this.groupBox1); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.columnListBox); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.Name = "FilterColumnChooser"; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Columns"; + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.groupBoxExectMatch.ResumeLayout(false); + this.groupBoxExectMatch.PerformLayout(); + this.ResumeLayout(false); + +} + +#endregion + +private System.Windows.Forms.CheckedListBox columnListBox; +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.ToolTip toolTipEmptyColumnNoHit; +private System.Windows.Forms.ToolTip toolTipListBox; +private System.Windows.Forms.CheckBox checkBoxExactMatch; +private System.Windows.Forms.GroupBox groupBox1; +private System.Windows.Forms.RadioButton emptyColumnUsePrevRadioButton; +private System.Windows.Forms.RadioButton emptyColumnHitRadioButton; +private System.Windows.Forms.RadioButton emptyColumnNoHitRadioButton; +private System.Windows.Forms.GroupBox groupBoxExectMatch; +private System.Windows.Forms.ToolTip toolTipExactMatch; +private System.Windows.Forms.ToolTip toolTipSearchHit; +private System.Windows.Forms.ToolTip toolTipPrevContent; +private System.Windows.Forms.Button buttonCancel; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/FilterColumnChooser.cs b/src/LogExpert.UI/Dialogs/FilterColumnChooser.cs new file mode 100644 index 00000000..1aea2b15 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/FilterColumnChooser.cs @@ -0,0 +1,74 @@ +using LogExpert.Core.Classes.Filter; + +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class FilterColumnChooser : Form +{ + #region Fields + + private readonly ILogLineColumnizer _columnizer; + private readonly FilterParams _filterParams; + + #endregion + + #region cTor + + //TODO: add Suspend and ResumeLayout() + public FilterColumnChooser(FilterParams filterParams) + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + columnListBox.ItemHeight = columnListBox.Font.Height; + + _columnizer = filterParams.CurrentColumnizer; + _filterParams = filterParams; + + Init(); + } + + #endregion + + #region Private Methods + + private void Init() + { + var count = _columnizer.GetColumnCount(); + var names = _columnizer.GetColumnNames(); + + for (var i = 0; i < count; ++i) + { + columnListBox.Items.Add(names[i], _filterParams.ColumnList.Contains(i)); + } + + emptyColumnUsePrevRadioButton.Checked = _filterParams.EmptyColumnUsePrev; + emptyColumnHitRadioButton.Checked = _filterParams.EmptyColumnHit; + emptyColumnNoHitRadioButton.Checked = _filterParams.EmptyColumnHit == false && _filterParams.EmptyColumnUsePrev == false; + checkBoxExactMatch.Checked = _filterParams.ExactColumnMatch; + } + + #endregion + + #region Events handler + + private void OnOkButtonClick(object sender, EventArgs e) + { + _filterParams.ColumnList.Clear(); + + foreach (int colNum in columnListBox.CheckedIndices) + { + _filterParams.ColumnList.Add(colNum); + } + + _filterParams.EmptyColumnUsePrev = emptyColumnUsePrevRadioButton.Checked; + _filterParams.EmptyColumnHit = emptyColumnHitRadioButton.Checked; + _filterParams.ExactColumnMatch = checkBoxExactMatch.Checked; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/FilterColumnChooser.resx b/src/LogExpert.UI/Dialogs/FilterColumnChooser.resx similarity index 98% rename from src/LogExpert/Dialogs/FilterColumnChooser.resx rename to src/LogExpert.UI/Dialogs/FilterColumnChooser.resx index bfab700f..a80b2c8f 100644 --- a/src/LogExpert/Dialogs/FilterColumnChooser.resx +++ b/src/LogExpert.UI/Dialogs/FilterColumnChooser.resx @@ -1,149 +1,149 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - 184, 17 - - - 17, 17 - - - 611, 17 - - - 454, 17 - - - 312, 17 - - - 71 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 184, 17 + + + 17, 17 + + + 611, 17 + + + 454, 17 + + + 312, 17 + + + 71 + + + + + 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/Dialogs/GotoLineDialog.Designer.cs b/src/LogExpert.UI/Dialogs/GotoLineDialog.Designer.cs new file mode 100644 index 00000000..799a964e --- /dev/null +++ b/src/LogExpert.UI/Dialogs/GotoLineDialog.Designer.cs @@ -0,0 +1,107 @@ +namespace LogExpert.UI.Dialogs; + +partial class GotoLineDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.labelLineNumber = new System.Windows.Forms.Label(); + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.lineNumberTextBox = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // labelLineNumber + // + this.labelLineNumber.AutoSize = true; + this.labelLineNumber.Location = new System.Drawing.Point(12, 30); + this.labelLineNumber.Name = "labelLineNumber"; + this.labelLineNumber.Size = new System.Drawing.Size(101, 20); + this.labelLineNumber.TabIndex = 0; + this.labelLineNumber.Text = "Line number:"; + // + // buttonOk + // + this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); + this.buttonOk.AutoSize = true; + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(15, 90); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 30); + this.buttonOk.TabIndex = 2; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.okButton_Click); + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.AutoSize = true; + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(149, 90); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 30); + this.buttonCancel.TabIndex = 3; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // lineNumberTextBox + // + this.lineNumberTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); + this.lineNumberTextBox.Location = new System.Drawing.Point(124, 27); + this.lineNumberTextBox.Name = "lineNumberTextBox"; + this.lineNumberTextBox.Size = new System.Drawing.Size(100, 26); + this.lineNumberTextBox.TabIndex = 0; + // + // GotoLineDialog + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(243, 130); + this.Controls.Add(this.lineNumberTextBox); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.labelLineNumber); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "GotoLineDialog"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Go to line"; + this.Load += new System.EventHandler(this.GotoLineDialog_Load); + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Label labelLineNumber; +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.Button buttonCancel; +private System.Windows.Forms.TextBox lineNumberTextBox; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/GotoLineDialog.cs b/src/LogExpert.UI/Dialogs/GotoLineDialog.cs new file mode 100644 index 00000000..8b7d0b36 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/GotoLineDialog.cs @@ -0,0 +1,51 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class GotoLineDialog : Form +{ + #region Fields + + #endregion + + #region cTor + + public GotoLineDialog(Form parent) + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + Owner = parent; + } + + #endregion + + #region Properties + + public int Line { get; private set; } + + #endregion + + #region Events handler + + private void GotoLineDialog_Load(object sender, EventArgs e) + { + } + + private void okButton_Click(object sender, EventArgs e) + { + try + { + Line = int.Parse(lineNumberTextBox.Text); + } + catch (Exception) + { + Line = -1; + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/GotoLineDialog.resx b/src/LogExpert.UI/Dialogs/GotoLineDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/GotoLineDialog.resx rename to src/LogExpert.UI/Dialogs/GotoLineDialog.resx index c7e0d4bd..d58980a3 100644 --- a/src/LogExpert/Dialogs/GotoLineDialog.resx +++ b/src/LogExpert.UI/Dialogs/GotoLineDialog.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Dialogs/ImportSettingsDialog.Designer.cs b/src/LogExpert.UI/Dialogs/ImportSettingsDialog.Designer.cs new file mode 100644 index 00000000..907f734a --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ImportSettingsDialog.Designer.cs @@ -0,0 +1,225 @@ +namespace LogExpert.UI.Dialogs; + +partial class ImportSettingsDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImportSettingsDialog)); + this.buttonFile = new System.Windows.Forms.Button(); + this.textBoxFileName = new System.Windows.Forms.TextBox(); + this.labelSettingsFileToImport = new System.Windows.Forms.Label(); + this.groupBoxImportOptions = new System.Windows.Forms.GroupBox(); + this.checkBoxKeepExistingSettings = new System.Windows.Forms.CheckBox(); + this.checkBoxOther = new System.Windows.Forms.CheckBox(); + this.checkBoxExternalTools = new System.Windows.Forms.CheckBox(); + this.checkBoxColumnizerFileMasks = new System.Windows.Forms.CheckBox(); + this.checkBoxHighlightFileMasks = new System.Windows.Forms.CheckBox(); + this.checkBoxHighlightSettings = new System.Windows.Forms.CheckBox(); + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.groupBoxImportOptions.SuspendLayout(); + this.SuspendLayout(); + // + // buttonFile + // + this.buttonFile.Location = new System.Drawing.Point(306, 25); + this.buttonFile.Name = "buttonFile"; + this.buttonFile.Size = new System.Drawing.Size(94, 23); + this.buttonFile.TabIndex = 0; + this.buttonFile.Text = "Choose file..."; + this.buttonFile.UseVisualStyleBackColor = true; + this.buttonFile.Click += new System.EventHandler(this.OnFileButtonClick); + // + // textBoxFileName + // + this.textBoxFileName.Location = new System.Drawing.Point(13, 27); + this.textBoxFileName.Name = "textBoxFileName"; + this.textBoxFileName.Size = new System.Drawing.Size(287, 20); + this.textBoxFileName.TabIndex = 1; + // + // labelSettingsFileToImport + // + this.labelSettingsFileToImport.AutoSize = true; + this.labelSettingsFileToImport.Location = new System.Drawing.Point(13, 8); + this.labelSettingsFileToImport.Name = "labelSettingsFileToImport"; + this.labelSettingsFileToImport.Size = new System.Drawing.Size(107, 13); + this.labelSettingsFileToImport.TabIndex = 2; + this.labelSettingsFileToImport.Text = "Settings file to import:"; + // + // groupBoxImportOptions + // + this.groupBoxImportOptions.Controls.Add(this.checkBoxKeepExistingSettings); + this.groupBoxImportOptions.Controls.Add(this.checkBoxOther); + this.groupBoxImportOptions.Controls.Add(this.checkBoxExternalTools); + this.groupBoxImportOptions.Controls.Add(this.checkBoxColumnizerFileMasks); + this.groupBoxImportOptions.Controls.Add(this.checkBoxHighlightFileMasks); + this.groupBoxImportOptions.Controls.Add(this.checkBoxHighlightSettings); + this.groupBoxImportOptions.Location = new System.Drawing.Point(16, 67); + this.groupBoxImportOptions.Name = "groupBoxImportOptions"; + this.groupBoxImportOptions.Size = new System.Drawing.Size(284, 143); + this.groupBoxImportOptions.TabIndex = 3; + this.groupBoxImportOptions.TabStop = false; + this.groupBoxImportOptions.Text = "Import options"; + // + // checkBoxKeepExistingSettings + // + this.checkBoxKeepExistingSettings.AutoSize = true; + this.checkBoxKeepExistingSettings.Location = new System.Drawing.Point(141, 20); + this.checkBoxKeepExistingSettings.Name = "checkBoxKeepExistingSettings"; + this.checkBoxKeepExistingSettings.Size = new System.Drawing.Size(128, 17); + this.checkBoxKeepExistingSettings.TabIndex = 1; + this.checkBoxKeepExistingSettings.Tag = "32"; + this.checkBoxKeepExistingSettings.Text = "Keep existing settings"; + this.checkBoxKeepExistingSettings.UseVisualStyleBackColor = true; + // + // checkBoxOther + // + this.checkBoxOther.AutoSize = true; + this.checkBoxOther.Checked = true; + this.checkBoxOther.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBoxOther.Location = new System.Drawing.Point(7, 112); + this.checkBoxOther.Name = "checkBoxOther"; + this.checkBoxOther.Size = new System.Drawing.Size(52, 17); + this.checkBoxOther.TabIndex = 0; + this.checkBoxOther.Tag = "16"; + this.checkBoxOther.Text = "Other"; + this.checkBoxOther.UseVisualStyleBackColor = true; + // + // checkBoxExternalTools + // + this.checkBoxExternalTools.AutoSize = true; + this.checkBoxExternalTools.Checked = true; + this.checkBoxExternalTools.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBoxExternalTools.Location = new System.Drawing.Point(7, 89); + this.checkBoxExternalTools.Name = "checkBoxExternalTools"; + this.checkBoxExternalTools.Size = new System.Drawing.Size(89, 17); + this.checkBoxExternalTools.TabIndex = 0; + this.checkBoxExternalTools.Tag = "8"; + this.checkBoxExternalTools.Text = "External tools"; + this.checkBoxExternalTools.UseVisualStyleBackColor = true; + // + // checkBoxColumnizerFileMasks + // + this.checkBoxColumnizerFileMasks.AutoSize = true; + this.checkBoxColumnizerFileMasks.Checked = true; + this.checkBoxColumnizerFileMasks.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBoxColumnizerFileMasks.Location = new System.Drawing.Point(7, 66); + this.checkBoxColumnizerFileMasks.Name = "checkBoxColumnizerFileMasks"; + this.checkBoxColumnizerFileMasks.Size = new System.Drawing.Size(126, 17); + this.checkBoxColumnizerFileMasks.TabIndex = 0; + this.checkBoxColumnizerFileMasks.Tag = "2"; + this.checkBoxColumnizerFileMasks.Text = "Columnizer file masks"; + this.checkBoxColumnizerFileMasks.UseVisualStyleBackColor = true; + // + // checkBoxHighlightFileMasks + // + this.checkBoxHighlightFileMasks.AutoSize = true; + this.checkBoxHighlightFileMasks.Checked = true; + this.checkBoxHighlightFileMasks.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBoxHighlightFileMasks.Location = new System.Drawing.Point(7, 43); + this.checkBoxHighlightFileMasks.Name = "checkBoxHighlightFileMasks"; + this.checkBoxHighlightFileMasks.Size = new System.Drawing.Size(116, 17); + this.checkBoxHighlightFileMasks.TabIndex = 0; + this.checkBoxHighlightFileMasks.Tag = "4"; + this.checkBoxHighlightFileMasks.Text = "Highlight file masks"; + this.checkBoxHighlightFileMasks.UseVisualStyleBackColor = true; + // + // checkBoxHighlightSettings + // + this.checkBoxHighlightSettings.AutoSize = true; + this.checkBoxHighlightSettings.Checked = true; + this.checkBoxHighlightSettings.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBoxHighlightSettings.Location = new System.Drawing.Point(7, 20); + this.checkBoxHighlightSettings.Name = "checkBoxHighlightSettings"; + this.checkBoxHighlightSettings.Size = new System.Drawing.Size(106, 17); + this.checkBoxHighlightSettings.TabIndex = 0; + this.checkBoxHighlightSettings.Tag = "1"; + this.checkBoxHighlightSettings.Text = "Highlight settings"; + this.checkBoxHighlightSettings.UseVisualStyleBackColor = true; + // + // buttonOk + // + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(325, 187); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 4; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnOkButtonClick); + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(325, 154); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 5; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // ImportSettingsDialog + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(412, 224); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.groupBoxImportOptions); + this.Controls.Add(this.labelSettingsFileToImport); + this.Controls.Add(this.textBoxFileName); + this.Controls.Add(this.buttonFile); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ImportSettingsDialog"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Import Settings"; + this.Load += new System.EventHandler(this.OnImportSettingsDialogLoad); + this.groupBoxImportOptions.ResumeLayout(false); + this.groupBoxImportOptions.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Button buttonFile; +private System.Windows.Forms.TextBox textBoxFileName; +private System.Windows.Forms.Label labelSettingsFileToImport; +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.Button buttonCancel; + public System.Windows.Forms.CheckBox checkBoxExternalTools; + public System.Windows.Forms.CheckBox checkBoxColumnizerFileMasks; + public System.Windows.Forms.CheckBox checkBoxHighlightFileMasks; + public System.Windows.Forms.CheckBox checkBoxHighlightSettings; + public System.Windows.Forms.CheckBox checkBoxOther; + public System.Windows.Forms.CheckBox checkBoxKeepExistingSettings; + public System.Windows.Forms.GroupBox groupBoxImportOptions; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/ImportSettingsDialog.cs b/src/LogExpert.UI/Dialogs/ImportSettingsDialog.cs new file mode 100644 index 00000000..e7200fb4 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ImportSettingsDialog.cs @@ -0,0 +1,98 @@ +using LogExpert.Core.Config; + +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class ImportSettingsDialog : Form +{ + #region cTor + + public ImportSettingsDialog(ExportImportFlags importFlags) + { + InitializeComponent(); + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + ImportFlags = importFlags; + FileName = string.Empty; + + if (ImportFlags == ExportImportFlags.HighlightSettings) + { + checkBoxHighlightSettings.Checked = true; + checkBoxHighlightSettings.Enabled = false; + checkBoxHighlightFileMasks.Checked = false; + checkBoxHighlightFileMasks.Enabled = false; + checkBoxColumnizerFileMasks.Checked = false; + checkBoxColumnizerFileMasks.Enabled = false; + checkBoxExternalTools.Checked = false; + checkBoxExternalTools.Enabled = false; + checkBoxOther.Checked = false; + checkBoxOther.Enabled = false; + } + + ResumeLayout(); + } + + #endregion + + #region Properties + + public string FileName { get; private set; } + + public ExportImportFlags ImportFlags { get; private set; } + + #endregion + + #region Events handler + + private void OnImportSettingsDialogLoad(object sender, EventArgs e) + { + } + + private void OnFileButtonClick(object sender, EventArgs e) + { + OpenFileDialog dlg = new() + { + Title = "Load Settings from file", + DefaultExt = "json", + AddExtension = false, + Filter = "Settings (*.json)|*.json|All files (*.*)|*.*" + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + textBoxFileName.Text = dlg.FileName; + } + } + + private void OnOkButtonClick(object sender, EventArgs e) + { + FileName = textBoxFileName.Text; + + if (ImportFlags != ExportImportFlags.HighlightSettings) + { + foreach (Control ctl in groupBoxImportOptions.Controls) + { + if (ctl.Tag != null) + { + if (((CheckBox)ctl).Checked) + { + ImportFlags |= (ExportImportFlags)long.Parse(ctl.Tag as string ?? string.Empty); + } + } + } + } + else + { + if (checkBoxKeepExistingSettings.Checked) + { + ImportFlags |= ExportImportFlags.KeepExisting; + } + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ImportSettingsDialog.resx b/src/LogExpert.UI/Dialogs/ImportSettingsDialog.resx similarity index 98% rename from src/LogExpert/Dialogs/ImportSettingsDialog.resx rename to src/LogExpert.UI/Dialogs/ImportSettingsDialog.resx index 2de0ae4d..a43dafee 100644 --- a/src/LogExpert/Dialogs/ImportSettingsDialog.resx +++ b/src/LogExpert.UI/Dialogs/ImportSettingsDialog.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + 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/Dialogs/KeywordActionDlg.Designer.cs b/src/LogExpert.UI/Dialogs/KeywordActionDlg.Designer.cs new file mode 100644 index 00000000..d7c8b0d6 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/KeywordActionDlg.Designer.cs @@ -0,0 +1,138 @@ +namespace LogExpert.UI.Dialogs; + +partial class KeywordActionDlg +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(KeywordActionDlg)); + this.actionComboBox = new System.Windows.Forms.ComboBox(); + this.label1 = new System.Windows.Forms.Label(); + this.parameterTextBox = new System.Windows.Forms.TextBox(); + this.label2 = new System.Windows.Forms.Label(); + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.commentTextBox = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // actionComboBox + // + this.actionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.actionComboBox.FormattingEnabled = true; + this.actionComboBox.Location = new System.Drawing.Point(12, 36); + this.actionComboBox.Name = "actionComboBox"; + this.actionComboBox.Size = new System.Drawing.Size(329, 28); + this.actionComboBox.TabIndex = 0; + this.actionComboBox.SelectedIndexChanged += new System.EventHandler(this.OnActionComboBoxSelectedIndexChanged); + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 20); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(166, 20); + this.label1.TabIndex = 1; + this.label1.Text = "Keyword action plugin:"; + // + // parameterTextBox + // + this.parameterTextBox.Location = new System.Drawing.Point(12, 188); + this.parameterTextBox.Name = "parameterTextBox"; + this.parameterTextBox.Size = new System.Drawing.Size(331, 26); + this.parameterTextBox.TabIndex = 2; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(12, 172); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(83, 20); + this.label2.TabIndex = 3; + this.label2.Text = "Parameter"; + // + // buttonOk + // + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(166, 223); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 4; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnOkButtonClick); + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(264, 223); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 5; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // commentTextBox + // + this.commentTextBox.Location = new System.Drawing.Point(15, 64); + this.commentTextBox.Multiline = true; + this.commentTextBox.Name = "commentTextBox"; + this.commentTextBox.ReadOnly = true; + this.commentTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.commentTextBox.Size = new System.Drawing.Size(326, 95); + this.commentTextBox.TabIndex = 6; + // + // KeywordActionDlg + // + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(353, 258); + this.Controls.Add(this.commentTextBox); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.label2); + this.Controls.Add(this.parameterTextBox); + this.Controls.Add(this.label1); + this.Controls.Add(this.actionComboBox); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "KeywordActionDlg"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Keyword Action"; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.ComboBox actionComboBox; +private System.Windows.Forms.Label label1; +private System.Windows.Forms.TextBox parameterTextBox; +private System.Windows.Forms.Label label2; +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.Button buttonCancel; +private System.Windows.Forms.TextBox commentTextBox; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/KeywordActionDlg.cs b/src/LogExpert.UI/Dialogs/KeywordActionDlg.cs new file mode 100644 index 00000000..dbc508f0 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/KeywordActionDlg.cs @@ -0,0 +1,82 @@ +using LogExpert.Core.Classes.Highlight; + +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class KeywordActionDlg : Form +{ + #region Fields + + private readonly IDictionary _actionDict = new Dictionary(); + + private IList _keywordActionList; + + #endregion + + #region cTor + + public KeywordActionDlg(ActionEntry entry, IList actionList) + { + _keywordActionList = actionList; + ActionEntry = entry; + + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + actionComboBox.Items.Clear(); + + foreach (IKeywordAction action in actionList) + { + actionComboBox.Items.Add(action.GetName()); + _actionDict[action.GetName()] = action; + } + + if (actionComboBox.Items.Count > 0) + { + if (ActionEntry.PluginName != null && _actionDict.ContainsKey(ActionEntry.PluginName)) + { + actionComboBox.SelectedItem = ActionEntry.PluginName; + } + else + { + actionComboBox.SelectedIndex = 0; + } + } + + parameterTextBox.Text = ActionEntry.ActionParam; + } + + #endregion + + #region Properties + + public ActionEntry ActionEntry { get; private set; } + + #endregion + + #region Events handler + + private void OnOkButtonClick(object sender, EventArgs e) + { + ActionEntry = new ActionEntry + { + ActionParam = parameterTextBox.Text + }; + + if (_actionDict.ContainsKey((string)actionComboBox.SelectedItem)) + { + ActionEntry.PluginName = (string)actionComboBox.SelectedItem; + } + } + + private void OnActionComboBoxSelectedIndexChanged(object sender, EventArgs e) + { + commentTextBox.Text = _actionDict[(string)actionComboBox.SelectedItem].GetDescription(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/KeywordActionDlg.resx b/src/LogExpert.UI/Dialogs/KeywordActionDlg.resx similarity index 98% rename from src/LogExpert/Dialogs/KeywordActionDlg.resx rename to src/LogExpert.UI/Dialogs/KeywordActionDlg.resx index 2de0ae4d..a43dafee 100644 --- a/src/LogExpert/Dialogs/KeywordActionDlg.resx +++ b/src/LogExpert.UI/Dialogs/KeywordActionDlg.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + 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/Dialogs/LogTabWindow/FilterSelectorForm.Designer.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.Designer.cs new file mode 100644 index 00000000..812f5924 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.Designer.cs @@ -0,0 +1,155 @@ +namespace LogExpert.Dialogs; + +partial class FilterSelectorForm +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FilterSelectorForm)); + this.filterComboBox = new System.Windows.Forms.ComboBox(); + this.label1 = new System.Windows.Forms.Label(); + this.okButton = new System.Windows.Forms.Button(); + this.cancelButton = new System.Windows.Forms.Button(); + this.commentTextBox = new System.Windows.Forms.TextBox(); + this.applyToAllCheckBox = new System.Windows.Forms.CheckBox(); + this.helpProvider1 = new System.Windows.Forms.HelpProvider(); + this.configButton = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // filterComboBox + // + this.filterComboBox.DisplayMember = "Text"; + this.filterComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.filterComboBox.FormattingEnabled = true; + this.filterComboBox.Location = new System.Drawing.Point(12, 25); + this.filterComboBox.Name = "filterComboBox"; + this.filterComboBox.Size = new System.Drawing.Size(298, 21); + this.filterComboBox.TabIndex = 0; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(13, 6); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(108, 13); + this.label1.TabIndex = 1; + this.label1.Text = "Choose a columnizer:"; + // + // okButton + // + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okButton.Location = new System.Drawing.Point(154, 194); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(75, 23); + this.okButton.TabIndex = 2; + this.okButton.Text = "OK"; + this.okButton.UseVisualStyleBackColor = true; + // + // cancelButton + // + this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.cancelButton.Location = new System.Drawing.Point(235, 194); + this.cancelButton.Name = "cancelButton"; + this.cancelButton.Size = new System.Drawing.Size(75, 23); + this.cancelButton.TabIndex = 3; + this.cancelButton.Text = "Cancel"; + this.cancelButton.UseVisualStyleBackColor = true; + // + // commentTextBox + // + this.commentTextBox.Location = new System.Drawing.Point(12, 81); + this.commentTextBox.Multiline = true; + this.commentTextBox.Name = "commentTextBox"; + this.commentTextBox.ReadOnly = true; + this.commentTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.commentTextBox.Size = new System.Drawing.Size(298, 89); + this.commentTextBox.TabIndex = 4; + // + // applyToAllCheckBox + // + this.applyToAllCheckBox.AutoSize = true; + this.applyToAllCheckBox.Location = new System.Drawing.Point(12, 176); + this.applyToAllCheckBox.Name = "applyToAllCheckBox"; + this.applyToAllCheckBox.Size = new System.Drawing.Size(125, 17); + this.applyToAllCheckBox.TabIndex = 6; + this.applyToAllCheckBox.Text = "Apply to all open files"; + this.applyToAllCheckBox.UseVisualStyleBackColor = true; + // + // helpProvider1 + // + this.helpProvider1.HelpNamespace = "LogExpert.chm"; + // + // configButton + // + this.configButton.Location = new System.Drawing.Point(235, 52); + this.configButton.Name = "configButton"; + this.configButton.Size = new System.Drawing.Size(75, 23); + this.configButton.TabIndex = 7; + this.configButton.Text = "Config..."; + this.configButton.UseVisualStyleBackColor = true; + this.configButton.Click += new System.EventHandler(this.OnConfigButtonClick); + // + // FilterSelectorForm + // + this.AcceptButton = this.okButton; + this.CancelButton = this.cancelButton; + this.ClientSize = new System.Drawing.Size(322, 232); + this.Controls.Add(this.configButton); + this.Controls.Add(this.applyToAllCheckBox); + this.Controls.Add(this.commentTextBox); + this.Controls.Add(this.cancelButton); + this.Controls.Add(this.okButton); + this.Controls.Add(this.label1); + this.Controls.Add(this.filterComboBox); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.helpProvider1.SetHelpKeyword(this, "Columnizers.htm"); + this.helpProvider1.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "FilterSelectorForm"; + this.helpProvider1.SetShowHelp(this, true); + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Columnizer"; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.ComboBox filterComboBox; +private System.Windows.Forms.Label label1; +private System.Windows.Forms.Button okButton; +private System.Windows.Forms.Button cancelButton; +private System.Windows.Forms.TextBox commentTextBox; +private System.Windows.Forms.CheckBox applyToAllCheckBox; +private System.Windows.Forms.HelpProvider helpProvider1; +private System.Windows.Forms.Button configButton; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.cs new file mode 100644 index 00000000..7fc01ba0 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.cs @@ -0,0 +1,101 @@ +using System.Runtime.Versioning; + +using LogExpert.Core.Interface; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class FilterSelectorForm : Form //TODO: Can this be changed to UserControl? +{ + #region Fields + + private readonly ILogLineColumnizerCallback _callback; + private readonly IList _columnizerList; + + #endregion + + #region cTor + + public FilterSelectorForm (IList existingColumnizerList, ILogLineColumnizer currentColumnizer, ILogLineColumnizerCallback callback, IConfigManager configManager) + { + SelectedColumnizer = currentColumnizer; + _callback = callback; + InitializeComponent(); + + ConfigManager = configManager; + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + filterComboBox.SelectedIndexChanged += OnFilterComboBoxSelectedIndexChanged; + + // for the currently selected columnizer use the current instance and not the template instance from + // columnizer registry. This ensures that changes made in columnizer config dialogs + // will apply to the current instance + _columnizerList = new List(); + + foreach (ILogLineColumnizer col in existingColumnizerList) + { + _columnizerList.Add(col.GetType() == SelectedColumnizer.GetType() ? SelectedColumnizer : col); + } + + foreach (ILogLineColumnizer col in _columnizerList) + { + filterComboBox.Items.Add(col); + } + + foreach (ILogLineColumnizer columnizer in _columnizerList) + { + if (columnizer.GetType() == SelectedColumnizer.GetType()) + { + filterComboBox.SelectedItem = columnizer; + break; + } + } + } + + #endregion + + #region Properties + + public ILogLineColumnizer SelectedColumnizer { get; private set; } + + public bool ApplyToAll => applyToAllCheckBox.Checked; + + public bool IsConfigPressed { get; private set; } + public IConfigManager ConfigManager { get; } + + #endregion + + #region Events handler + + private void OnFilterComboBoxSelectedIndexChanged (object sender, EventArgs e) + { + ILogLineColumnizer col = _columnizerList[filterComboBox.SelectedIndex]; + SelectedColumnizer = col; + var description = col.GetDescription(); + description += "\r\nSupports timeshift: " + (SelectedColumnizer.IsTimeshiftImplemented() ? "Yes" : "No"); + commentTextBox.Text = description; + configButton.Enabled = SelectedColumnizer is IColumnizerConfigurator; + } + + + //TODO: Check if this logic can be remoed from this class and remove all the config manager instances from here. + private void OnConfigButtonClick (object sender, EventArgs e) + { + if (SelectedColumnizer is IColumnizerConfigurator configurator) + { + var configDir = ConfigManager.ConfigDir; + + if (ConfigManager.Settings.Preferences.PortableMode) + { + configDir = ConfigManager.PortableModeDir; + } + + configurator.Configure(_callback, configDir); + IsConfigPressed = true; + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/FilterSelectorForm.resx b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.resx similarity index 98% rename from src/LogExpert/Dialogs/FilterSelectorForm.resx rename to src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.resx index 03269ae2..59a0e090 100644 --- a/src/LogExpert/Dialogs/FilterSelectorForm.resx +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/FilterSelectorForm.resx @@ -1,134 +1,134 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + + + + 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/Dialogs/LogTabWindow/HighlightDialog.Designer.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.Designer.cs new file mode 100644 index 00000000..fab3e223 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.Designer.cs @@ -0,0 +1,725 @@ +using LogExpert.UI.Controls; + +using System.Drawing; + +namespace LogExpert.Dialogs; + +partial class HighlightDialog +{ + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HighlightDialog)); + listBoxHighlight = new System.Windows.Forms.ListBox(); + btnAdd = new System.Windows.Forms.Button(); + btnDelete = new System.Windows.Forms.Button(); + btnMoveUp = new System.Windows.Forms.Button(); + btnMoveDown = new System.Windows.Forms.Button(); + labelForgroundColor = new System.Windows.Forms.Label(); + labelBackgroundColor = new System.Windows.Forms.Label(); + btnOk = new System.Windows.Forms.Button(); + btnCancel = new System.Windows.Forms.Button(); + textBoxSearchString = new System.Windows.Forms.TextBox(); + labelSearchString = new System.Windows.Forms.Label(); + btnApply = new System.Windows.Forms.Button(); + btnCustomForeColor = new System.Windows.Forms.Button(); + btnCustomBackColor = new System.Windows.Forms.Button(); + checkBoxRegex = new System.Windows.Forms.CheckBox(); + checkBoxCaseSensitive = new System.Windows.Forms.CheckBox(); + checkBoxDontDirtyLed = new System.Windows.Forms.CheckBox(); + groupBoxLineMatchCriteria = new System.Windows.Forms.GroupBox(); + groupBoxColoring = new System.Windows.Forms.GroupBox(); + checkBoxNoBackground = new System.Windows.Forms.CheckBox(); + checkBoxBold = new System.Windows.Forms.CheckBox(); + checkBoxWordMatch = new System.Windows.Forms.CheckBox(); + colorBoxForeground = new ColorComboBox(); + colorBoxBackground = new ColorComboBox(); + groupBoxActions = new System.Windows.Forms.GroupBox(); + btnBookmarkComment = new System.Windows.Forms.Button(); + btnSelectPlugin = new System.Windows.Forms.Button(); + checkBoxPlugin = new System.Windows.Forms.CheckBox(); + checkBoxStopTail = new System.Windows.Forms.CheckBox(); + checkBoxBookmark = new System.Windows.Forms.CheckBox(); + helpProvider = new System.Windows.Forms.HelpProvider(); + groupBox4 = new System.Windows.Forms.GroupBox(); + btnImportGroup = new System.Windows.Forms.Button(); + btnExportGroup = new System.Windows.Forms.Button(); + btnMoveGroupDown = new System.Windows.Forms.Button(); + btnMoveGroupUp = new System.Windows.Forms.Button(); + labelAssignNamesToGroups = new System.Windows.Forms.Label(); + btnCopyGroup = new System.Windows.Forms.Button(); + btnDeleteGroup = new System.Windows.Forms.Button(); + btnNewGroup = new System.Windows.Forms.Button(); + comboBoxGroups = new System.Windows.Forms.ComboBox(); + toolTip = new System.Windows.Forms.ToolTip(components); + pnlBackground = new System.Windows.Forms.Panel(); + groupBoxLineMatchCriteria.SuspendLayout(); + groupBoxColoring.SuspendLayout(); + groupBoxActions.SuspendLayout(); + groupBox4.SuspendLayout(); + pnlBackground.SuspendLayout(); + SuspendLayout(); + // + // listBoxHighlight + // + listBoxHighlight.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + listBoxHighlight.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; + listBoxHighlight.FormattingEnabled = true; + listBoxHighlight.Location = new Point(32, 160); + listBoxHighlight.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + listBoxHighlight.Name = "listBoxHighlight"; + listBoxHighlight.Size = new Size(487, 228); + listBoxHighlight.TabIndex = 0; + listBoxHighlight.SelectedIndexChanged += OnListBoxHighlightSelectedIndexChanged; + // + // btnAdd + // + btnAdd.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnAdd.Location = new Point(529, 218); + btnAdd.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnAdd.Name = "btnAdd"; + btnAdd.Size = new Size(158, 35); + btnAdd.TabIndex = 1; + btnAdd.Text = "&Add"; + toolTip.SetToolTip(btnAdd, "Create a new hilight item from information below"); + btnAdd.UseVisualStyleBackColor = true; + btnAdd.Click += OnAddButtonClick; + // + // btnDelete + // + btnDelete.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnDelete.Location = new Point(529, 263); + btnDelete.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnDelete.Name = "btnDelete"; + btnDelete.Size = new Size(158, 35); + btnDelete.TabIndex = 2; + btnDelete.Text = "D&elete"; + toolTip.SetToolTip(btnDelete, "Delete the current hilight"); + btnDelete.UseVisualStyleBackColor = true; + btnDelete.Click += OnDeleteButtonClick; + // + // btnMoveUp + // + btnMoveUp.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnMoveUp.Location = new Point(529, 160); + btnMoveUp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnMoveUp.Name = "btnMoveUp"; + btnMoveUp.Size = new Size(75, 35); + btnMoveUp.TabIndex = 3; + btnMoveUp.Text = "&Up"; + toolTip.SetToolTip(btnMoveUp, "Move the current hilight one position up"); + btnMoveUp.UseVisualStyleBackColor = true; + btnMoveUp.Click += OnBtnMoveUpClick; + // + // btnMoveDown + // + btnMoveDown.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnMoveDown.Location = new Point(612, 160); + btnMoveDown.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnMoveDown.Name = "btnMoveDown"; + btnMoveDown.Size = new Size(75, 35); + btnMoveDown.TabIndex = 4; + btnMoveDown.Text = "&Down"; + toolTip.SetToolTip(btnMoveDown, "Move the current hilight one position down"); + btnMoveDown.UseVisualStyleBackColor = true; + btnMoveDown.Click += OnBtnMoveDownClick; + // + // labelForgroundColor + // + labelForgroundColor.AutoSize = true; + labelForgroundColor.Location = new Point(9, 38); + labelForgroundColor.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelForgroundColor.Name = "labelForgroundColor"; + labelForgroundColor.Size = new Size(99, 15); + labelForgroundColor.TabIndex = 6; + labelForgroundColor.Text = "Foreground color"; + // + // labelBackgroundColor + // + labelBackgroundColor.AutoSize = true; + labelBackgroundColor.Location = new Point(9, 115); + labelBackgroundColor.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelBackgroundColor.Name = "labelBackgroundColor"; + labelBackgroundColor.Size = new Size(101, 15); + labelBackgroundColor.TabIndex = 8; + labelBackgroundColor.Text = "Background color"; + // + // btnOk + // + btnOk.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; + btnOk.Location = new Point(449, 832); + btnOk.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnOk.Name = "btnOk"; + btnOk.Size = new Size(112, 35); + btnOk.TabIndex = 9; + btnOk.Text = "OK"; + btnOk.UseVisualStyleBackColor = true; + btnOk.Click += OnBtnOkClick; + // + // btnCancel + // + btnCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + btnCancel.Location = new Point(576, 832); + btnCancel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnCancel.Name = "btnCancel"; + btnCancel.Size = new Size(112, 35); + btnCancel.TabIndex = 10; + btnCancel.Text = "Cancel"; + btnCancel.UseVisualStyleBackColor = true; + // + // textBoxSearchString + // + textBoxSearchString.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + textBoxSearchString.Location = new Point(9, 55); + textBoxSearchString.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + textBoxSearchString.Name = "textBoxSearchString"; + textBoxSearchString.Size = new Size(639, 23); + textBoxSearchString.TabIndex = 11; + textBoxSearchString.TextChanged += ChangeToDirty; + // + // labelSearchString + // + labelSearchString.AutoSize = true; + labelSearchString.Location = new Point(9, 31); + labelSearchString.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelSearchString.Name = "labelSearchString"; + labelSearchString.Size = new Size(78, 15); + labelSearchString.TabIndex = 12; + labelSearchString.Text = "Search string:"; + // + // btnApply + // + btnApply.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnApply.Enabled = false; + btnApply.Image = (Image)resources.GetObject("btnApply.Image"); + btnApply.ImageAlign = ContentAlignment.MiddleRight; + btnApply.Location = new Point(529, 308); + btnApply.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnApply.Name = "btnApply"; + btnApply.Size = new Size(158, 35); + btnApply.TabIndex = 13; + btnApply.Text = "A&pply"; + toolTip.SetToolTip(btnApply, "Apply changes below to current hiligth"); + btnApply.UseVisualStyleBackColor = true; + btnApply.Click += OnBtnApplyClick; + // + // btnCustomForeColor + // + btnCustomForeColor.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnCustomForeColor.Location = new Point(247, 60); + btnCustomForeColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnCustomForeColor.Name = "btnCustomForeColor"; + btnCustomForeColor.Size = new Size(78, 35); + btnCustomForeColor.TabIndex = 14; + btnCustomForeColor.Text = "Custom"; + toolTip.SetToolTip(btnCustomForeColor, "Pick a custom foreground color"); + btnCustomForeColor.UseVisualStyleBackColor = true; + btnCustomForeColor.Click += OnBtnCustomForeColorClick; + // + // btnCustomBackColor + // + btnCustomBackColor.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnCustomBackColor.Location = new Point(247, 137); + btnCustomBackColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnCustomBackColor.Name = "btnCustomBackColor"; + btnCustomBackColor.Size = new Size(78, 35); + btnCustomBackColor.TabIndex = 15; + btnCustomBackColor.Text = "Custom"; + toolTip.SetToolTip(btnCustomBackColor, "Pick a custom background color"); + btnCustomBackColor.UseVisualStyleBackColor = true; + btnCustomBackColor.Click += OnBtnCustomBackColorClick; + // + // checkBoxRegex + // + checkBoxRegex.AutoSize = true; + checkBoxRegex.Location = new Point(180, 95); + checkBoxRegex.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxRegex.Name = "checkBoxRegex"; + checkBoxRegex.Size = new Size(57, 19); + checkBoxRegex.TabIndex = 16; + checkBoxRegex.Text = "RegEx"; + toolTip.SetToolTip(checkBoxRegex, "Whether the string is a regular expresion"); + checkBoxRegex.UseVisualStyleBackColor = true; + checkBoxRegex.CheckedChanged += ChangeToDirty; + checkBoxRegex.MouseUp += OnChkBoxRegexMouseUp; + // + // checkBoxCaseSensitive + // + checkBoxCaseSensitive.AutoSize = true; + checkBoxCaseSensitive.Location = new Point(14, 95); + checkBoxCaseSensitive.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxCaseSensitive.Name = "checkBoxCaseSensitive"; + checkBoxCaseSensitive.Size = new Size(99, 19); + checkBoxCaseSensitive.TabIndex = 17; + checkBoxCaseSensitive.Text = "Case sensitive"; + toolTip.SetToolTip(checkBoxCaseSensitive, "Whether the string will match uppercases and lowercases"); + checkBoxCaseSensitive.UseVisualStyleBackColor = true; + checkBoxCaseSensitive.CheckedChanged += ChangeToDirty; + // + // checkBoxDontDirtyLed + // + checkBoxDontDirtyLed.AutoSize = true; + checkBoxDontDirtyLed.Location = new Point(15, 38); + checkBoxDontDirtyLed.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxDontDirtyLed.Name = "checkBoxDontDirtyLed"; + checkBoxDontDirtyLed.Size = new Size(118, 19); + checkBoxDontDirtyLed.TabIndex = 18; + checkBoxDontDirtyLed.Text = "Don't lit dirty LED"; + toolTip.SetToolTip(checkBoxDontDirtyLed, "When matching a line, don't mark the page as \"dirty\""); + checkBoxDontDirtyLed.UseVisualStyleBackColor = true; + checkBoxDontDirtyLed.CheckedChanged += ChangeToDirty; + // + // groupBoxLineMatchCriteria + // + groupBoxLineMatchCriteria.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + groupBoxLineMatchCriteria.Controls.Add(textBoxSearchString); + groupBoxLineMatchCriteria.Controls.Add(labelSearchString); + groupBoxLineMatchCriteria.Controls.Add(checkBoxRegex); + groupBoxLineMatchCriteria.Controls.Add(checkBoxCaseSensitive); + groupBoxLineMatchCriteria.Location = new Point(18, 437); + groupBoxLineMatchCriteria.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxLineMatchCriteria.Name = "groupBoxLineMatchCriteria"; + groupBoxLineMatchCriteria.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxLineMatchCriteria.Size = new Size(671, 135); + groupBoxLineMatchCriteria.TabIndex = 19; + groupBoxLineMatchCriteria.TabStop = false; + groupBoxLineMatchCriteria.Text = "Line match criteria"; + // + // groupBoxColoring + // + groupBoxColoring.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + groupBoxColoring.Controls.Add(checkBoxNoBackground); + groupBoxColoring.Controls.Add(checkBoxBold); + groupBoxColoring.Controls.Add(checkBoxWordMatch); + groupBoxColoring.Controls.Add(labelForgroundColor); + groupBoxColoring.Controls.Add(colorBoxForeground); + groupBoxColoring.Controls.Add(btnCustomForeColor); + groupBoxColoring.Controls.Add(btnCustomBackColor); + groupBoxColoring.Controls.Add(labelBackgroundColor); + groupBoxColoring.Controls.Add(colorBoxBackground); + groupBoxColoring.Location = new Point(18, 581); + groupBoxColoring.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxColoring.Name = "groupBoxColoring"; + groupBoxColoring.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxColoring.Size = new Size(349, 286); + groupBoxColoring.TabIndex = 20; + groupBoxColoring.TabStop = false; + groupBoxColoring.Text = "Coloring"; + // + // checkBoxNoBackground + // + checkBoxNoBackground.AutoSize = true; + checkBoxNoBackground.Enabled = false; + checkBoxNoBackground.Location = new Point(141, 240); + checkBoxNoBackground.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxNoBackground.Name = "checkBoxNoBackground"; + checkBoxNoBackground.Size = new Size(109, 19); + checkBoxNoBackground.TabIndex = 18; + checkBoxNoBackground.Text = "No Background"; + toolTip.SetToolTip(checkBoxNoBackground, "Don't set the background color"); + checkBoxNoBackground.UseVisualStyleBackColor = true; + checkBoxNoBackground.CheckedChanged += OnChkBoxNoBackgroundCheckedChanged; + // + // checkBoxBold + // + checkBoxBold.AutoSize = true; + checkBoxBold.Location = new Point(9, 205); + checkBoxBold.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxBold.Name = "checkBoxBold"; + checkBoxBold.Size = new Size(50, 19); + checkBoxBold.TabIndex = 17; + checkBoxBold.Text = "Bold"; + toolTip.SetToolTip(checkBoxBold, "Display the line in bold characters"); + checkBoxBold.UseVisualStyleBackColor = true; + checkBoxBold.CheckedChanged += OnChkBoxBoldCheckedChanged; + // + // checkBoxWordMatch + // + checkBoxWordMatch.AutoSize = true; + checkBoxWordMatch.Location = new Point(9, 240); + checkBoxWordMatch.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxWordMatch.Name = "checkBoxWordMatch"; + checkBoxWordMatch.Size = new Size(89, 19); + checkBoxWordMatch.TabIndex = 16; + checkBoxWordMatch.Text = "Word mode"; + toolTip.SetToolTip(checkBoxWordMatch, "Don't highlight the whole line but only the matching keywords"); + checkBoxWordMatch.UseVisualStyleBackColor = true; + checkBoxWordMatch.CheckedChanged += OnChkBoxWordMatchCheckedChanged; + // + // colorBoxForeground + // + colorBoxForeground.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + colorBoxForeground.CustomColor = Color.Black; + colorBoxForeground.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; + colorBoxForeground.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + colorBoxForeground.FormattingEnabled = true; + colorBoxForeground.Location = new Point(8, 63); + colorBoxForeground.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + colorBoxForeground.Name = "colorBoxForeground"; + colorBoxForeground.Size = new Size(229, 24); + colorBoxForeground.TabIndex = 5; + colorBoxForeground.SelectedIndexChanged += ChangeToDirty; + // + // colorBoxBackground + // + colorBoxBackground.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + colorBoxBackground.CustomColor = Color.Black; + colorBoxBackground.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; + colorBoxBackground.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + colorBoxBackground.FormattingEnabled = true; + colorBoxBackground.Location = new Point(9, 140); + colorBoxBackground.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + colorBoxBackground.Name = "colorBoxBackground"; + colorBoxBackground.Size = new Size(229, 24); + colorBoxBackground.TabIndex = 7; + colorBoxBackground.SelectedIndexChanged += ChangeToDirty; + // + // groupBoxActions + // + groupBoxActions.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + groupBoxActions.Controls.Add(btnBookmarkComment); + groupBoxActions.Controls.Add(btnSelectPlugin); + groupBoxActions.Controls.Add(checkBoxPlugin); + groupBoxActions.Controls.Add(checkBoxStopTail); + groupBoxActions.Controls.Add(checkBoxBookmark); + groupBoxActions.Controls.Add(checkBoxDontDirtyLed); + groupBoxActions.Location = new Point(377, 581); + groupBoxActions.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxActions.Name = "groupBoxActions"; + groupBoxActions.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxActions.Size = new Size(312, 195); + groupBoxActions.TabIndex = 21; + groupBoxActions.TabStop = false; + groupBoxActions.Text = "Actions"; + // + // btnBookmarkComment + // + btnBookmarkComment.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnBookmarkComment.Location = new Point(210, 69); + btnBookmarkComment.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnBookmarkComment.Name = "btnBookmarkComment"; + btnBookmarkComment.Size = new Size(81, 31); + btnBookmarkComment.TabIndex = 23; + btnBookmarkComment.Text = "Text..."; + btnBookmarkComment.UseVisualStyleBackColor = true; + btnBookmarkComment.Click += OnBtnBookmarkCommentClick; + // + // btnSelectPlugin + // + btnSelectPlugin.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnSelectPlugin.Location = new Point(210, 143); + btnSelectPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnSelectPlugin.Name = "btnSelectPlugin"; + btnSelectPlugin.Size = new Size(81, 31); + btnSelectPlugin.TabIndex = 22; + btnSelectPlugin.Text = "Select..."; + btnSelectPlugin.UseVisualStyleBackColor = true; + btnSelectPlugin.Click += OnPluginButtonClick; + // + // checkBoxPlugin + // + checkBoxPlugin.AutoSize = true; + checkBoxPlugin.Location = new Point(15, 148); + checkBoxPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxPlugin.Name = "checkBoxPlugin"; + checkBoxPlugin.Size = new Size(60, 19); + checkBoxPlugin.TabIndex = 21; + checkBoxPlugin.Text = "Plugin"; + toolTip.SetToolTip(checkBoxPlugin, "When matching a line, call a keyword action plugin"); + checkBoxPlugin.UseVisualStyleBackColor = true; + checkBoxPlugin.CheckedChanged += OnChkBoxPluginCheckedChanged; + // + // checkBoxStopTail + // + checkBoxStopTail.AutoSize = true; + checkBoxStopTail.Location = new Point(15, 111); + checkBoxStopTail.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxStopTail.Name = "checkBoxStopTail"; + checkBoxStopTail.Size = new Size(109, 19); + checkBoxStopTail.TabIndex = 20; + checkBoxStopTail.Text = "Stop Follow Tail"; + toolTip.SetToolTip(checkBoxStopTail, "When matching a line, stop automatic scrolling"); + checkBoxStopTail.UseVisualStyleBackColor = true; + checkBoxStopTail.CheckedChanged += ChangeToDirty; + // + // checkBoxBookmark + // + checkBoxBookmark.AutoSize = true; + checkBoxBookmark.Location = new Point(15, 74); + checkBoxBookmark.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxBookmark.Name = "checkBoxBookmark"; + checkBoxBookmark.Size = new Size(99, 19); + checkBoxBookmark.TabIndex = 19; + checkBoxBookmark.Text = "Set bookmark"; + toolTip.SetToolTip(checkBoxBookmark, "When matching a line, create a new bookmark for it"); + checkBoxBookmark.UseVisualStyleBackColor = true; + checkBoxBookmark.CheckedChanged += ChangeToDirty; + // + // helpProvider + // + helpProvider.HelpNamespace = "LogExpert.chm"; + helpProvider.Tag = ""; + // + // groupBox4 + // + groupBox4.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + groupBox4.Controls.Add(btnImportGroup); + groupBox4.Controls.Add(btnExportGroup); + groupBox4.Controls.Add(btnMoveGroupDown); + groupBox4.Controls.Add(btnMoveGroupUp); + groupBox4.Controls.Add(labelAssignNamesToGroups); + groupBox4.Controls.Add(btnCopyGroup); + groupBox4.Controls.Add(btnDeleteGroup); + groupBox4.Controls.Add(btnNewGroup); + groupBox4.Controls.Add(comboBoxGroups); + groupBox4.Location = new Point(18, 5); + groupBox4.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBox4.Name = "groupBox4"; + groupBox4.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBox4.Size = new Size(671, 129); + groupBox4.TabIndex = 22; + groupBox4.TabStop = false; + groupBox4.Text = "Groups"; + // + // btnImportGroup + // + btnImportGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + btnImportGroup.Location = new Point(333, 26); + btnImportGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnImportGroup.Name = "btnImportGroup"; + btnImportGroup.Size = new Size(75, 35); + btnImportGroup.TabIndex = 7; + btnImportGroup.Text = "Import"; + toolTip.SetToolTip(btnImportGroup, "Import highlight groups"); + btnImportGroup.UseVisualStyleBackColor = true; + btnImportGroup.Click += OnBtnImportGroupClick; + // + // btnExportGroup + // + btnExportGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + btnExportGroup.Location = new Point(333, 75); + btnExportGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnExportGroup.Name = "btnExportGroup"; + btnExportGroup.Size = new Size(75, 35); + btnExportGroup.TabIndex = 8; + btnExportGroup.Text = "Export"; + toolTip.SetToolTip(btnExportGroup, "Export highlight groups"); + btnExportGroup.UseVisualStyleBackColor = true; + btnExportGroup.Click += OnBtnExportGroupClick; + // + // btnMoveGroupDown + // + btnMoveGroupDown.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnMoveGroupDown.Location = new Point(582, 75); + btnMoveGroupDown.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnMoveGroupDown.Name = "btnMoveGroupDown"; + btnMoveGroupDown.Size = new Size(75, 35); + btnMoveGroupDown.TabIndex = 6; + btnMoveGroupDown.Text = "Down"; + toolTip.SetToolTip(btnMoveGroupDown, "Move the current hilight group one position down"); + btnMoveGroupDown.UseVisualStyleBackColor = true; + btnMoveGroupDown.Click += OnBtnGroupDownClick; + // + // btnMoveGroupUp + // + btnMoveGroupUp.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; + btnMoveGroupUp.Location = new Point(499, 75); + btnMoveGroupUp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnMoveGroupUp.Name = "btnMoveGroupUp"; + btnMoveGroupUp.Size = new Size(75, 35); + btnMoveGroupUp.TabIndex = 5; + btnMoveGroupUp.Text = "Up"; + toolTip.SetToolTip(btnMoveGroupUp, "Move the current hilight group one position up"); + btnMoveGroupUp.UseVisualStyleBackColor = true; + btnMoveGroupUp.Click += OnBtnGroupUpClick; + // + // labelAssignNamesToGroups + // + labelAssignNamesToGroups.AutoSize = true; + labelAssignNamesToGroups.Location = new Point(9, 88); + labelAssignNamesToGroups.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelAssignNamesToGroups.Name = "labelAssignNamesToGroups"; + labelAssignNamesToGroups.Size = new Size(276, 15); + labelAssignNamesToGroups.TabIndex = 4; + labelAssignNamesToGroups.Text = "You can assign groups to file names in the settings."; + // + // btnCopyGroup + // + btnCopyGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + btnCopyGroup.Location = new Point(582, 26); + btnCopyGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnCopyGroup.Name = "btnCopyGroup"; + btnCopyGroup.Size = new Size(75, 35); + btnCopyGroup.TabIndex = 3; + btnCopyGroup.Text = "Copy"; + toolTip.SetToolTip(btnCopyGroup, "Copy the current hilight group into a new one"); + btnCopyGroup.UseVisualStyleBackColor = true; + btnCopyGroup.Click += OnBtnCopyGroupClick; + // + // btnDeleteGroup + // + btnDeleteGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + btnDeleteGroup.Location = new Point(499, 26); + btnDeleteGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnDeleteGroup.Name = "btnDeleteGroup"; + btnDeleteGroup.Size = new Size(75, 35); + btnDeleteGroup.TabIndex = 2; + btnDeleteGroup.Text = "Del"; + toolTip.SetToolTip(btnDeleteGroup, "Delete the current hilight group"); + btnDeleteGroup.UseVisualStyleBackColor = true; + btnDeleteGroup.Click += OnBtnDelGroupClick; + // + // btnNewGroup + // + btnNewGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; + btnNewGroup.Location = new Point(416, 26); + btnNewGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + btnNewGroup.Name = "btnNewGroup"; + btnNewGroup.Size = new Size(75, 35); + btnNewGroup.TabIndex = 1; + btnNewGroup.Text = "New group"; + btnNewGroup.TextAlign = ContentAlignment.MiddleLeft; + toolTip.SetToolTip(btnNewGroup, "Create a new empty hilight group"); + btnNewGroup.UseVisualStyleBackColor = true; + btnNewGroup.Click += OnBtnNewGroupClick; + // + // comboBoxGroups + // + comboBoxGroups.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + comboBoxGroups.DisplayMember = "GroupName"; + comboBoxGroups.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; + comboBoxGroups.Location = new Point(14, 32); + comboBoxGroups.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + comboBoxGroups.Name = "comboBoxGroups"; + comboBoxGroups.Size = new Size(311, 24); + comboBoxGroups.TabIndex = 0; + toolTip.SetToolTip(comboBoxGroups, "Choose a group to create different highlight settings. Type in a name to change in the name of a group."); + comboBoxGroups.DrawItem += OnCmbBoxGroupDrawItem; + comboBoxGroups.SelectionChangeCommitted += OnCmbBoxGroupSelectionChangeCommitted; + comboBoxGroups.TextUpdate += OnCmbBoxGroupTextUpdate; + // + // pnlBackground + // + pnlBackground.AutoScroll = true; + pnlBackground.Controls.Add(listBoxHighlight); + pnlBackground.Controls.Add(btnAdd); + pnlBackground.Controls.Add(btnDelete); + pnlBackground.Controls.Add(btnMoveUp); + pnlBackground.Controls.Add(btnMoveDown); + pnlBackground.Controls.Add(btnOk); + pnlBackground.Controls.Add(btnCancel); + pnlBackground.Controls.Add(btnApply); + pnlBackground.Controls.Add(groupBoxLineMatchCriteria); + pnlBackground.Controls.Add(groupBoxColoring); + pnlBackground.Controls.Add(groupBoxActions); + pnlBackground.Controls.Add(groupBox4); + pnlBackground.Dock = System.Windows.Forms.DockStyle.Fill; + pnlBackground.Location = new Point(0, 0); + pnlBackground.Name = "pnlBackground"; + pnlBackground.Size = new Size(708, 895); + pnlBackground.TabIndex = 23; + // + // HighlightDialog + // + AcceptButton = btnOk; + CancelButton = btnCancel; + ClientSize = new Size(708, 895); + Controls.Add(pnlBackground); + DoubleBuffered = true; + helpProvider.SetHelpKeyword(this, "Highlighting.htm"); + helpProvider.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); + helpProvider.SetHelpString(this, ""); + Icon = (Icon)resources.GetObject("$this.Icon"); + Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + MaximizeBox = false; + MinimizeBox = false; + MinimumSize = new Size(660, 934); + Name = "HighlightDialog"; + helpProvider.SetShowHelp(this, true); + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Highlighting and action triggers"; + Shown += OnHighlightDialogShown; + groupBoxLineMatchCriteria.ResumeLayout(false); + groupBoxLineMatchCriteria.PerformLayout(); + groupBoxColoring.ResumeLayout(false); + groupBoxColoring.PerformLayout(); + groupBoxActions.ResumeLayout(false); + groupBoxActions.PerformLayout(); + groupBox4.ResumeLayout(false); + groupBox4.PerformLayout(); + pnlBackground.ResumeLayout(false); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.ListBox listBoxHighlight; + private System.Windows.Forms.Button btnAdd; + private System.Windows.Forms.Button btnDelete; + private System.Windows.Forms.Button btnMoveUp; + private System.Windows.Forms.Button btnMoveDown; + private ColorComboBox colorBoxForeground; + private System.Windows.Forms.Label labelForgroundColor; + private ColorComboBox colorBoxBackground; + private System.Windows.Forms.Label labelBackgroundColor; + private System.Windows.Forms.Button btnOk; + private System.Windows.Forms.Button btnCancel; + private System.Windows.Forms.TextBox textBoxSearchString; + private System.Windows.Forms.Label labelSearchString; + private System.Windows.Forms.Button btnApply; + private System.Windows.Forms.Button btnCustomForeColor; + private System.Windows.Forms.Button btnCustomBackColor; + private System.Windows.Forms.CheckBox checkBoxRegex; + private System.Windows.Forms.CheckBox checkBoxCaseSensitive; + private System.Windows.Forms.CheckBox checkBoxDontDirtyLed; + private System.Windows.Forms.GroupBox groupBoxLineMatchCriteria; + private System.Windows.Forms.GroupBox groupBoxColoring; + private System.Windows.Forms.GroupBox groupBoxActions; + private System.Windows.Forms.CheckBox checkBoxBookmark; + private System.Windows.Forms.CheckBox checkBoxStopTail; + private System.Windows.Forms.HelpProvider helpProvider; + private System.Windows.Forms.CheckBox checkBoxPlugin; + private System.Windows.Forms.Button btnSelectPlugin; + private System.Windows.Forms.Button btnBookmarkComment; + private System.Windows.Forms.GroupBox groupBox4; + private System.Windows.Forms.ComboBox comboBoxGroups; + private System.Windows.Forms.Button btnDeleteGroup; + private System.Windows.Forms.Button btnNewGroup; + private System.Windows.Forms.Button btnCopyGroup; + private System.Windows.Forms.ToolTip toolTip; + private System.Windows.Forms.Label labelAssignNamesToGroups; + private System.Windows.Forms.Button btnMoveGroupUp; + private System.Windows.Forms.Button btnMoveGroupDown; + private System.Windows.Forms.CheckBox checkBoxWordMatch; + private System.Windows.Forms.CheckBox checkBoxBold; + private System.Windows.Forms.CheckBox checkBoxNoBackground; + private System.Windows.Forms.Button btnImportGroup; + private System.Windows.Forms.Button btnExportGroup; + private System.Windows.Forms.Panel pnlBackground; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs new file mode 100644 index 00000000..d772f4da --- /dev/null +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.cs @@ -0,0 +1,739 @@ +using System.Runtime.Versioning; +using System.Text.RegularExpressions; + +using LogExpert.Core.Classes.Highlight; +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; +using LogExpert.UI.Controls; +using LogExpert.UI.Dialogs; +using LogExpert.UI.Entities; + +using NLog; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class HighlightDialog : Form +{ + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + + #region Private Fields + + private readonly Image _applyButtonImage; + private string _bookmarkComment; + private ActionEntry _currentActionEntry = new(); + private HighlightGroup _currentGroup; + private List _highlightGroupList; + + #endregion + + #region Ctor + + public HighlightDialog (IConfigManager configManager) + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + ConfigManager = configManager; + Load += OnHighlightDialogLoad; + listBoxHighlight.DrawItem += OnHighlightListBoxDrawItem; + _applyButtonImage = btnApply.Image; + btnApply.Image = null; + } + + #endregion + + #region Properties / Indexers + + public List HighlightGroupList + { + get => _highlightGroupList; + set + { + _highlightGroupList ??= []; + + foreach (var group in value) + { + _highlightGroupList.Add((HighlightGroup)group.Clone()); + } + } + } + + public IList KeywordActionList { get; set; } + + public string PreSelectedGroupName { get; set; } + + private bool IsDirty => btnApply.Image == _applyButtonImage; + + private IConfigManager ConfigManager { get; } + + #endregion + + #region Event handling Methods + + private void OnAddButtonClick (object sender, EventArgs e) + { + AddNewEntry(); + Dirty(); + } + + private void OnBtnApplyClick (object sender, EventArgs e) + { + SaveEntry(); + } + + private void OnBtnBookmarkCommentClick (object sender, EventArgs e) + { + BookmarkCommentDlg dlg = new(); + dlg.Comment = _bookmarkComment; + if (dlg.ShowDialog() == DialogResult.OK) + { + _bookmarkComment = dlg.Comment; + Dirty(); + } + } + + private void OnBtnCopyGroupClick (object sender, EventArgs e) + { + if (comboBoxGroups.SelectedIndex >= 0 && comboBoxGroups.SelectedIndex < HighlightGroupList.Count) + { + var newGroup = (HighlightGroup)HighlightGroupList[comboBoxGroups.SelectedIndex].Clone(); + newGroup.GroupName = "Copy of " + newGroup.GroupName; + + HighlightGroupList.Add(newGroup); + FillGroupComboBox(); + SelectGroup(HighlightGroupList.Count - 1); + } + } + + private void OnBtnCustomBackColorClick (object sender, EventArgs e) + { + ChooseColor(colorBoxBackground); + Dirty(); + } + + private void OnBtnCustomForeColorClick (object sender, EventArgs e) + { + ChooseColor(colorBoxForeground); + Dirty(); + } + + private void OnBtnDelGroupClick (object sender, EventArgs e) + { + // the last group cannot be deleted + if (HighlightGroupList.Count == 1) + { + return; + } + + if (comboBoxGroups.SelectedIndex >= 0 && comboBoxGroups.SelectedIndex < HighlightGroupList.Count) + { + var index = comboBoxGroups.SelectedIndex; + HighlightGroupList.RemoveAt(comboBoxGroups.SelectedIndex); + FillGroupComboBox(); + if (index < HighlightGroupList.Count) + { + SelectGroup(index); + } + else + { + SelectGroup(HighlightGroupList.Count - 1); + } + } + } + + //TODO: This class should not knoow ConfigManager? + private void OnBtnExportGroupClick (object sender, EventArgs e) + { + SaveFileDialog dlg = new() + { + Title = @"Export Settings to file", + DefaultExt = "json", + AddExtension = true, + Filter = @"Settings (*.json)|*.json|All files (*.*)|*.*" + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + FileInfo fileInfo = new(dlg.FileName); + ConfigManager.Export(fileInfo, Core.Config.SettingsFlags.HighlightSettings); + } + } + + private void OnBtnGroupDownClick (object sender, EventArgs e) + { + var index = comboBoxGroups.SelectedIndex; + if (index > -1 && index < _highlightGroupList.Count - 1) + { + _highlightGroupList.Reverse(index, 2); + comboBoxGroups.Refresh(); + FillGroupComboBox(); + SelectGroup(index + 1); + } + } + + private void OnBtnGroupUpClick (object sender, EventArgs e) + { + var index = comboBoxGroups.SelectedIndex; + if (index > 0) + { + _highlightGroupList.Reverse(index - 1, 2); + comboBoxGroups.Refresh(); + FillGroupComboBox(); + SelectGroup(index - 1); + } + } + + private void OnBtnImportGroupClick (object sender, EventArgs e) + { + ImportSettingsDialog dlg = new(Core.Config.ExportImportFlags.HighlightSettings); + + foreach (Control ctl in dlg.groupBoxImportOptions.Controls) + { + if (ctl.Tag != null) + { + ((CheckBox)ctl).Checked = false; + } + } + + dlg.checkBoxHighlightSettings.Checked = true; + dlg.checkBoxKeepExistingSettings.Checked = true; + + if (dlg.ShowDialog() != DialogResult.OK) + { + return; + } + + if (string.IsNullOrWhiteSpace(dlg.FileName)) + { + return; + } + + Cursor.Current = Cursors.WaitCursor; + + FileInfo fileInfo; + + try + { + fileInfo = new FileInfo(dlg.FileName); + } + catch (Exception ex) + { + MessageBox.Show(this, $@"Settings could not be imported: {ex}", @"LogExpert"); + _logger.Error($"Error while trying to access file: {dlg.FileName}: {ex}"); + return; + } + + ConfigManager.ImportHighlightSettings(fileInfo, dlg.ImportFlags); + Cursor.Current = Cursors.Default; + + _highlightGroupList = ConfigManager.Settings.Preferences.HighlightGroupList; + + FillGroupComboBox(); + + MessageBox.Show(this, @"Settings imported", @"LogExpert"); + } + + private void OnBtnMoveDownClick (object sender, EventArgs e) + { + var index = listBoxHighlight.SelectedIndex; + + if (index > -1 && index < listBoxHighlight.Items.Count - 1) + { + var item = listBoxHighlight.SelectedItem; + listBoxHighlight.Items.RemoveAt(index); + listBoxHighlight.Items.Insert(index + 1, item); + listBoxHighlight.SelectedIndex = index + 1; + _currentGroup.HighlightEntryList.Reverse(index, 2); + } + } + + private void OnBtnMoveUpClick (object sender, EventArgs e) + { + var index = listBoxHighlight.SelectedIndex; + if (index > 0) + { + var item = listBoxHighlight.SelectedItem; + listBoxHighlight.Items.RemoveAt(index); // will also clear the selection + listBoxHighlight.Items.Insert(index - 1, item); + listBoxHighlight.SelectedIndex = index - 1; // restore the selection + _currentGroup.HighlightEntryList.Reverse(index - 1, 2); + } + } + + private void OnBtnNewGroupClick (object sender, EventArgs e) + { + // Propose a unique name + const string baseName = "New group"; + var name = baseName; + var uniqueName = false; + var i = 1; + while (!uniqueName) + { + uniqueName = HighlightGroupList.FindIndex(delegate (HighlightGroup g) + { return g.GroupName == name; }) < 0; + + if (!uniqueName) + { + name = $"{baseName} #{i++}"; + } + } + + HighlightGroup newGroup = new() { GroupName = name }; + HighlightGroupList.Add(newGroup); + FillGroupComboBox(); + SelectGroup(HighlightGroupList.Count - 1); + } + + private void OnBtnOkClick (object sender, EventArgs e) + { + // Apply pending changes if closing the form. + if (IsDirty) + { + // cannot call 'this.applyButton.PerformClick();' because it prohibits the OK button to terminate the dialog + OnBtnApplyClick(btnApply, EventArgs.Empty); + } + } + + private void OnChkBoxBoldCheckedChanged (object sender, EventArgs e) + { + Dirty(); + } + + private void OnChkBoxNoBackgroundCheckedChanged (object sender, EventArgs e) + { + colorBoxBackground.Enabled = !checkBoxNoBackground.Checked; + btnCustomBackColor.Enabled = !checkBoxNoBackground.Checked; + Dirty(); + } + + private void OnChkBoxPluginCheckedChanged (object sender, EventArgs e) + { + Dirty(); + btnSelectPlugin.Enabled = checkBoxPlugin.Checked; + } + + private void OnChkBoxRegexMouseUp (object sender, MouseEventArgs e) + { + if (e.Button == MouseButtons.Right) + { + RegexHelperDialog dlg = new() + { + Owner = this, + CaseSensitive = checkBoxCaseSensitive.Checked, + Pattern = textBoxSearchString.Text + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + checkBoxCaseSensitive.Checked = dlg.CaseSensitive; + textBoxSearchString.Text = dlg.Pattern; + } + } + } + + private void OnChkBoxWordMatchCheckedChanged (object sender, EventArgs e) + { + Dirty(); + checkBoxNoBackground.Enabled = checkBoxWordMatch.Checked; + } + + private void OnCmbBoxGroupDrawItem (object sender, DrawItemEventArgs e) + { + e.DrawBackground(); + if (e.Index >= 0) + { + HighlightGroup group = HighlightGroupList[e.Index]; + Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); + + Brush brush = new SolidBrush(SystemColors.ControlText); + e.Graphics.DrawString(group.GroupName, e.Font, brush, new PointF(rectangle.Left, rectangle.Top)); + e.DrawFocusRectangle(); + brush.Dispose(); + } + } + + private void OnCmbBoxGroupSelectionChangeCommitted (object sender, EventArgs e) + { + SelectGroup(comboBoxGroups.SelectedIndex); + } + + private void OnCmbBoxGroupTextUpdate (object sender, EventArgs e) + { + _currentGroup.GroupName = comboBoxGroups.Text; + } + + private void OnDeleteButtonClick (object sender, EventArgs e) + { + if (listBoxHighlight.SelectedIndex >= 0) + { + var removeIndex = listBoxHighlight.SelectedIndex; + _currentGroup.HighlightEntryList.RemoveAt(removeIndex); + listBoxHighlight.Items.RemoveAt(removeIndex); + + // Select previous (or first if none before) + var nextSelectIndex = removeIndex; + if (nextSelectIndex >= listBoxHighlight.Items.Count) + { + nextSelectIndex--; // if last item was removed, go one up + } + + if (nextSelectIndex >= 0) + { + listBoxHighlight.SelectedIndex = nextSelectIndex; // if still some item, select it + } + + ReEvaluateHighlightButtonStates(); + } + } + + private void OnHighlightDialogLoad (object sender, EventArgs e) + { + colorBoxForeground.SelectedIndex = 1; + colorBoxBackground.SelectedIndex = 2; + btnApply.Enabled = false; + btnApply.Image = null; + btnBookmarkComment.Enabled = false; + btnSelectPlugin.Enabled = false; + + ReEvaluateHighlightButtonStates(); + } + + private void OnHighlightDialogShown (object sender, EventArgs e) + { + InitData(); + } + + private void OnHighlightListBoxDrawItem (object sender, DrawItemEventArgs e) + { + e.DrawBackground(); + if (e.Index >= 0) + { + var entry = (HighlightEntry)listBoxHighlight.Items[e.Index]; + Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); + + SolidBrush foregroundBrush; + + if (e.State.HasFlag(DrawItemState.Selected)) + { + 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); + } + + using (foregroundBrush) + { + e.Graphics.DrawString(entry.SearchText, e.Font, foregroundBrush, new PointF(rectangle.Left, rectangle.Top)); + } + + e.DrawFocusRectangle(); + } + } + + private void OnListBoxHighlightSelectedIndexChanged (object sender, EventArgs e) + { + StartEditEntry(); + } + + private void OnPluginButtonClick (object sender, EventArgs e) + { + KeywordActionDlg dlg = new(_currentActionEntry, KeywordActionList); + + if (dlg.ShowDialog() == DialogResult.OK) + { + _currentActionEntry = dlg.ActionEntry; + Dirty(); + } + } + + #endregion + + #region Private Methods + + private void AddNewEntry () + { + { + try + { + CheckRegex(); + + HighlightEntry entry = new() + { + SearchText = textBoxSearchString.Text, + ForegroundColor = colorBoxForeground.SelectedColor, + BackgroundColor = colorBoxBackground.SelectedColor, + IsRegEx = checkBoxRegex.Checked, + IsCaseSensitive = checkBoxCaseSensitive.Checked, + IsLedSwitch = checkBoxDontDirtyLed.Checked, + IsStopTail = checkBoxStopTail.Checked, + IsSetBookmark = checkBoxBookmark.Checked, + IsActionEntry = checkBoxPlugin.Checked, + ActionEntry = _currentActionEntry, + IsWordMatch = checkBoxWordMatch.Checked, + IsBold = checkBoxBold.Checked, + NoBackground = checkBoxNoBackground.Checked + }; + + listBoxHighlight.Items.Add(entry); + + // Select the newly created item + _currentGroup.HighlightEntryList.Add(entry); + listBoxHighlight.SelectedItem = entry; + } + catch (Exception ex) + { + _logger.Error(ex, "Error during add of highlight entry"); + MessageBox.Show($"Error during add of entry.\r\n{ex.Message}"); + } + } + } + + private void ChangeToDirty (object sender, EventArgs e) + { + Dirty(); + } + + private void CheckRegex () + { + if (checkBoxRegex.Checked) + { + if (string.IsNullOrWhiteSpace(textBoxSearchString.Text)) + { + throw new ArgumentException("Regex value is null or whitespace"); + } + + // ReSharper disable once ReturnValueOfPureMethodIsNotUsed + Regex.IsMatch("", textBoxSearchString.Text); + } + } + + private void ChooseColor (ColorComboBox comboBox) + { + ColorDialog colorDialog = new(); + colorDialog.AllowFullOpen = true; + colorDialog.ShowHelp = false; + colorDialog.Color = comboBox.CustomColor; + if (colorDialog.ShowDialog() == DialogResult.OK) + { + comboBox.CustomColor = colorDialog.Color; + comboBox.SelectedIndex = 0; + } + } + + private void Dirty () + { + var index = listBoxHighlight.SelectedIndex; + if (index > -1) + { + btnApply.Enabled = true; + btnApply.Image = _applyButtonImage; + } + + btnAdd.Enabled = textBoxSearchString.Text.Length > 0; + } + + private void FillGroupComboBox () + { + SelectGroup(-1); + + comboBoxGroups.Items.Clear(); + + foreach (HighlightGroup group in HighlightGroupList) + { + comboBoxGroups.Items.Add(group); + } + + ReEvaluateGroupButtonStates(); + } + + private void FillHighlightListBox () + { + listBoxHighlight.Items.Clear(); + if (_currentGroup != null) + { + foreach (HighlightEntry entry in _currentGroup.HighlightEntryList) + { + listBoxHighlight.Items.Add(entry); + } + } + } + + private void InitData () + { + const string def = "[Default]"; + HighlightGroupList ??= []; + + if (HighlightGroupList.Count == 0) + { + HighlightGroup highlightGroup = new() + { + GroupName = def, + HighlightEntryList = [] + }; + + HighlightGroupList.Add(highlightGroup); + } + + FillGroupComboBox(); + + _currentGroup = null; + var groupToSelect = PreSelectedGroupName; + if (string.IsNullOrEmpty(groupToSelect)) + { + groupToSelect = def; + } + + foreach (HighlightGroup group in HighlightGroupList) + { + if (group.GroupName.Equals(groupToSelect, StringComparison.Ordinal)) + { + _currentGroup = group; + comboBoxGroups.SelectedValue = group; + comboBoxGroups.SelectedIndex = HighlightGroupList.IndexOf(group); + break; + } + } + + ReEvaluateGroupButtonStates(); + + FillHighlightListBox(); + } + + private void ReEvaluateGroupButtonStates () + { + // Refresh button states based on the selection in the combobox + var atLeastOneSelected = comboBoxGroups.SelectedItem != null; + var moreThanOne = comboBoxGroups.Items.Count > 1; + var firstSelected = atLeastOneSelected && comboBoxGroups.SelectedIndex == 0; + var lastSelected = atLeastOneSelected && comboBoxGroups.SelectedIndex == comboBoxGroups.Items.Count - 1; + + btnDeleteGroup.Enabled = atLeastOneSelected; + btnCopyGroup.Enabled = atLeastOneSelected; + btnMoveGroupUp.Enabled = atLeastOneSelected && moreThanOne && !firstSelected; + btnMoveGroupDown.Enabled = atLeastOneSelected && moreThanOne && !lastSelected; + } + + private void ReEvaluateHighlightButtonStates () + { + // Refresh button states based on the selection in the combobox + var atLeastOneSelected = listBoxHighlight.SelectedItem != null; + var moreThanOne = listBoxHighlight.Items.Count > 1; + var firstSelected = atLeastOneSelected && listBoxHighlight.SelectedIndex == 0; + var lastSelected = atLeastOneSelected && listBoxHighlight.SelectedIndex == listBoxHighlight.Items.Count - 1; + + btnDelete.Enabled = atLeastOneSelected; + btnMoveUp.Enabled = atLeastOneSelected && moreThanOne && !firstSelected; + btnMoveDown.Enabled = atLeastOneSelected && moreThanOne && !lastSelected; + } + + private void SaveEntry () + { + try + { + CheckRegex(); + + var entry = (HighlightEntry)listBoxHighlight.SelectedItem; + + entry.ForegroundColor = (Color)colorBoxForeground.SelectedItem; + entry.BackgroundColor = (Color)colorBoxBackground.SelectedItem; + entry.SearchText = textBoxSearchString.Text; + entry.IsRegEx = checkBoxRegex.Checked; + entry.IsCaseSensitive = checkBoxCaseSensitive.Checked; + btnApply.Enabled = false; + btnApply.Image = null; + entry.IsLedSwitch = checkBoxDontDirtyLed.Checked; + entry.IsSetBookmark = checkBoxBookmark.Checked; + entry.IsStopTail = checkBoxStopTail.Checked; + entry.IsActionEntry = checkBoxPlugin.Checked; + entry.ActionEntry = (ActionEntry)_currentActionEntry.Clone(); + entry.BookmarkComment = _bookmarkComment; + entry.IsWordMatch = checkBoxWordMatch.Checked; + entry.IsBold = checkBoxBold.Checked; + entry.NoBackground = checkBoxNoBackground.Checked; + listBoxHighlight.Refresh(); + } + catch (Exception ex) + { + _logger.Error(ex, "Error during save of save highlight entry"); + MessageBox.Show($"Error during save of entry.\r\n{ex.Message}"); + } + } + + private void SelectGroup (int index) + { + if (index >= 0 && index < HighlightGroupList.Count) + { + _currentGroup = HighlightGroupList[index]; + comboBoxGroups.Items[index] = _currentGroup; + comboBoxGroups.SelectedIndex = index; + comboBoxGroups.SelectedItem = _currentGroup; + FillHighlightListBox(); + } + else + { + comboBoxGroups.SelectedItem = null; + _currentGroup = null; + listBoxHighlight.Items.Clear(); + } + + ReEvaluateHighlightButtonStates(); + ReEvaluateGroupButtonStates(); + } + + private void StartEditEntry () + { + var entry = (HighlightEntry)listBoxHighlight.SelectedItem; + + if (entry != null) + { + textBoxSearchString.Text = entry.SearchText; + + colorBoxForeground.CustomColor = entry.ForegroundColor; + colorBoxBackground.CustomColor = entry.BackgroundColor; + + if (colorBoxForeground.Items.Contains(entry.ForegroundColor)) + { + colorBoxForeground.SelectedIndex = colorBoxForeground.Items.Cast().ToList().LastIndexOf(entry.ForegroundColor); + } + else + { + colorBoxForeground.SelectedItem = entry.ForegroundColor; + } + + if (colorBoxForeground.Items.Contains(entry.ForegroundColor)) + { + colorBoxBackground.SelectedIndex = colorBoxBackground.Items.Cast().ToList().LastIndexOf(entry.BackgroundColor); + } + else + { + colorBoxBackground.SelectedItem = entry.BackgroundColor; + } + + checkBoxRegex.Checked = entry.IsRegEx; + checkBoxCaseSensitive.Checked = entry.IsCaseSensitive; + checkBoxDontDirtyLed.Checked = entry.IsLedSwitch; + checkBoxBookmark.Checked = entry.IsSetBookmark; + checkBoxStopTail.Checked = entry.IsStopTail; + checkBoxPlugin.Checked = entry.IsActionEntry; + btnSelectPlugin.Enabled = checkBoxPlugin.Checked; + btnBookmarkComment.Enabled = checkBoxBookmark.Checked; + _currentActionEntry = entry.ActionEntry != null ? (ActionEntry)entry.ActionEntry.Clone() : new ActionEntry(); + _bookmarkComment = entry.BookmarkComment; + checkBoxWordMatch.Checked = entry.IsWordMatch; + checkBoxBold.Checked = entry.IsBold; + checkBoxNoBackground.Checked = entry.NoBackground; + } + + btnApply.Enabled = false; + btnApply.Image = null; + + ReEvaluateHighlightButtonStates(); + } + + #endregion +} diff --git a/src/LogExpert/Dialogs/HighlightDialog.resx b/src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.resx similarity index 100% rename from src/LogExpert/Dialogs/HighlightDialog.resx rename to src/LogExpert.UI/Dialogs/LogTabWindow/HighlightDialog.resx diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs new file mode 100644 index 00000000..b75a674c --- /dev/null +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.cs @@ -0,0 +1,3053 @@ +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.Entities; +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 +//TODO: Can we get rid of this class? +[SupportedOSPlatform("windows")] +internal partial class LogTabWindow : Form, ILogTabWindow +{ + #region Fields + + private const int MAX_COLUMNIZER_HISTORY = 40; + private const int MAX_COLOR_HISTORY = 40; + private const int DIFF_MAX = 100; + private const int MAX_FILE_HISTORY = 10; + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + private readonly Icon _deadIcon; + + private readonly Color _defaultTabColor = Color.FromArgb(255, 192, 192, 192); + private readonly Brush _dirtyLedBrush; + + private readonly int _instanceNumber; + private readonly Brush[] _ledBrushes = new Brush[5]; + private readonly Icon[,,,] _ledIcons = new Icon[6, 2, 4, 2]; + + private readonly Rectangle[] _leds = new Rectangle[5]; + + private readonly IList _logWindowList = []; + private readonly Brush _offLedBrush; + private readonly bool _showInstanceNumbers; + + private readonly string[] _startupFileNames; + + private readonly EventWaitHandle _statusLineEventHandle = new AutoResetEvent(false); + private readonly EventWaitHandle _statusLineEventWakeupHandle = new ManualResetEvent(false); + private readonly Brush _syncLedBrush; + + [SupportedOSPlatform("windows")] + private readonly StringFormat _tabStringFormat = new(); + + private readonly Brush[] _tailLedBrush = new Brush[3]; + + private BookmarkWindow _bookmarkWindow; + + private LogWindow.LogWindow _currentLogWindow; + private bool _firstBookmarkWindowShow = true; + + private Thread _ledThread; + + //Settings settings; + + private bool _shouldStop; + + private bool _skipEvents; + + private bool _wasMaximized; + + #endregion + + #region cTor + + [SupportedOSPlatform("windows")] + public LogTabWindow (string[] fileNames, int instanceNumber, bool showInstanceNumbers, IConfigManager configManager) + { + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + InitializeComponent(); + + ConfigManager = configManager; + + //Fix MainMenu and externalToolsToolStrip.Location, if the location has unintentionally been changed in the designer + mainMenuStrip.Location = new Point(0, 0); + externalToolsToolStrip.Location = new Point(0, 54); + + _startupFileNames = fileNames; + _instanceNumber = instanceNumber; + _showInstanceNumbers = showInstanceNumbers; + + Load += OnLogTabWindowLoad; + + configManager.Instance.ConfigChanged += OnConfigChanged; + HighlightGroupList = configManager.Settings.Preferences.HighlightGroupList; + + Rectangle led = new(0, 0, 8, 2); + + for (var i = 0; i < _leds.Length; ++i) + { + _leds[i] = led; + led.Offset(0, led.Height + 0); + } + + var grayAlpha = 50; + + _ledBrushes[0] = new SolidBrush(Color.FromArgb(255, 220, 0, 0)); + _ledBrushes[1] = new SolidBrush(Color.FromArgb(255, 220, 220, 0)); + _ledBrushes[2] = new SolidBrush(Color.FromArgb(255, 0, 220, 0)); + _ledBrushes[3] = new SolidBrush(Color.FromArgb(255, 0, 220, 0)); + _ledBrushes[4] = new SolidBrush(Color.FromArgb(255, 0, 220, 0)); + + _offLedBrush = new SolidBrush(Color.FromArgb(grayAlpha, 160, 160, 160)); + + _dirtyLedBrush = new SolidBrush(Color.FromArgb(255, 220, 0, 00)); + + _tailLedBrush[0] = new SolidBrush(Color.FromArgb(255, 50, 100, 250)); // Follow tail: blue-ish + _tailLedBrush[1] = new SolidBrush(Color.FromArgb(grayAlpha, 160, 160, 160)); // Don't follow tail: gray + _tailLedBrush[2] = new SolidBrush(Color.FromArgb(255, 220, 220, 0)); // Stop follow tail (trigger): yellow-ish + + _syncLedBrush = new SolidBrush(Color.FromArgb(255, 250, 145, 30)); + + CreateIcons(); + + _tabStringFormat.LineAlignment = StringAlignment.Center; + _tabStringFormat.Alignment = StringAlignment.Near; + + ToolStripControlHost host = new(checkBoxFollowTail); + + host.Padding = new Padding(20, 0, 0, 0); + host.BackColor = Color.FromKnownColor(KnownColor.Transparent); + + var index = buttonToolStrip.Items.IndexOfKey("toolStripButtonTail"); + + toolStripEncodingASCIIItem.Text = Encoding.ASCII.HeaderName; + toolStripEncodingANSIItem.Text = Encoding.Default.HeaderName; + toolStripEncodingISO88591Item.Text = Encoding.GetEncoding("iso-8859-1").HeaderName; + toolStripEncodingUTF8Item.Text = Encoding.UTF8.HeaderName; + toolStripEncodingUTF16Item.Text = Encoding.Unicode.HeaderName; + + if (index != -1) + { + buttonToolStrip.Items.RemoveAt(index); + buttonToolStrip.Items.Insert(index, host); + } + + dragControlDateTime.Visible = false; + loadProgessBar.Visible = false; + + // get a reference to the current assembly + var a = Assembly.GetExecutingAssembly(); + + // get a list of resource names from the manifest + var resNames = a.GetManifestResourceNames(); + + Bitmap bmp = Resources.Deceased; + _deadIcon = Icon.FromHandle(bmp.GetHicon()); + bmp.Dispose(); + Closing += OnLogTabWindowClosing; + + InitToolWindows(); + } + + #endregion + + #region Delegates + + private delegate void AddFileTabsDelegate (string[] fileNames); + + private delegate void ExceptionFx (); + + private delegate void FileNotFoundDelegate (LogWindow.LogWindow logWin); + + private delegate void FileRespawnedDelegate (LogWindow.LogWindow logWin); + + public delegate void HighlightSettingsChangedEventHandler (object sender, EventArgs e); + + private delegate void LoadMultiFilesDelegate (string[] fileName, EncodingOptions encodingOptions); + + private delegate void SetColumnizerFx (ILogLineColumnizer columnizer); + + private delegate void SetTabIconDelegate (LogWindow.LogWindow logWindow, Icon icon); + + #endregion + + #region Events + + public event HighlightSettingsChangedEventHandler HighlightSettingsChanged; + + #endregion + + #region Properties + + [SupportedOSPlatform("windows")] + public LogWindow.LogWindow CurrentLogWindow + { + get => _currentLogWindow; + set => ChangeCurrentLogWindow(value); + } + + public SearchParams SearchParams { get; private set; } = new SearchParams(); + + public Preferences Preferences => ConfigManager.Settings.Preferences; + + public List HighlightGroupList { get; private set; } = []; + + //public Settings Settings + //{ + // get { return ConfigManager.Settings; } + //} + + public ILogExpertProxy LogExpertProxy { get; set; } + public IConfigManager ConfigManager { get; } + + #endregion + + #region Internals + + internal HighlightGroup FindHighlightGroup (string groupName) + { + lock (HighlightGroupList) + { + foreach (HighlightGroup group in HighlightGroupList) + { + if (group.GroupName.Equals(groupName, StringComparison.Ordinal)) + { + return group; + } + } + + return null; + } + } + + #endregion + + private class LogWindowData + { + #region Fields + + // public MdiTabControl.TabPage tabPage; + + public Color Color { get; set; } = Color.FromKnownColor(KnownColor.Gray); + + public int DiffSum { get; set; } + + public bool Dirty { get; set; } + + // tailState: + /// + /// 0 = on

+ /// 1 = off

+ /// 2 = off by Trigger

+ ///
+ public int TailState { get; set; } + + public ToolTip ToolTip { get; set; } + + /// + /// 0 = off

+ /// 1 = timeSynced + ///
+ public int SyncMode { get; set; } + + #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.CurrentLineNum; + 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) + { + // (shift pressed) https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.drageventargs.keystate + LoadFiles(names, (e.KeyState & 4) == 4); + 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/Controls/LogTabWindow/LogTabWindow.designer.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs similarity index 88% rename from src/LogExpert/Controls/LogTabWindow/LogTabWindow.designer.cs rename to src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs index 45393abd..2b322b27 100644 --- a/src/LogExpert/Controls/LogTabWindow/LogTabWindow.designer.cs +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.designer.cs @@ -1,1286 +1,1292 @@ -using System.Windows.Forms; -using LogExpert.Dialogs; -using LogExpert.Extensions.Forms; -using LogExpert.Properties; - -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.Controls.LogTabWindow -{ - partial class LogTabWindow - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - DockPanelSkin dockPanelSkin1 = new DockPanelSkin(); - AutoHideStripSkin autoHideStripSkin1 = new AutoHideStripSkin(); - DockPanelGradient dockPanelGradient1 = new DockPanelGradient(); - TabGradient tabGradient1 = new TabGradient(); - DockPaneStripSkin dockPaneStripSkin1 = new DockPaneStripSkin(); - DockPaneStripGradient dockPaneStripGradient1 = new DockPaneStripGradient(); - TabGradient tabGradient2 = new TabGradient(); - DockPanelGradient dockPanelGradient2 = new DockPanelGradient(); - TabGradient tabGradient3 = new TabGradient(); - DockPaneStripToolWindowGradient dockPaneStripToolWindowGradient1 = new DockPaneStripToolWindowGradient(); - TabGradient tabGradient4 = new TabGradient(); - TabGradient tabGradient5 = new TabGradient(); - DockPanelGradient dockPanelGradient3 = new DockPanelGradient(); - TabGradient tabGradient6 = new TabGradient(); - TabGradient tabGradient7 = new TabGradient(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LogTabWindow)); - statusStrip = new StatusStrip(); - labelLines = new ToolStripStatusLabel(); - labelSize = new ToolStripStatusLabel(); - labelCurrentLine = new ToolStripStatusLabel(); - loadProgessBar = new ToolStripProgressBar(); - labelStatus = new ToolStripStatusLabel(); - mainMenuStrip = new MenuStrip(); - fileToolStripMenuItem = new ToolStripMenuItem(); - openToolStripMenuItem = new ToolStripMenuItem(); - openURIToolStripMenuItem = new ToolStripMenuItem(); - closeFileToolStripMenuItem = new ToolStripMenuItem(); - reloadToolStripMenuItem = new ToolStripMenuItem(); - newFromClipboardToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension1 = new MenuToolStripSeparatorExtension(); - multiFileToolStripMenuItem = new ToolStripMenuItem(); - multiFileEnabledStripMenuItem = new ToolStripMenuItem(); - multifileMaskToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension2 = new MenuToolStripSeparatorExtension(); - loadProjectToolStripMenuItem = new ToolStripMenuItem(); - saveProjectToolStripMenuItem = new ToolStripMenuItem(); - exportBookmarksToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension3 = new MenuToolStripSeparatorExtension(); - lastUsedToolStripMenuItem = new ToolStripMenuItem(); - exitToolStripMenuItem = new ToolStripMenuItem(); - viewNavigateToolStripMenuItem = new ToolStripMenuItem(); - goToLineToolStripMenuItem = new ToolStripMenuItem(); - searchToolStripMenuItem = new ToolStripMenuItem(); - filterToolStripMenuItem = new ToolStripMenuItem(); - bookmarksToolStripMenuItem = new ToolStripMenuItem(); - toggleBookmarkToolStripMenuItem = new ToolStripMenuItem(); - jumpToNextToolStripMenuItem = new ToolStripMenuItem(); - jumpToPrevToolStripMenuItem = new ToolStripMenuItem(); - showBookmarkListToolStripMenuItem = new ToolStripMenuItem(); - columnFinderToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension5 = new MenuToolStripSeparatorExtension(); - toolStripEncodingMenuItem = new ToolStripMenuItem(); - toolStripEncodingASCIIItem = new ToolStripMenuItem(); - toolStripEncodingANSIItem = new ToolStripMenuItem(); - toolStripEncodingISO88591Item = new ToolStripMenuItem(); - toolStripEncodingUTF8Item = new ToolStripMenuItem(); - toolStripEncodingUTF16Item = new ToolStripMenuItem(); - menuToolStripSeparatorExtension6 = new MenuToolStripSeparatorExtension(); - timeshiftToolStripMenuItem = new ToolStripMenuItem(); - timeshiftMenuTextBox = new ToolStripTextBox(); - menuToolStripSeparatorExtension4 = new MenuToolStripSeparatorExtension(); - copyMarkedLinesIntoNewTabToolStripMenuItem = new ToolStripMenuItem(); - optionToolStripMenuItem = new ToolStripMenuItem(); - columnizerToolStripMenuItem = new ToolStripMenuItem(); - hilightingToolStripMenuItem1 = new ToolStripMenuItem(); - menuToolStripSeparatorExtension7 = new MenuToolStripSeparatorExtension(); - settingsToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension9 = new MenuToolStripSeparatorExtension(); - cellSelectModeToolStripMenuItem = new ToolStripMenuItem(); - alwaysOnTopToolStripMenuItem = new ToolStripMenuItem(); - hideLineColumnToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension8 = new MenuToolStripSeparatorExtension(); - lockInstanceToolStripMenuItem = new ToolStripMenuItem(); - toolsToolStripMenuItem = new ToolStripMenuItem(); - configureToolStripMenuItem = new ToolStripMenuItem(); - configureToolStripSeparator = new MenuToolStripSeparatorExtension(); - helpToolStripMenuItem = new ToolStripMenuItem(); - showHelpToolStripMenuItem = new ToolStripMenuItem(); - menuToolStripSeparatorExtension11 = new MenuToolStripSeparatorExtension(); - aboutToolStripMenuItem = new ToolStripMenuItem(); - debugToolStripMenuItem = new ToolStripMenuItem(); - dumpLogBufferInfoToolStripMenuItem = new ToolStripMenuItem(); - dumpBufferDiagnosticToolStripMenuItem = new ToolStripMenuItem(); - runGCToolStripMenuItem = new ToolStripMenuItem(); - gCInfoToolStripMenuItem = new ToolStripMenuItem(); - throwExceptionGUIThreadToolStripMenuItem = new ToolStripMenuItem(); - throwExceptionbackgroundThToolStripMenuItem = new ToolStripMenuItem(); - throwExceptionBackgroundThreadToolStripMenuItem = new ToolStripMenuItem(); - loglevelToolStripMenuItem = new ToolStripMenuItem(); - warnToolStripMenuItem = new ToolStripMenuItem(); - infoToolStripMenuItem = new ToolStripMenuItem(); - debugToolStripMenuItem1 = new ToolStripMenuItem(); - disableWordHighlightModeToolStripMenuItem = new ToolStripMenuItem(); - host = new CheckBox(); - toolStripContainer = new ToolStripContainer(); - dockPanel = new DockPanel(); - externalToolsToolStrip = new ToolStrip(); - buttonToolStrip = new ToolStrip(); - toolStripButtonOpen = new ToolStripButton(); - lineToolStripSeparatorExtension1 = new LineToolStripSeparatorExtension(); - toolStripButtonSearch = new ToolStripButton(); - toolStripButtonFilter = new ToolStripButton(); - lineToolStripSeparatorExtension2 = new LineToolStripSeparatorExtension(); - toolStripButtonBookmark = new ToolStripButton(); - toolStripButtonUp = new ToolStripButton(); - toolStripButtonDown = new ToolStripButton(); - lineToolStripSeparatorExtension3 = new LineToolStripSeparatorExtension(); - toolStripButtonBubbles = new ToolStripButton(); - lineToolStripSeparatorExtension4 = new LineToolStripSeparatorExtension(); - toolStripButtonTail = new ToolStripButton(); - lineToolStripSeparatorExtension5 = new LineToolStripSeparatorExtension(); - groupsComboBoxHighlightGroups = new ToolStripComboBox(); - checkBoxFollowTail = new CheckBox(); - tabContextMenuStrip = new ContextMenuStrip(components); - closeThisTabToolStripMenuItem = new ToolStripMenuItem(); - closeOtherTabsToolStripMenuItem = new ToolStripMenuItem(); - closeAllTabsToolStripMenuItem = new ToolStripMenuItem(); - tabColorToolStripMenuItem = new ToolStripMenuItem(); - tabRenameToolStripMenuItem = new ToolStripMenuItem(); - copyPathToClipboardToolStripMenuItem = new ToolStripMenuItem(); - findInExplorerToolStripMenuItem = new ToolStripMenuItem(); - dragControlDateTime = new DateTimeDragControl(); - statusStrip.SuspendLayout(); - mainMenuStrip.SuspendLayout(); - toolStripContainer.ContentPanel.SuspendLayout(); - toolStripContainer.TopToolStripPanel.SuspendLayout(); - toolStripContainer.SuspendLayout(); - buttonToolStrip.SuspendLayout(); - tabContextMenuStrip.SuspendLayout(); - SuspendLayout(); - // - // statusStrip - // - statusStrip.AutoSize = false; - statusStrip.ImageScalingSize = new System.Drawing.Size(24, 24); - statusStrip.Items.AddRange(new ToolStripItem[] { labelLines, labelSize, labelCurrentLine, loadProgessBar, labelStatus }); - 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.SizingGrip = false; - statusStrip.TabIndex = 5; - statusStrip.Text = "statusStrip1"; - // - // labelLines - // - labelLines.AutoSize = false; - 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.Text = "0"; - // - // labelSize - // - labelSize.AutoSize = false; - 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.Text = "0"; - // - // labelCurrentLine - // - labelCurrentLine.AutoSize = false; - 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.Text = "L:"; - // - // loadProgessBar - // - loadProgessBar.Name = "loadProgessBar"; - loadProgessBar.Size = new System.Drawing.Size(83, 57); - // - // labelStatus - // - labelStatus.Name = "labelStatus"; - labelStatus.Size = new System.Drawing.Size(39, 58); - labelStatus.Text = "Ready"; - // - // mainMenuStrip - // - mainMenuStrip.AllowMerge = false; - mainMenuStrip.Dock = DockStyle.None; - mainMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); - mainMenuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem, viewNavigateToolStripMenuItem, optionToolStripMenuItem, toolsToolStripMenuItem, helpToolStripMenuItem, debugToolStripMenuItem }); - mainMenuStrip.LayoutStyle = ToolStripLayoutStyle.Flow; - mainMenuStrip.Location = new System.Drawing.Point(0, 19); - mainMenuStrip.Name = "mainMenuStrip"; - mainMenuStrip.Size = new System.Drawing.Size(1603, 23); - mainMenuStrip.TabIndex = 6; - mainMenuStrip.Text = "menuStrip1"; - // - // fileToolStripMenuItem - // - fileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { openToolStripMenuItem, openURIToolStripMenuItem, closeFileToolStripMenuItem, reloadToolStripMenuItem, newFromClipboardToolStripMenuItem, menuToolStripSeparatorExtension1, multiFileToolStripMenuItem, menuToolStripSeparatorExtension2, loadProjectToolStripMenuItem, saveProjectToolStripMenuItem, exportBookmarksToolStripMenuItem, menuToolStripSeparatorExtension3, lastUsedToolStripMenuItem, exitToolStripMenuItem }); - fileToolStripMenuItem.Name = "fileToolStripMenuItem"; - fileToolStripMenuItem.Size = new System.Drawing.Size(37, 19); - fileToolStripMenuItem.Text = "File"; - fileToolStripMenuItem.DropDownOpening += OnFileToolStripMenuItemDropDownOpening; - // - // openToolStripMenuItem - // - openToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - openToolStripMenuItem.Image = Resources.File_open; - openToolStripMenuItem.Name = "openToolStripMenuItem"; - openToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.O; - openToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - openToolStripMenuItem.Text = "Open..."; - openToolStripMenuItem.Click += OnOpenToolStripMenuItemClick; - // - // openURIToolStripMenuItem - // - openURIToolStripMenuItem.Name = "openURIToolStripMenuItem"; - openURIToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.U; - openURIToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - openURIToolStripMenuItem.Text = "Open URL..."; - openURIToolStripMenuItem.ToolTipText = "Opens a file by entering a URL which is supported by a file system plugin"; - openURIToolStripMenuItem.Click += OnOpenURIToolStripMenuItemClick; - // - // closeFileToolStripMenuItem - // - closeFileToolStripMenuItem.Image = Resources.Close; - closeFileToolStripMenuItem.Name = "closeFileToolStripMenuItem"; - closeFileToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F4; - closeFileToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - closeFileToolStripMenuItem.Text = "Close File"; - closeFileToolStripMenuItem.Click += OnCloseFileToolStripMenuItemClick; - // - // reloadToolStripMenuItem - // - reloadToolStripMenuItem.Image = Resources.Restart_alt; - reloadToolStripMenuItem.Name = "reloadToolStripMenuItem"; - reloadToolStripMenuItem.ShortcutKeys = Keys.F5; - reloadToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - reloadToolStripMenuItem.Text = "Reload"; - reloadToolStripMenuItem.Click += OnReloadToolStripMenuItemClick; - // - // newFromClipboardToolStripMenuItem - // - newFromClipboardToolStripMenuItem.Name = "newFromClipboardToolStripMenuItem"; - newFromClipboardToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.N; - newFromClipboardToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - newFromClipboardToolStripMenuItem.Text = "New tab from clipboard"; - newFromClipboardToolStripMenuItem.ToolTipText = "Creates a new tab with content from clipboard"; - newFromClipboardToolStripMenuItem.Click += OnNewFromClipboardToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension1 - // - menuToolStripSeparatorExtension1.Name = "menuToolStripSeparatorExtension1"; - menuToolStripSeparatorExtension1.Size = new System.Drawing.Size(250, 6); - // - // multiFileToolStripMenuItem - // - multiFileToolStripMenuItem.CheckOnClick = true; - multiFileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { multiFileEnabledStripMenuItem, multifileMaskToolStripMenuItem }); - multiFileToolStripMenuItem.Name = "multiFileToolStripMenuItem"; - multiFileToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - multiFileToolStripMenuItem.Text = "MultiFile"; - multiFileToolStripMenuItem.ToolTipText = "Treat multiple files as one large file (e.g. data.log, data.log.1, data.log.2,...)"; - multiFileToolStripMenuItem.Click += OnMultiFileToolStripMenuItemClick; - // - // multiFileEnabledStripMenuItem - // - multiFileEnabledStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - multiFileEnabledStripMenuItem.CheckOnClick = true; - multiFileEnabledStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - multiFileEnabledStripMenuItem.Name = "multiFileEnabledStripMenuItem"; - multiFileEnabledStripMenuItem.Size = new System.Drawing.Size(165, 22); - multiFileEnabledStripMenuItem.Text = "Enable MultiFile"; - multiFileEnabledStripMenuItem.Click += OnMultiFileEnabledStripMenuItemClick; - // - // multifileMaskToolStripMenuItem - // - multifileMaskToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - multifileMaskToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - multifileMaskToolStripMenuItem.Name = "multifileMaskToolStripMenuItem"; - multifileMaskToolStripMenuItem.Size = new System.Drawing.Size(165, 22); - multifileMaskToolStripMenuItem.Text = "File name mask..."; - multifileMaskToolStripMenuItem.Click += OnMultiFileMaskToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension2 - // - menuToolStripSeparatorExtension2.Name = "menuToolStripSeparatorExtension2"; - menuToolStripSeparatorExtension2.Size = new System.Drawing.Size(250, 6); - // - // loadProjectToolStripMenuItem - // - loadProjectToolStripMenuItem.Name = "loadProjectToolStripMenuItem"; - loadProjectToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - loadProjectToolStripMenuItem.Text = "Load session..."; - loadProjectToolStripMenuItem.ToolTipText = "Load a saved session (list of log files)"; - loadProjectToolStripMenuItem.Click += OnLoadProjectToolStripMenuItemClick; - // - // saveProjectToolStripMenuItem - // - saveProjectToolStripMenuItem.Name = "saveProjectToolStripMenuItem"; - saveProjectToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - saveProjectToolStripMenuItem.Text = "Save session..."; - saveProjectToolStripMenuItem.ToolTipText = "Save a session (all open tabs)"; - saveProjectToolStripMenuItem.Click += OnSaveProjectToolStripMenuItemClick; - // - // exportBookmarksToolStripMenuItem - // - exportBookmarksToolStripMenuItem.Name = "exportBookmarksToolStripMenuItem"; - exportBookmarksToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - exportBookmarksToolStripMenuItem.Text = "Export bookmarks..."; - exportBookmarksToolStripMenuItem.ToolTipText = "Write a list of bookmarks and their comments to a CSV file"; - exportBookmarksToolStripMenuItem.Click += OnExportBookmarksToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension3 - // - menuToolStripSeparatorExtension3.Name = "menuToolStripSeparatorExtension3"; - menuToolStripSeparatorExtension3.Size = new System.Drawing.Size(250, 6); - // - // lastUsedToolStripMenuItem - // - lastUsedToolStripMenuItem.Name = "lastUsedToolStripMenuItem"; - lastUsedToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - lastUsedToolStripMenuItem.Text = "Last used"; - // - // exitToolStripMenuItem - // - exitToolStripMenuItem.Image = Resources.Exit; - exitToolStripMenuItem.Name = "exitToolStripMenuItem"; - exitToolStripMenuItem.ShortcutKeys = Keys.Alt | Keys.F4; - exitToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - exitToolStripMenuItem.Text = "Exit"; - exitToolStripMenuItem.Click += OnExitToolStripMenuItemClick; - // - // viewNavigateToolStripMenuItem - // - viewNavigateToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { goToLineToolStripMenuItem, searchToolStripMenuItem, filterToolStripMenuItem, bookmarksToolStripMenuItem, columnFinderToolStripMenuItem, menuToolStripSeparatorExtension5, toolStripEncodingMenuItem, menuToolStripSeparatorExtension6, timeshiftToolStripMenuItem, timeshiftMenuTextBox, menuToolStripSeparatorExtension4, copyMarkedLinesIntoNewTabToolStripMenuItem }); - viewNavigateToolStripMenuItem.Name = "viewNavigateToolStripMenuItem"; - viewNavigateToolStripMenuItem.Size = new System.Drawing.Size(96, 19); - viewNavigateToolStripMenuItem.Text = "View/Navigate"; - // - // goToLineToolStripMenuItem - // - goToLineToolStripMenuItem.Name = "goToLineToolStripMenuItem"; - goToLineToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.G; - goToLineToolStripMenuItem.Size = new System.Drawing.Size(189, 30); - goToLineToolStripMenuItem.Text = "Go to line..."; - goToLineToolStripMenuItem.Click += OnGoToLineToolStripMenuItemClick; - // - // searchToolStripMenuItem - // - searchToolStripMenuItem.Name = "searchToolStripMenuItem"; - searchToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F; - searchToolStripMenuItem.Size = new System.Drawing.Size(189, 30); - searchToolStripMenuItem.Text = "Search..."; - searchToolStripMenuItem.Click += OnSearchToolStripMenuItemClick; - // - // filterToolStripMenuItem - // - filterToolStripMenuItem.Image = Resources.Filter; - filterToolStripMenuItem.Name = "filterToolStripMenuItem"; - filterToolStripMenuItem.ShortcutKeys = Keys.F4; - filterToolStripMenuItem.Size = new System.Drawing.Size(189, 30); - filterToolStripMenuItem.Text = "Filter"; - filterToolStripMenuItem.Click += OnFilterToolStripMenuItemClick; - // - // bookmarksToolStripMenuItem - // - bookmarksToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { toggleBookmarkToolStripMenuItem, jumpToNextToolStripMenuItem, jumpToPrevToolStripMenuItem, showBookmarkListToolStripMenuItem }); - bookmarksToolStripMenuItem.Name = "bookmarksToolStripMenuItem"; - bookmarksToolStripMenuItem.Size = new System.Drawing.Size(189, 30); - bookmarksToolStripMenuItem.Text = "Bookmarks"; - // - // toggleBookmarkToolStripMenuItem - // - toggleBookmarkToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - toggleBookmarkToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - toggleBookmarkToolStripMenuItem.Image = Resources.Bookmark_add; - toggleBookmarkToolStripMenuItem.Name = "toggleBookmarkToolStripMenuItem"; - toggleBookmarkToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F2; - toggleBookmarkToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - toggleBookmarkToolStripMenuItem.Text = "Toggle Bookmark"; - toggleBookmarkToolStripMenuItem.Click += OnToggleBookmarkToolStripMenuItemClick; - // - // jumpToNextToolStripMenuItem - // - jumpToNextToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - jumpToNextToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - jumpToNextToolStripMenuItem.Image = Resources.ArrowDown; - jumpToNextToolStripMenuItem.Name = "jumpToNextToolStripMenuItem"; - jumpToNextToolStripMenuItem.ShortcutKeys = Keys.F2; - jumpToNextToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - jumpToNextToolStripMenuItem.Text = "Jump to next"; - jumpToNextToolStripMenuItem.Click += OnJumpToNextToolStripMenuItemClick; - // - // jumpToPrevToolStripMenuItem - // - jumpToPrevToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - jumpToPrevToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - jumpToPrevToolStripMenuItem.Image = Resources.ArrowUp; - jumpToPrevToolStripMenuItem.Name = "jumpToPrevToolStripMenuItem"; - jumpToPrevToolStripMenuItem.ShortcutKeys = Keys.Shift | Keys.F2; - jumpToPrevToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - jumpToPrevToolStripMenuItem.Text = "Jump to prev"; - jumpToPrevToolStripMenuItem.Click += OnJumpToPrevToolStripMenuItemClick; - // - // showBookmarkListToolStripMenuItem - // - showBookmarkListToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - showBookmarkListToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - showBookmarkListToolStripMenuItem.Name = "showBookmarkListToolStripMenuItem"; - showBookmarkListToolStripMenuItem.ShortcutKeys = Keys.F6; - showBookmarkListToolStripMenuItem.Size = new System.Drawing.Size(253, 30); - showBookmarkListToolStripMenuItem.Text = "Bookmark list"; - showBookmarkListToolStripMenuItem.Click += OnShowBookmarkListToolStripMenuItemClick; - // - // columnFinderToolStripMenuItem - // - columnFinderToolStripMenuItem.CheckOnClick = true; - columnFinderToolStripMenuItem.Name = "columnFinderToolStripMenuItem"; - columnFinderToolStripMenuItem.ShortcutKeys = Keys.F8; - columnFinderToolStripMenuItem.Size = new System.Drawing.Size(189, 30); - columnFinderToolStripMenuItem.Text = "Column finder"; - columnFinderToolStripMenuItem.Click += OnColumnFinderToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension5 - // - menuToolStripSeparatorExtension5.Name = "menuToolStripSeparatorExtension5"; - menuToolStripSeparatorExtension5.Size = new System.Drawing.Size(186, 6); - // - // toolStripEncodingMenuItem - // - toolStripEncodingMenuItem.DropDownItems.AddRange(new ToolStripItem[] { toolStripEncodingASCIIItem, toolStripEncodingANSIItem, toolStripEncodingISO88591Item, toolStripEncodingUTF8Item, toolStripEncodingUTF16Item }); - toolStripEncodingMenuItem.Name = "toolStripEncodingMenuItem"; - toolStripEncodingMenuItem.Size = new System.Drawing.Size(189, 30); - toolStripEncodingMenuItem.Text = "Encoding"; - // - // toolStripEncodingASCIIItem - // - toolStripEncodingASCIIItem.BackColor = System.Drawing.SystemColors.Control; - toolStripEncodingASCIIItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - toolStripEncodingASCIIItem.Name = "toolStripEncodingASCIIItem"; - toolStripEncodingASCIIItem.Size = new System.Drawing.Size(132, 22); - toolStripEncodingASCIIItem.Tag = ""; - toolStripEncodingASCIIItem.Text = "ASCII"; - toolStripEncodingASCIIItem.Click += OnASCIIToolStripMenuItemClick; - // - // toolStripEncodingANSIItem - // - toolStripEncodingANSIItem.BackColor = System.Drawing.SystemColors.Control; - toolStripEncodingANSIItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - toolStripEncodingANSIItem.Name = "toolStripEncodingANSIItem"; - toolStripEncodingANSIItem.Size = new System.Drawing.Size(132, 22); - toolStripEncodingANSIItem.Tag = ""; - toolStripEncodingANSIItem.Text = "ANSI"; - toolStripEncodingANSIItem.Click += OnANSIToolStripMenuItemClick; - // - // toolStripEncodingISO88591Item - // - toolStripEncodingISO88591Item.BackColor = System.Drawing.SystemColors.Control; - toolStripEncodingISO88591Item.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - toolStripEncodingISO88591Item.Name = "toolStripEncodingISO88591Item"; - toolStripEncodingISO88591Item.Size = new System.Drawing.Size(132, 22); - toolStripEncodingISO88591Item.Text = "ISO-8859-1"; - toolStripEncodingISO88591Item.Click += OnISO88591ToolStripMenuItemClick; - // - // toolStripEncodingUTF8Item - // - toolStripEncodingUTF8Item.BackColor = System.Drawing.SystemColors.Control; - toolStripEncodingUTF8Item.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - toolStripEncodingUTF8Item.Name = "toolStripEncodingUTF8Item"; - toolStripEncodingUTF8Item.Size = new System.Drawing.Size(132, 22); - toolStripEncodingUTF8Item.Text = "UTF8"; - toolStripEncodingUTF8Item.Click += OnUTF8ToolStripMenuItemClick; - // - // toolStripEncodingUTF16Item - // - toolStripEncodingUTF16Item.BackColor = System.Drawing.SystemColors.Control; - toolStripEncodingUTF16Item.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - toolStripEncodingUTF16Item.Name = "toolStripEncodingUTF16Item"; - toolStripEncodingUTF16Item.Size = new System.Drawing.Size(132, 22); - toolStripEncodingUTF16Item.Text = "Unicode"; - toolStripEncodingUTF16Item.Click += OnUTF16ToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension6 - // - menuToolStripSeparatorExtension6.Name = "menuToolStripSeparatorExtension6"; - menuToolStripSeparatorExtension6.Size = new System.Drawing.Size(186, 6); - // - // timeshiftToolStripMenuItem - // - timeshiftToolStripMenuItem.CheckOnClick = true; - timeshiftToolStripMenuItem.Name = "timeshiftToolStripMenuItem"; - timeshiftToolStripMenuItem.Size = new System.Drawing.Size(189, 30); - timeshiftToolStripMenuItem.Text = "Timeshift"; - timeshiftToolStripMenuItem.ToolTipText = "If supported by the columnizer, you can set an offset to the displayed log time"; - timeshiftToolStripMenuItem.CheckStateChanged += OnTimeShiftToolStripMenuItemCheckStateChanged; - // - // timeshiftMenuTextBox - // - timeshiftMenuTextBox.BorderStyle = BorderStyle.FixedSingle; - timeshiftMenuTextBox.Enabled = false; - timeshiftMenuTextBox.Font = new System.Drawing.Font("Segoe UI", 9F); - timeshiftMenuTextBox.Name = "timeshiftMenuTextBox"; - timeshiftMenuTextBox.Size = new System.Drawing.Size(100, 23); - timeshiftMenuTextBox.Text = "+00:00:00.000"; - timeshiftMenuTextBox.ToolTipText = "Time offset (hh:mm:ss.fff)"; - timeshiftMenuTextBox.KeyDown += OnTimeShiftMenuTextBoxKeyDown; - // - // menuToolStripSeparatorExtension4 - // - menuToolStripSeparatorExtension4.Name = "menuToolStripSeparatorExtension4"; - menuToolStripSeparatorExtension4.Size = new System.Drawing.Size(186, 6); - // - // copyMarkedLinesIntoNewTabToolStripMenuItem - // - copyMarkedLinesIntoNewTabToolStripMenuItem.Name = "copyMarkedLinesIntoNewTabToolStripMenuItem"; - copyMarkedLinesIntoNewTabToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T; - copyMarkedLinesIntoNewTabToolStripMenuItem.Size = new System.Drawing.Size(189, 30); - copyMarkedLinesIntoNewTabToolStripMenuItem.Text = "Copy to Tab"; - copyMarkedLinesIntoNewTabToolStripMenuItem.ToolTipText = "Copies all selected lines into a new tab page"; - copyMarkedLinesIntoNewTabToolStripMenuItem.Click += OnCopyMarkedLinesIntoNewTabToolStripMenuItemClick; - // - // optionToolStripMenuItem - // - optionToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { columnizerToolStripMenuItem, hilightingToolStripMenuItem1, menuToolStripSeparatorExtension7, settingsToolStripMenuItem, menuToolStripSeparatorExtension9, cellSelectModeToolStripMenuItem, alwaysOnTopToolStripMenuItem, hideLineColumnToolStripMenuItem, menuToolStripSeparatorExtension8, lockInstanceToolStripMenuItem }); - optionToolStripMenuItem.Name = "optionToolStripMenuItem"; - optionToolStripMenuItem.Size = new System.Drawing.Size(61, 19); - optionToolStripMenuItem.Text = "Options"; - optionToolStripMenuItem.DropDownOpening += OnOptionToolStripMenuItemDropDownOpening; - // - // columnizerToolStripMenuItem - // - columnizerToolStripMenuItem.Name = "columnizerToolStripMenuItem"; - columnizerToolStripMenuItem.Size = new System.Drawing.Size(224, 30); - columnizerToolStripMenuItem.Text = "Columnizer..."; - columnizerToolStripMenuItem.ToolTipText = "Splits various kinds of logfiles into fixed columns"; - columnizerToolStripMenuItem.Click += OnSelectFilterToolStripMenuItemClick; - // - // hilightingToolStripMenuItem1 - // - hilightingToolStripMenuItem1.Name = "hilightingToolStripMenuItem1"; - hilightingToolStripMenuItem1.Size = new System.Drawing.Size(224, 30); - hilightingToolStripMenuItem1.Text = "Highlighting and triggers..."; - hilightingToolStripMenuItem1.Click += OnHighlightingToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension7 - // - menuToolStripSeparatorExtension7.Name = "menuToolStripSeparatorExtension7"; - menuToolStripSeparatorExtension7.Size = new System.Drawing.Size(221, 6); - // - // settingsToolStripMenuItem - // - settingsToolStripMenuItem.Image = Resources.Settings; - settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; - settingsToolStripMenuItem.Size = new System.Drawing.Size(224, 30); - settingsToolStripMenuItem.Text = "Settings..."; - settingsToolStripMenuItem.Click += OnSettingsToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension9 - // - menuToolStripSeparatorExtension9.Name = "menuToolStripSeparatorExtension9"; - menuToolStripSeparatorExtension9.Size = new System.Drawing.Size(221, 6); - // - // cellSelectModeToolStripMenuItem - // - cellSelectModeToolStripMenuItem.CheckOnClick = true; - cellSelectModeToolStripMenuItem.Name = "cellSelectModeToolStripMenuItem"; - cellSelectModeToolStripMenuItem.Size = new System.Drawing.Size(224, 30); - cellSelectModeToolStripMenuItem.Text = "Cell select mode"; - cellSelectModeToolStripMenuItem.ToolTipText = "Switches between foll row selection and single cell selection mode"; - cellSelectModeToolStripMenuItem.Click += OnCellSelectModeToolStripMenuItemClick; - // - // alwaysOnTopToolStripMenuItem - // - alwaysOnTopToolStripMenuItem.CheckOnClick = true; - alwaysOnTopToolStripMenuItem.Name = "alwaysOnTopToolStripMenuItem"; - alwaysOnTopToolStripMenuItem.Size = new System.Drawing.Size(224, 30); - alwaysOnTopToolStripMenuItem.Text = "Always on top"; - alwaysOnTopToolStripMenuItem.Click += OnAlwaysOnTopToolStripMenuItemClick; - // - // hideLineColumnToolStripMenuItem - // - hideLineColumnToolStripMenuItem.CheckOnClick = true; - hideLineColumnToolStripMenuItem.Name = "hideLineColumnToolStripMenuItem"; - hideLineColumnToolStripMenuItem.Size = new System.Drawing.Size(224, 30); - hideLineColumnToolStripMenuItem.Text = "Hide line column"; - hideLineColumnToolStripMenuItem.Click += OnHideLineColumnToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension8 - // - menuToolStripSeparatorExtension8.Name = "menuToolStripSeparatorExtension8"; - menuToolStripSeparatorExtension8.Size = new System.Drawing.Size(221, 6); - // - // lockInstanceToolStripMenuItem - // - lockInstanceToolStripMenuItem.Name = "lockInstanceToolStripMenuItem"; - lockInstanceToolStripMenuItem.Size = new System.Drawing.Size(224, 30); - lockInstanceToolStripMenuItem.Text = "Lock instance"; - lockInstanceToolStripMenuItem.ToolTipText = "When enabled all new launched LogExpert instances will redirect to this window"; - lockInstanceToolStripMenuItem.Click += OnLockInstanceToolStripMenuItemClick; - // - // toolsToolStripMenuItem - // - toolsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { configureToolStripMenuItem, configureToolStripSeparator }); - toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; - toolsToolStripMenuItem.Size = new System.Drawing.Size(47, 19); - toolsToolStripMenuItem.Text = "Tools"; - toolsToolStripMenuItem.ToolTipText = "Launch external tools (configure in the settings)"; - toolsToolStripMenuItem.DropDownItemClicked += OnToolsToolStripMenuItemDropDownItemClicked; - // - // configureToolStripMenuItem - // - configureToolStripMenuItem.Name = "configureToolStripMenuItem"; - configureToolStripMenuItem.Size = new System.Drawing.Size(136, 22); - configureToolStripMenuItem.Text = "Configure..."; - configureToolStripMenuItem.Click += OnConfigureToolStripMenuItemClick; - // - // configureToolStripSeparator - // - configureToolStripSeparator.Name = "configureToolStripSeparator"; - configureToolStripSeparator.Size = new System.Drawing.Size(133, 6); - // - // helpToolStripMenuItem - // - helpToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { showHelpToolStripMenuItem, menuToolStripSeparatorExtension11, aboutToolStripMenuItem }); - helpToolStripMenuItem.Name = "helpToolStripMenuItem"; - helpToolStripMenuItem.Size = new System.Drawing.Size(44, 19); - helpToolStripMenuItem.Text = "Help"; - // - // showHelpToolStripMenuItem - // - showHelpToolStripMenuItem.Name = "showHelpToolStripMenuItem"; - showHelpToolStripMenuItem.ShortcutKeys = Keys.F1; - showHelpToolStripMenuItem.Size = new System.Drawing.Size(148, 22); - showHelpToolStripMenuItem.Text = "Show help"; - showHelpToolStripMenuItem.Click += OnShowHelpToolStripMenuItemClick; - // - // menuToolStripSeparatorExtension11 - // - menuToolStripSeparatorExtension11.Name = "menuToolStripSeparatorExtension11"; - menuToolStripSeparatorExtension11.Size = new System.Drawing.Size(145, 6); - // - // aboutToolStripMenuItem - // - aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; - aboutToolStripMenuItem.Size = new System.Drawing.Size(148, 22); - aboutToolStripMenuItem.Text = "About"; - aboutToolStripMenuItem.Click += OnAboutToolStripMenuItemClick; - // - // debugToolStripMenuItem - // - debugToolStripMenuItem.Alignment = ToolStripItemAlignment.Right; - debugToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { dumpLogBufferInfoToolStripMenuItem, dumpBufferDiagnosticToolStripMenuItem, runGCToolStripMenuItem, gCInfoToolStripMenuItem, throwExceptionGUIThreadToolStripMenuItem, throwExceptionbackgroundThToolStripMenuItem, throwExceptionBackgroundThreadToolStripMenuItem, loglevelToolStripMenuItem, disableWordHighlightModeToolStripMenuItem }); - debugToolStripMenuItem.Name = "debugToolStripMenuItem"; - debugToolStripMenuItem.Size = new System.Drawing.Size(54, 19); - debugToolStripMenuItem.Text = "Debug"; - // - // dumpLogBufferInfoToolStripMenuItem - // - dumpLogBufferInfoToolStripMenuItem.Name = "dumpLogBufferInfoToolStripMenuItem"; - dumpLogBufferInfoToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - dumpLogBufferInfoToolStripMenuItem.Text = "Dump LogBuffer info"; - dumpLogBufferInfoToolStripMenuItem.Click += OnDumpLogBufferInfoToolStripMenuItemClick; - // - // dumpBufferDiagnosticToolStripMenuItem - // - dumpBufferDiagnosticToolStripMenuItem.Name = "dumpBufferDiagnosticToolStripMenuItem"; - dumpBufferDiagnosticToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - dumpBufferDiagnosticToolStripMenuItem.Text = "Dump buffer diagnostic"; - dumpBufferDiagnosticToolStripMenuItem.Click += OnDumpBufferDiagnosticToolStripMenuItemClick; - // - // runGCToolStripMenuItem - // - runGCToolStripMenuItem.Name = "runGCToolStripMenuItem"; - runGCToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - runGCToolStripMenuItem.Text = "Run GC"; - runGCToolStripMenuItem.Click += OnRunGCToolStripMenuItemClick; - // - // gCInfoToolStripMenuItem - // - gCInfoToolStripMenuItem.Name = "gCInfoToolStripMenuItem"; - gCInfoToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - gCInfoToolStripMenuItem.Text = "Dump GC info"; - gCInfoToolStripMenuItem.Click += OnGCInfoToolStripMenuItemClick; - // - // throwExceptionGUIThreadToolStripMenuItem - // - throwExceptionGUIThreadToolStripMenuItem.Name = "throwExceptionGUIThreadToolStripMenuItem"; - throwExceptionGUIThreadToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - throwExceptionGUIThreadToolStripMenuItem.Text = "Throw exception (GUI Thread)"; - throwExceptionGUIThreadToolStripMenuItem.Click += OnThrowExceptionGUIThreadToolStripMenuItemClick; - // - // throwExceptionbackgroundThToolStripMenuItem - // - throwExceptionbackgroundThToolStripMenuItem.Name = "throwExceptionbackgroundThToolStripMenuItem"; - throwExceptionbackgroundThToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - throwExceptionbackgroundThToolStripMenuItem.Text = "Throw exception (Async delegate)"; - throwExceptionbackgroundThToolStripMenuItem.Click += OnThrowExceptionBackgroundThToolStripMenuItemClick; - // - // throwExceptionBackgroundThreadToolStripMenuItem - // - throwExceptionBackgroundThreadToolStripMenuItem.Name = "throwExceptionBackgroundThreadToolStripMenuItem"; - throwExceptionBackgroundThreadToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - throwExceptionBackgroundThreadToolStripMenuItem.Text = "Throw exception (background thread)"; - throwExceptionBackgroundThreadToolStripMenuItem.Click += OnThrowExceptionBackgroundThreadToolStripMenuItemClick; - // - // loglevelToolStripMenuItem - // - loglevelToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { warnToolStripMenuItem, infoToolStripMenuItem, debugToolStripMenuItem1 }); - loglevelToolStripMenuItem.Name = "loglevelToolStripMenuItem"; - loglevelToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - loglevelToolStripMenuItem.Text = "Loglevel"; - loglevelToolStripMenuItem.DropDownOpening += OnLogLevelToolStripMenuItemDropDownOpening; - loglevelToolStripMenuItem.Click += OnLogLevelToolStripMenuItemClick; - // - // warnToolStripMenuItem - // - warnToolStripMenuItem.Name = "warnToolStripMenuItem"; - warnToolStripMenuItem.Size = new System.Drawing.Size(109, 22); - warnToolStripMenuItem.Text = "Warn"; - warnToolStripMenuItem.Click += OnWarnToolStripMenuItemClick; - // - // infoToolStripMenuItem - // - infoToolStripMenuItem.Name = "infoToolStripMenuItem"; - infoToolStripMenuItem.Size = new System.Drawing.Size(109, 22); - infoToolStripMenuItem.Text = "Info"; - infoToolStripMenuItem.Click += OnInfoToolStripMenuItemClick; - // - // debugToolStripMenuItem1 - // - debugToolStripMenuItem1.Name = "debugToolStripMenuItem1"; - debugToolStripMenuItem1.Size = new System.Drawing.Size(109, 22); - debugToolStripMenuItem1.Text = "Debug"; - debugToolStripMenuItem1.Click += OnDebugToolStripMenuItemClick; - // - // disableWordHighlightModeToolStripMenuItem - // - disableWordHighlightModeToolStripMenuItem.CheckOnClick = true; - disableWordHighlightModeToolStripMenuItem.Name = "disableWordHighlightModeToolStripMenuItem"; - disableWordHighlightModeToolStripMenuItem.Size = new System.Drawing.Size(274, 22); - disableWordHighlightModeToolStripMenuItem.Text = "Disable word highlight mode"; - disableWordHighlightModeToolStripMenuItem.Click += OnDisableWordHighlightModeToolStripMenuItemClick; - // - // host - // - host.AccessibleName = "host"; - host.AutoSize = true; - host.BackColor = System.Drawing.Color.Transparent; - host.Location = new System.Drawing.Point(9, 1); - host.Name = "host"; - host.Size = new System.Drawing.Size(80, 22); - host.TabIndex = 7; - host.Text = "Follow tail"; - host.UseVisualStyleBackColor = false; - // - // toolStripContainer - // - // - // toolStripContainer.BottomToolStripPanel - // - toolStripContainer.BottomToolStripPanel.RenderMode = ToolStripRenderMode.System; - toolStripContainer.BottomToolStripPanelVisible = false; - // - // toolStripContainer.ContentPanel - // - toolStripContainer.ContentPanel.Controls.Add(dockPanel); - toolStripContainer.ContentPanel.Margin = new Padding(0); - toolStripContainer.ContentPanel.Size = new System.Drawing.Size(1603, 881); - toolStripContainer.Dock = DockStyle.Fill; - // - // toolStripContainer.LeftToolStripPanel - // - toolStripContainer.LeftToolStripPanel.Enabled = false; - toolStripContainer.LeftToolStripPanelVisible = false; - toolStripContainer.Location = new System.Drawing.Point(0, 0); - toolStripContainer.Margin = new Padding(0); - toolStripContainer.Name = "toolStripContainer"; - // - // toolStripContainer.RightToolStripPanel - // - toolStripContainer.RightToolStripPanel.Enabled = false; - toolStripContainer.RightToolStripPanelVisible = false; - toolStripContainer.Size = new System.Drawing.Size(1603, 954); - toolStripContainer.TabIndex = 13; - toolStripContainer.Text = "toolStripContainer1"; - // - // toolStripContainer.TopToolStripPanel - // - toolStripContainer.TopToolStripPanel.Controls.Add(externalToolsToolStrip); - toolStripContainer.TopToolStripPanel.Controls.Add(mainMenuStrip); - toolStripContainer.TopToolStripPanel.Controls.Add(buttonToolStrip); - // - // dockPanel - // - dockPanel.ActiveAutoHideContent = null; - dockPanel.DefaultFloatWindowSize = new System.Drawing.Size(600, 400); - 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"; - dockPanel.ShowDocumentIcon = true; - dockPanel.Size = new System.Drawing.Size(1603, 881); - dockPanelGradient1.EndColor = System.Drawing.SystemColors.Control; - dockPanelGradient1.StartColor = System.Drawing.SystemColors.Control; - autoHideStripSkin1.DockStripGradient = dockPanelGradient1; - tabGradient1.EndColor = System.Drawing.SystemColors.Control; - tabGradient1.StartColor = System.Drawing.SystemColors.Control; - tabGradient1.TextColor = System.Drawing.SystemColors.ControlText; - autoHideStripSkin1.TabGradient = tabGradient1; - autoHideStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F); - dockPanelSkin1.AutoHideStripSkin = autoHideStripSkin1; - tabGradient2.EndColor = System.Drawing.SystemColors.Control; - tabGradient2.StartColor = System.Drawing.SystemColors.Control; - tabGradient2.TextColor = System.Drawing.SystemColors.ControlText; - dockPaneStripGradient1.ActiveTabGradient = tabGradient2; - dockPanelGradient2.EndColor = System.Drawing.SystemColors.Control; - dockPanelGradient2.StartColor = System.Drawing.SystemColors.Control; - dockPaneStripGradient1.DockStripGradient = dockPanelGradient2; - tabGradient3.EndColor = System.Drawing.SystemColors.ControlLight; - tabGradient3.StartColor = System.Drawing.SystemColors.ControlLight; - tabGradient3.TextColor = System.Drawing.SystemColors.ControlText; - dockPaneStripGradient1.InactiveTabGradient = tabGradient3; - dockPaneStripSkin1.DocumentGradient = dockPaneStripGradient1; - dockPaneStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F); - tabGradient4.EndColor = System.Drawing.SystemColors.ActiveCaption; - tabGradient4.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical; - tabGradient4.StartColor = System.Drawing.SystemColors.GradientActiveCaption; - tabGradient4.TextColor = System.Drawing.SystemColors.ActiveCaptionText; - dockPaneStripToolWindowGradient1.ActiveCaptionGradient = tabGradient4; - tabGradient5.EndColor = System.Drawing.SystemColors.Control; - tabGradient5.StartColor = System.Drawing.SystemColors.Control; - tabGradient5.TextColor = System.Drawing.SystemColors.ControlText; - dockPaneStripToolWindowGradient1.ActiveTabGradient = tabGradient5; - dockPanelGradient3.EndColor = System.Drawing.SystemColors.ControlLight; - dockPanelGradient3.StartColor = System.Drawing.SystemColors.ControlLight; - dockPaneStripToolWindowGradient1.DockStripGradient = dockPanelGradient3; - tabGradient6.EndColor = System.Drawing.SystemColors.InactiveCaption; - tabGradient6.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical; - tabGradient6.StartColor = System.Drawing.SystemColors.GradientInactiveCaption; - tabGradient6.TextColor = System.Drawing.SystemColors.InactiveCaptionText; - dockPaneStripToolWindowGradient1.InactiveCaptionGradient = tabGradient6; - tabGradient7.EndColor = System.Drawing.Color.Transparent; - tabGradient7.StartColor = System.Drawing.Color.Transparent; - tabGradient7.TextColor = System.Drawing.SystemColors.Control; - dockPaneStripToolWindowGradient1.InactiveTabGradient = tabGradient7; - dockPaneStripSkin1.ToolWindowGradient = dockPaneStripToolWindowGradient1; - dockPanelSkin1.DockPaneStripSkin = dockPaneStripSkin1; - dockPanel.Skin = dockPanelSkin1; - dockPanel.TabIndex = 14; - dockPanel.ActiveContentChanged += OnDockPanelActiveContentChanged; - // - // externalToolsToolStrip - // - externalToolsToolStrip.AllowMerge = false; - externalToolsToolStrip.Dock = DockStyle.None; - externalToolsToolStrip.ImageScalingSize = new System.Drawing.Size(24, 24); - externalToolsToolStrip.LayoutStyle = ToolStripLayoutStyle.Flow; - externalToolsToolStrip.Location = new System.Drawing.Point(8, 0); - externalToolsToolStrip.Name = "externalToolsToolStrip"; - externalToolsToolStrip.Size = new System.Drawing.Size(32, 19); - externalToolsToolStrip.TabIndex = 8; - externalToolsToolStrip.ItemClicked += OnExternalToolsToolStripItemClicked; - // - // buttonToolStrip - // - buttonToolStrip.AllowMerge = false; - buttonToolStrip.Dock = DockStyle.None; - buttonToolStrip.ImageScalingSize = new System.Drawing.Size(24, 24); - buttonToolStrip.Items.AddRange(new ToolStripItem[] { toolStripButtonOpen, lineToolStripSeparatorExtension1, toolStripButtonSearch, toolStripButtonFilter, lineToolStripSeparatorExtension2, toolStripButtonBookmark, toolStripButtonUp, toolStripButtonDown, lineToolStripSeparatorExtension3, toolStripButtonBubbles, lineToolStripSeparatorExtension4, toolStripButtonTail, lineToolStripSeparatorExtension5, groupsComboBoxHighlightGroups }); - buttonToolStrip.LayoutStyle = ToolStripLayoutStyle.Flow; - buttonToolStrip.Location = new System.Drawing.Point(3, 42); - buttonToolStrip.Name = "buttonToolStrip"; - buttonToolStrip.Size = new System.Drawing.Size(406, 31); - buttonToolStrip.TabIndex = 7; - // - // toolStripButtonOpen - // - toolStripButtonOpen.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonOpen.Image = Resources.File_open; - toolStripButtonOpen.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonOpen.Name = "toolStripButtonOpen"; - toolStripButtonOpen.Size = new System.Drawing.Size(28, 28); - toolStripButtonOpen.Text = "Open File"; - toolStripButtonOpen.ToolTipText = "Open file"; - toolStripButtonOpen.Click += OnToolStripButtonOpenClick; - // - // lineToolStripSeparatorExtension1 - // - lineToolStripSeparatorExtension1.Name = "lineToolStripSeparatorExtension1"; - lineToolStripSeparatorExtension1.Size = new System.Drawing.Size(6, 23); - // - // toolStripButtonSearch - // - toolStripButtonSearch.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonSearch.Image = Resources.Search; - toolStripButtonSearch.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonSearch.Name = "toolStripButtonSearch"; - toolStripButtonSearch.Size = new System.Drawing.Size(28, 28); - toolStripButtonSearch.Text = "Search"; - toolStripButtonSearch.ToolTipText = "Search"; - toolStripButtonSearch.Click += OnToolStripButtonSearchClick; - // - // toolStripButtonFilter - // - toolStripButtonFilter.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonFilter.Image = Resources.Filter; - toolStripButtonFilter.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonFilter.Name = "toolStripButtonFilter"; - toolStripButtonFilter.Size = new System.Drawing.Size(28, 28); - toolStripButtonFilter.Text = "Filter"; - toolStripButtonFilter.ToolTipText = "Filter window"; - toolStripButtonFilter.Click += OnToolStripButtonFilterClick; - // - // lineToolStripSeparatorExtension2 - // - lineToolStripSeparatorExtension2.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - lineToolStripSeparatorExtension2.Name = "lineToolStripSeparatorExtension2"; - lineToolStripSeparatorExtension2.Size = new System.Drawing.Size(6, 23); - // - // toolStripButtonBookmark - // - toolStripButtonBookmark.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonBookmark.Image = Resources.Bookmark_add; - toolStripButtonBookmark.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonBookmark.Name = "toolStripButtonBookmark"; - toolStripButtonBookmark.Size = new System.Drawing.Size(28, 28); - toolStripButtonBookmark.Text = "Toggle Bookmark"; - toolStripButtonBookmark.ToolTipText = "Toggle bookmark"; - toolStripButtonBookmark.Click += OnToolStripButtonBookmarkClick; - // - // toolStripButtonUp - // - toolStripButtonUp.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonUp.Image = Resources.ArrowUp; - toolStripButtonUp.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonUp.Name = "toolStripButtonUp"; - toolStripButtonUp.Size = new System.Drawing.Size(28, 28); - toolStripButtonUp.Text = "Previous Bookmark"; - toolStripButtonUp.ToolTipText = "Go to previous bookmark"; - toolStripButtonUp.Click += OnToolStripButtonUpClick; - // - // toolStripButtonDown - // - toolStripButtonDown.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonDown.Image = Resources.ArrowDown; - toolStripButtonDown.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonDown.Name = "toolStripButtonDown"; - toolStripButtonDown.Size = new System.Drawing.Size(28, 28); - toolStripButtonDown.Text = "Next Bookmark"; - toolStripButtonDown.ToolTipText = "Go to next bookmark"; - toolStripButtonDown.Click += OnToolStripButtonDownClick; - // - // lineToolStripSeparatorExtension3 - // - lineToolStripSeparatorExtension3.Name = "lineToolStripSeparatorExtension3"; - lineToolStripSeparatorExtension3.Size = new System.Drawing.Size(6, 23); - // - // toolStripButtonBubbles - // - toolStripButtonBubbles.CheckOnClick = true; - toolStripButtonBubbles.DisplayStyle = ToolStripItemDisplayStyle.Image; - toolStripButtonBubbles.Image = Resources.bookmark_bubbles; - toolStripButtonBubbles.ImageAlign = System.Drawing.ContentAlignment.BottomCenter; - toolStripButtonBubbles.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonBubbles.Name = "toolStripButtonBubbles"; - toolStripButtonBubbles.Size = new System.Drawing.Size(28, 28); - toolStripButtonBubbles.Text = "Show bookmark bubbles"; - toolStripButtonBubbles.Click += OnToolStripButtonBubblesClick; - // - // lineToolStripSeparatorExtension4 - // - lineToolStripSeparatorExtension4.Name = "lineToolStripSeparatorExtension4"; - lineToolStripSeparatorExtension4.Size = new System.Drawing.Size(6, 23); - // - // toolStripButtonTail - // - toolStripButtonTail.DisplayStyle = ToolStripItemDisplayStyle.Text; - toolStripButtonTail.Image = (System.Drawing.Image)resources.GetObject("toolStripButtonTail.Image"); - toolStripButtonTail.ImageTransparentColor = System.Drawing.Color.Magenta; - toolStripButtonTail.Name = "toolStripButtonTail"; - toolStripButtonTail.Size = new System.Drawing.Size(27, 19); - toolStripButtonTail.Text = "tail"; - // - // lineToolStripSeparatorExtension5 - // - lineToolStripSeparatorExtension5.Name = "lineToolStripSeparatorExtension5"; - lineToolStripSeparatorExtension5.Size = new System.Drawing.Size(6, 23); - // - // groupsComboBoxHighlightGroups - // - groupsComboBoxHighlightGroups.DropDownStyle = ComboBoxStyle.DropDownList; - groupsComboBoxHighlightGroups.DropDownWidth = 250; - groupsComboBoxHighlightGroups.FlatStyle = FlatStyle.Standard; - groupsComboBoxHighlightGroups.Name = "groupsComboBoxHighlightGroups"; - groupsComboBoxHighlightGroups.Size = new System.Drawing.Size(150, 23); - groupsComboBoxHighlightGroups.ToolTipText = "Select the current highlight settings for the log file (right-click to open highlight settings)"; - groupsComboBoxHighlightGroups.DropDownClosed += OnHighlightGroupsComboBoxDropDownClosed; - groupsComboBoxHighlightGroups.SelectedIndexChanged += OnHighlightGroupsComboBoxSelectedIndexChanged; - groupsComboBoxHighlightGroups.MouseUp += OnHighlightGroupsComboBoxMouseUp; - // - // checkBoxFollowTail - // - checkBoxFollowTail.AutoSize = true; - checkBoxFollowTail.Location = new System.Drawing.Point(663, 985); - checkBoxFollowTail.Margin = new Padding(4, 7, 4, 7); - checkBoxFollowTail.Name = "checkBoxFollowTail"; - checkBoxFollowTail.Size = new System.Drawing.Size(80, 19); - checkBoxFollowTail.TabIndex = 14; - checkBoxFollowTail.Text = "Follow tail"; - checkBoxFollowTail.UseVisualStyleBackColor = true; - checkBoxFollowTail.Click += OnFollowTailCheckBoxClick; - // - // tabContextMenuStrip - // - tabContextMenuStrip.ForeColor = System.Drawing.SystemColors.ControlText; - tabContextMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); - tabContextMenuStrip.Items.AddRange(new ToolStripItem[] { closeThisTabToolStripMenuItem, closeOtherTabsToolStripMenuItem, closeAllTabsToolStripMenuItem, tabColorToolStripMenuItem, tabRenameToolStripMenuItem, copyPathToClipboardToolStripMenuItem, findInExplorerToolStripMenuItem }); - tabContextMenuStrip.Name = "tabContextMenuStrip"; - tabContextMenuStrip.Size = new System.Drawing.Size(197, 158); - // - // closeThisTabToolStripMenuItem - // - closeThisTabToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; - closeThisTabToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText; - closeThisTabToolStripMenuItem.Name = "closeThisTabToolStripMenuItem"; - closeThisTabToolStripMenuItem.Size = new System.Drawing.Size(196, 22); - closeThisTabToolStripMenuItem.Text = "Close this tab"; - closeThisTabToolStripMenuItem.Click += OnCloseThisTabToolStripMenuItemClick; - // - // closeOtherTabsToolStripMenuItem - // - closeOtherTabsToolStripMenuItem.Name = "closeOtherTabsToolStripMenuItem"; - closeOtherTabsToolStripMenuItem.Size = new System.Drawing.Size(196, 22); - closeOtherTabsToolStripMenuItem.Text = "Close other tabs"; - closeOtherTabsToolStripMenuItem.ToolTipText = "Close all tabs except of this one"; - closeOtherTabsToolStripMenuItem.Click += OnCloseOtherTabsToolStripMenuItemClick; - // - // closeAllTabsToolStripMenuItem - // - closeAllTabsToolStripMenuItem.Name = "closeAllTabsToolStripMenuItem"; - closeAllTabsToolStripMenuItem.Size = new System.Drawing.Size(196, 22); - closeAllTabsToolStripMenuItem.Text = "Close all tabs"; - closeAllTabsToolStripMenuItem.ToolTipText = "Close all tabs"; - closeAllTabsToolStripMenuItem.Click += OnCloseAllTabsToolStripMenuItemClick; - // - // tabColorToolStripMenuItem - // - tabColorToolStripMenuItem.Name = "tabColorToolStripMenuItem"; - tabColorToolStripMenuItem.Size = new System.Drawing.Size(196, 22); - tabColorToolStripMenuItem.Text = "Tab color..."; - tabColorToolStripMenuItem.ToolTipText = "Sets the tab color"; - tabColorToolStripMenuItem.Click += OnTabColorToolStripMenuItemClick; - // - // tabRenameToolStripMenuItem - // - tabRenameToolStripMenuItem.Name = "tabRenameToolStripMenuItem"; - tabRenameToolStripMenuItem.Size = new System.Drawing.Size(196, 22); - tabRenameToolStripMenuItem.Text = "Tab rename..."; - tabRenameToolStripMenuItem.ToolTipText = "Set the text which is shown on the tab"; - tabRenameToolStripMenuItem.Click += OnTabRenameToolStripMenuItemClick; - // - // copyPathToClipboardToolStripMenuItem - // - copyPathToClipboardToolStripMenuItem.Name = "copyPathToClipboardToolStripMenuItem"; - copyPathToClipboardToolStripMenuItem.Size = new System.Drawing.Size(196, 22); - copyPathToClipboardToolStripMenuItem.Text = "Copy path to clipboard"; - copyPathToClipboardToolStripMenuItem.ToolTipText = "The complete file name (incl. path) is copied to clipboard"; - copyPathToClipboardToolStripMenuItem.Click += OnCopyPathToClipboardToolStripMenuItemClick; - // - // findInExplorerToolStripMenuItem - // - findInExplorerToolStripMenuItem.Name = "findInExplorerToolStripMenuItem"; - findInExplorerToolStripMenuItem.Size = new System.Drawing.Size(196, 22); - findInExplorerToolStripMenuItem.Text = "Find in Explorer"; - findInExplorerToolStripMenuItem.ToolTipText = "Opens an Explorer window and selects the log file"; - findInExplorerToolStripMenuItem.Click += OnFindInExplorerToolStripMenuItemClick; - // - // dragControlDateTime - // - dragControlDateTime.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; - dragControlDateTime.BackColor = System.Drawing.SystemColors.Control; - dragControlDateTime.DateTime = new System.DateTime(0L); - dragControlDateTime.DragOrientation = DateTimeDragControl.DragOrientations.Vertical; - dragControlDateTime.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); - dragControlDateTime.ForeColor = System.Drawing.SystemColors.ControlDarkDark; - dragControlDateTime.HoverColor = System.Drawing.Color.LightGray; - dragControlDateTime.Location = new System.Drawing.Point(1017, 977); - dragControlDateTime.Margin = new Padding(0); - dragControlDateTime.MaxDateTime = new System.DateTime(9999, 12, 31, 23, 59, 59, 999); - dragControlDateTime.MinDateTime = new System.DateTime(0L); - dragControlDateTime.Name = "dragControlDateTime"; - dragControlDateTime.Size = new System.Drawing.Size(313, 38); - dragControlDateTime.TabIndex = 14; - dragControlDateTime.ValueChanged += OnDateTimeDragControlValueChanged; - dragControlDateTime.ValueDragged += OnDateTimeDragControlValueDragged; - // - // LogTabWindow - // - AllowDrop = true; - ClientSize = new System.Drawing.Size(1603, 1017); - Controls.Add(checkBoxFollowTail); - Controls.Add(dragControlDateTime); - Controls.Add(toolStripContainer); - Controls.Add(statusStrip); - DoubleBuffered = true; - Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); - KeyPreview = true; - MainMenuStrip = mainMenuStrip; - Margin = new Padding(4, 7, 4, 7); - Name = "LogTabWindow"; - Text = "LogExpert"; - Activated += OnLogTabWindowActivated; - Deactivate += OnLogTabWindowDeactivate; - SizeChanged += OnLogTabWindowSizeChanged; - DragDrop += OnLogWindowDragDrop; - DragEnter += OnLogTabWindowDragEnter; - DragOver += OnLogWindowDragOver; - KeyDown += OnLogTabWindowKeyDown; - statusStrip.ResumeLayout(false); - statusStrip.PerformLayout(); - mainMenuStrip.ResumeLayout(false); - mainMenuStrip.PerformLayout(); - toolStripContainer.ContentPanel.ResumeLayout(false); - toolStripContainer.TopToolStripPanel.ResumeLayout(false); - toolStripContainer.TopToolStripPanel.PerformLayout(); - toolStripContainer.ResumeLayout(false); - toolStripContainer.PerformLayout(); - buttonToolStrip.ResumeLayout(false); - buttonToolStrip.PerformLayout(); - tabContextMenuStrip.ResumeLayout(false); - ResumeLayout(false); - PerformLayout(); - } - - #endregion - - private System.Windows.Forms.StatusStrip statusStrip; - private System.Windows.Forms.ToolStripStatusLabel labelLines; - private System.Windows.Forms.ToolStripStatusLabel labelSize; - private System.Windows.Forms.MenuStrip mainMenuStrip; - private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem viewNavigateToolStripMenuItem; - private System.Windows.Forms.ToolStripStatusLabel labelCurrentLine; - private System.Windows.Forms.ToolStripProgressBar loadProgessBar; - private System.Windows.Forms.ToolStripStatusLabel labelStatus; - private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; - private System.Windows.Forms.ToolStripContainer toolStripContainer; - private System.Windows.Forms.ToolStripMenuItem closeFileToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem multiFileToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem goToLineToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem timeshiftToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem filterToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem copyMarkedLinesIntoNewTabToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem optionToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem hilightingToolStripMenuItem1; - private System.Windows.Forms.ToolStripMenuItem cellSelectModeToolStripMenuItem; - private System.Windows.Forms.ToolStripTextBox timeshiftMenuTextBox; - private System.Windows.Forms.ToolStripMenuItem alwaysOnTopToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem bookmarksToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem toggleBookmarkToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem jumpToNextToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem jumpToPrevToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem toolStripEncodingMenuItem; - private System.Windows.Forms.ToolStripMenuItem toolStripEncodingASCIIItem; - private System.Windows.Forms.ToolStripMenuItem toolStripEncodingANSIItem; - private System.Windows.Forms.ToolStripMenuItem toolStripEncodingUTF8Item; - private System.Windows.Forms.ToolStripMenuItem toolStripEncodingUTF16Item; - private System.Windows.Forms.ToolStripMenuItem reloadToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem columnizerToolStripMenuItem; - private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem; - private DateTimeDragControl dragControlDateTime; - private System.Windows.Forms.ToolStripMenuItem showBookmarkListToolStripMenuItem; - private System.Windows.Forms.ToolStrip buttonToolStrip; - private System.Windows.Forms.ToolStripButton toolStripButtonOpen; - private System.Windows.Forms.ToolStripButton toolStripButtonSearch; - private System.Windows.Forms.ToolStripButton toolStripButtonFilter; - private System.Windows.Forms.ToolStripButton toolStripButtonBookmark; - private System.Windows.Forms.ToolStripButton toolStripButtonUp; - private System.Windows.Forms.ToolStripButton toolStripButtonDown; - private CheckBox host; - private CheckBox checkBoxFollowTail; - private ToolStripButton toolStripButtonTail; - private ToolStripMenuItem showHelpToolStripMenuItem; - private ToolStripMenuItem hideLineColumnToolStripMenuItem; - private ToolStripMenuItem lastUsedToolStripMenuItem; - private ContextMenuStrip tabContextMenuStrip; - private ToolStripMenuItem closeThisTabToolStripMenuItem; - private ToolStripMenuItem closeOtherTabsToolStripMenuItem; - private ToolStripMenuItem closeAllTabsToolStripMenuItem; - private ToolStripMenuItem tabColorToolStripMenuItem; - private ToolStripMenuItem loadProjectToolStripMenuItem; - private ToolStripMenuItem saveProjectToolStripMenuItem; - private ToolStripButton toolStripButtonBubbles; - private ToolStripMenuItem copyPathToClipboardToolStripMenuItem; - private ToolStripMenuItem findInExplorerToolStripMenuItem; - private ToolStripMenuItem exportBookmarksToolStripMenuItem; - private ToolStripComboBox groupsComboBoxHighlightGroups; - private ToolStripMenuItem debugToolStripMenuItem; - private ToolStripMenuItem dumpLogBufferInfoToolStripMenuItem; - private ToolStripMenuItem dumpBufferDiagnosticToolStripMenuItem; - private ToolStripMenuItem runGCToolStripMenuItem; - private ToolStripMenuItem gCInfoToolStripMenuItem; - private ToolStrip externalToolsToolStrip; - private ToolStripMenuItem toolsToolStripMenuItem; - private ToolStripMenuItem configureToolStripMenuItem; - private ToolStripMenuItem throwExceptionGUIThreadToolStripMenuItem; - private ToolStripMenuItem throwExceptionbackgroundThToolStripMenuItem; - private ToolStripMenuItem throwExceptionBackgroundThreadToolStripMenuItem; - private ToolStripMenuItem loglevelToolStripMenuItem; - private ToolStripMenuItem warnToolStripMenuItem; - private ToolStripMenuItem infoToolStripMenuItem; - private ToolStripMenuItem debugToolStripMenuItem1; - private ToolStripMenuItem disableWordHighlightModeToolStripMenuItem; - private ToolStripMenuItem multifileMaskToolStripMenuItem; - private ToolStripMenuItem multiFileEnabledStripMenuItem; - private ToolStripMenuItem toolStripEncodingISO88591Item; - private ToolStripMenuItem lockInstanceToolStripMenuItem; - private ToolStripMenuItem newFromClipboardToolStripMenuItem; - private ToolStripMenuItem openURIToolStripMenuItem; - 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; - } -} - +using System.Windows.Forms; +using LogExpert.Core.Enums; +using LogExpert.Dialogs; +using WeifenLuo.WinFormsUI.Docking; + +namespace LogExpert.UI.Controls.LogTabWindow +{ + partial class LogTabWindow + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + AutoHideStripSkin autoHideStripSkin1 = new AutoHideStripSkin(); + DockPanelGradient dockPanelGradient1 = new DockPanelGradient(); + TabGradient tabGradient1 = new TabGradient(); + DockPaneStripSkin dockPaneStripSkin1 = new DockPaneStripSkin(); + DockPaneStripGradient dockPaneStripGradient1 = new DockPaneStripGradient(); + TabGradient tabGradient2 = new TabGradient(); + DockPanelGradient dockPanelGradient2 = new DockPanelGradient(); + TabGradient tabGradient3 = new TabGradient(); + DockPaneStripToolWindowGradient dockPaneStripToolWindowGradient1 = new DockPaneStripToolWindowGradient(); + TabGradient tabGradient4 = new TabGradient(); + TabGradient tabGradient5 = new TabGradient(); + DockPanelGradient dockPanelGradient3 = new DockPanelGradient(); + TabGradient tabGradient6 = new TabGradient(); + TabGradient tabGradient7 = new TabGradient(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LogTabWindow)); + statusStrip = new StatusStrip(); + labelLines = new ToolStripStatusLabel(); + labelSize = new ToolStripStatusLabel(); + labelCurrentLine = new ToolStripStatusLabel(); + loadProgessBar = new ToolStripProgressBar(); + labelStatus = new ToolStripStatusLabel(); + mainMenuStrip = new MenuStrip(); + fileToolStripMenuItem = new ToolStripMenuItem(); + openToolStripMenuItem = new ToolStripMenuItem(); + openURIToolStripMenuItem = new ToolStripMenuItem(); + closeFileToolStripMenuItem = new ToolStripMenuItem(); + reloadToolStripMenuItem = new ToolStripMenuItem(); + newFromClipboardToolStripMenuItem = new ToolStripMenuItem(); + ToolStripSeparator1 = new ToolStripSeparator(); + multiFileToolStripMenuItem = new ToolStripMenuItem(); + multiFileEnabledStripMenuItem = new ToolStripMenuItem(); + multifileMaskToolStripMenuItem = new ToolStripMenuItem(); + ToolStripSeparator2 = new ToolStripSeparator(); + loadProjectToolStripMenuItem = new ToolStripMenuItem(); + saveProjectToolStripMenuItem = new ToolStripMenuItem(); + exportBookmarksToolStripMenuItem = new ToolStripMenuItem(); + ToolStripSeparator3 = new ToolStripSeparator(); + lastUsedToolStripMenuItem = new ToolStripMenuItem(); + exitToolStripMenuItem = new ToolStripMenuItem(); + viewNavigateToolStripMenuItem = new ToolStripMenuItem(); + goToLineToolStripMenuItem = new ToolStripMenuItem(); + searchToolStripMenuItem = new ToolStripMenuItem(); + filterToolStripMenuItem = new ToolStripMenuItem(); + bookmarksToolStripMenuItem = new ToolStripMenuItem(); + toggleBookmarkToolStripMenuItem = new ToolStripMenuItem(); + jumpToNextToolStripMenuItem = new ToolStripMenuItem(); + jumpToPrevToolStripMenuItem = new ToolStripMenuItem(); + showBookmarkListToolStripMenuItem = new ToolStripMenuItem(); + columnFinderToolStripMenuItem = new ToolStripMenuItem(); + ToolStripSeparator5 = new ToolStripSeparator(); + toolStripEncodingMenuItem = new ToolStripMenuItem(); + toolStripEncodingASCIIItem = new ToolStripMenuItem(); + toolStripEncodingANSIItem = new ToolStripMenuItem(); + toolStripEncodingISO88591Item = new ToolStripMenuItem(); + toolStripEncodingUTF8Item = new ToolStripMenuItem(); + toolStripEncodingUTF16Item = new ToolStripMenuItem(); + ToolStripSeparator6 = new ToolStripSeparator(); + timeshiftToolStripMenuItem = new ToolStripMenuItem(); + timeshiftMenuTextBox = new ToolStripTextBox(); + ToolStripSeparator4 = new ToolStripSeparator(); + copyMarkedLinesIntoNewTabToolStripMenuItem = new ToolStripMenuItem(); + optionToolStripMenuItem = new ToolStripMenuItem(); + columnizerToolStripMenuItem = new ToolStripMenuItem(); + hilightingToolStripMenuItem1 = new ToolStripMenuItem(); + ToolStripSeparator7 = new ToolStripSeparator(); + settingsToolStripMenuItem = new ToolStripMenuItem(); + ToolStripSeparator9 = new ToolStripSeparator(); + cellSelectModeToolStripMenuItem = new ToolStripMenuItem(); + alwaysOnTopToolStripMenuItem = new ToolStripMenuItem(); + hideLineColumnToolStripMenuItem = new ToolStripMenuItem(); + ToolStripSeparator8 = new ToolStripSeparator(); + lockInstanceToolStripMenuItem = new ToolStripMenuItem(); + toolsToolStripMenuItem = new ToolStripMenuItem(); + configureToolStripMenuItem = new ToolStripMenuItem(); + configureToolStripSeparator = new ToolStripSeparator(); + helpToolStripMenuItem = new ToolStripMenuItem(); + showHelpToolStripMenuItem = new ToolStripMenuItem(); + ToolStripSeparator11 = new ToolStripSeparator(); + aboutToolStripMenuItem = new ToolStripMenuItem(); + debugToolStripMenuItem = new ToolStripMenuItem(); + dumpLogBufferInfoToolStripMenuItem = new ToolStripMenuItem(); + dumpBufferDiagnosticToolStripMenuItem = new ToolStripMenuItem(); + runGCToolStripMenuItem = new ToolStripMenuItem(); + gCInfoToolStripMenuItem = new ToolStripMenuItem(); + throwExceptionGUIThreadToolStripMenuItem = new ToolStripMenuItem(); + throwExceptionbackgroundThToolStripMenuItem = new ToolStripMenuItem(); + throwExceptionBackgroundThreadToolStripMenuItem = new ToolStripMenuItem(); + loglevelToolStripMenuItem = new ToolStripMenuItem(); + warnToolStripMenuItem = new ToolStripMenuItem(); + infoToolStripMenuItem = new ToolStripMenuItem(); + debugToolStripMenuItem1 = new ToolStripMenuItem(); + disableWordHighlightModeToolStripMenuItem = new ToolStripMenuItem(); + host = new CheckBox(); + toolStripContainer = new ToolStripContainer(); + dockPanel = new DockPanel(); + externalToolsToolStrip = new ToolStrip(); + buttonToolStrip = new ToolStrip(); + toolStripButtonOpen = new ToolStripButton(); + lineToolStripSeparatorExtension1 = new ToolStripSeparator(); + toolStripButtonSearch = new ToolStripButton(); + toolStripButtonFilter = new ToolStripButton(); + lineToolStripSeparatorExtension2 = new ToolStripSeparator(); + toolStripButtonBookmark = new ToolStripButton(); + toolStripButtonUp = new ToolStripButton(); + toolStripButtonDown = new ToolStripButton(); + lineToolStripSeparatorExtension3 = new ToolStripSeparator(); + toolStripButtonBubbles = new ToolStripButton(); + lineToolStripSeparatorExtension4 = new ToolStripSeparator(); + toolStripButtonTail = new ToolStripButton(); + lineToolStripSeparatorExtension5 = new ToolStripSeparator(); + groupsComboBoxHighlightGroups = new ToolStripComboBox(); + checkBoxFollowTail = new CheckBox(); + tabContextMenuStrip = new ContextMenuStrip(components); + closeThisTabToolStripMenuItem = new ToolStripMenuItem(); + closeOtherTabsToolStripMenuItem = new ToolStripMenuItem(); + closeAllTabsToolStripMenuItem = new ToolStripMenuItem(); + tabColorToolStripMenuItem = new ToolStripMenuItem(); + tabRenameToolStripMenuItem = new ToolStripMenuItem(); + copyPathToClipboardToolStripMenuItem = new ToolStripMenuItem(); + findInExplorerToolStripMenuItem = new ToolStripMenuItem(); + truncateFileToolStripMenuItem = new ToolStripMenuItem(); + dragControlDateTime = new DateTimeDragControl(); + statusStrip.SuspendLayout(); + mainMenuStrip.SuspendLayout(); + toolStripContainer.ContentPanel.SuspendLayout(); + toolStripContainer.TopToolStripPanel.SuspendLayout(); + toolStripContainer.SuspendLayout(); + buttonToolStrip.SuspendLayout(); + tabContextMenuStrip.SuspendLayout(); + SuspendLayout(); + // + // statusStrip + // + statusStrip.AutoSize = false; + statusStrip.ImageScalingSize = new System.Drawing.Size(24, 24); + statusStrip.Items.AddRange(new ToolStripItem[] { labelLines, labelSize, labelCurrentLine, loadProgessBar, labelStatus }); + 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, 35); + statusStrip.SizingGrip = false; + statusStrip.TabIndex = 5; + statusStrip.Text = "statusStrip1"; + // + // labelLines + // + labelLines.AutoSize = false; + labelLines.BorderSides = ToolStripStatusLabelBorderSides.Left | ToolStripStatusLabelBorderSides.Top | ToolStripStatusLabelBorderSides.Right | ToolStripStatusLabelBorderSides.Bottom; + labelLines.BorderStyle = Border3DStyle.SunkenOuter; + labelLines.Name = "labelLines"; + labelLines.Size = new System.Drawing.Size(26, 35); + labelLines.Text = "0"; + // + // labelSize + // + labelSize.AutoSize = false; + labelSize.BorderSides = ToolStripStatusLabelBorderSides.Left | ToolStripStatusLabelBorderSides.Top | ToolStripStatusLabelBorderSides.Right | ToolStripStatusLabelBorderSides.Bottom; + labelSize.BorderStyle = Border3DStyle.SunkenOuter; + labelSize.Name = "labelSize"; + labelSize.Size = new System.Drawing.Size(26, 35); + labelSize.Text = "0"; + // + // labelCurrentLine + // + labelCurrentLine.AutoSize = false; + labelCurrentLine.BorderSides = ToolStripStatusLabelBorderSides.Left | ToolStripStatusLabelBorderSides.Top | ToolStripStatusLabelBorderSides.Right | ToolStripStatusLabelBorderSides.Bottom; + labelCurrentLine.BorderStyle = Border3DStyle.SunkenOuter; + labelCurrentLine.Name = "labelCurrentLine"; + labelCurrentLine.Size = new System.Drawing.Size(28, 35); + labelCurrentLine.Text = "L:"; + // + // loadProgessBar + // + loadProgessBar.Name = "loadProgessBar"; + loadProgessBar.Size = new System.Drawing.Size(83, 35); + // + // labelStatus + // + labelStatus.Name = "labelStatus"; + labelStatus.Size = new System.Drawing.Size(39, 35); + labelStatus.Text = "Ready"; + // + // mainMenuStrip + // + mainMenuStrip.AllowMerge = false; + mainMenuStrip.Dock = DockStyle.None; + mainMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); + mainMenuStrip.Items.AddRange(new ToolStripItem[] { fileToolStripMenuItem, viewNavigateToolStripMenuItem, optionToolStripMenuItem, toolsToolStripMenuItem, helpToolStripMenuItem, debugToolStripMenuItem }); + mainMenuStrip.LayoutStyle = ToolStripLayoutStyle.Flow; + mainMenuStrip.Location = new System.Drawing.Point(0, 19); + mainMenuStrip.Name = "mainMenuStrip"; + mainMenuStrip.Size = new System.Drawing.Size(1603, 23); + mainMenuStrip.TabIndex = 6; + mainMenuStrip.Text = "menuStrip1"; + // + // fileToolStripMenuItem + // + 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"; + fileToolStripMenuItem.DropDownOpening += OnFileToolStripMenuItemDropDownOpening; + // + // openToolStripMenuItem + // + openToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + openToolStripMenuItem.Image = LogExpert.Resources.File_open; + openToolStripMenuItem.Name = "openToolStripMenuItem"; + openToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.O; + openToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + openToolStripMenuItem.Text = "Open..."; + openToolStripMenuItem.Click += OnOpenToolStripMenuItemClick; + // + // openURIToolStripMenuItem + // + openURIToolStripMenuItem.Name = "openURIToolStripMenuItem"; + openURIToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.U; + openURIToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + openURIToolStripMenuItem.Text = "Open URL..."; + openURIToolStripMenuItem.ToolTipText = "Opens a file by entering a URL which is supported by a file system plugin"; + openURIToolStripMenuItem.Click += OnOpenURIToolStripMenuItemClick; + // + // closeFileToolStripMenuItem + // + closeFileToolStripMenuItem.Image = LogExpert.Resources.Close; + closeFileToolStripMenuItem.Name = "closeFileToolStripMenuItem"; + closeFileToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F4; + closeFileToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + closeFileToolStripMenuItem.Text = "Close File"; + closeFileToolStripMenuItem.Click += OnCloseFileToolStripMenuItemClick; + // + // reloadToolStripMenuItem + // + reloadToolStripMenuItem.Image = LogExpert.Resources.Restart_alt; + reloadToolStripMenuItem.Name = "reloadToolStripMenuItem"; + reloadToolStripMenuItem.ShortcutKeys = Keys.F5; + reloadToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + reloadToolStripMenuItem.Text = "Reload"; + reloadToolStripMenuItem.Click += OnReloadToolStripMenuItemClick; + // + // newFromClipboardToolStripMenuItem + // + newFromClipboardToolStripMenuItem.Name = "newFromClipboardToolStripMenuItem"; + newFromClipboardToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.N; + newFromClipboardToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + newFromClipboardToolStripMenuItem.Text = "New tab from clipboard"; + newFromClipboardToolStripMenuItem.ToolTipText = "Creates a new tab with content from clipboard"; + newFromClipboardToolStripMenuItem.Click += OnNewFromClipboardToolStripMenuItemClick; + // + // ToolStripSeparator1 + // + ToolStripSeparator1.Name = "ToolStripSeparator1"; + ToolStripSeparator1.Size = new System.Drawing.Size(250, 6); + // + // multiFileToolStripMenuItem + // + multiFileToolStripMenuItem.CheckOnClick = true; + multiFileToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { multiFileEnabledStripMenuItem, multifileMaskToolStripMenuItem }); + multiFileToolStripMenuItem.Name = "multiFileToolStripMenuItem"; + multiFileToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + multiFileToolStripMenuItem.Text = "MultiFile"; + multiFileToolStripMenuItem.ToolTipText = "Treat multiple files as one large file (e.g. data.log, data.log.1, data.log.2,...)"; + multiFileToolStripMenuItem.Click += OnMultiFileToolStripMenuItemClick; + // + // multiFileEnabledStripMenuItem + // + multiFileEnabledStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + multiFileEnabledStripMenuItem.CheckOnClick = true; + multiFileEnabledStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + multiFileEnabledStripMenuItem.Name = "multiFileEnabledStripMenuItem"; + multiFileEnabledStripMenuItem.Size = new System.Drawing.Size(165, 22); + multiFileEnabledStripMenuItem.Text = "Enable MultiFile"; + multiFileEnabledStripMenuItem.Click += OnMultiFileEnabledStripMenuItemClick; + // + // multifileMaskToolStripMenuItem + // + multifileMaskToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + multifileMaskToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + multifileMaskToolStripMenuItem.Name = "multifileMaskToolStripMenuItem"; + multifileMaskToolStripMenuItem.Size = new System.Drawing.Size(165, 22); + multifileMaskToolStripMenuItem.Text = "File name mask..."; + multifileMaskToolStripMenuItem.Click += OnMultiFileMaskToolStripMenuItemClick; + // + // ToolStripSeparator2 + // + ToolStripSeparator2.Name = "ToolStripSeparator2"; + ToolStripSeparator2.Size = new System.Drawing.Size(250, 6); + // + // loadProjectToolStripMenuItem + // + loadProjectToolStripMenuItem.Name = "loadProjectToolStripMenuItem"; + loadProjectToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + loadProjectToolStripMenuItem.Text = "Load session..."; + loadProjectToolStripMenuItem.ToolTipText = "Load a saved session (list of log files)"; + loadProjectToolStripMenuItem.Click += OnLoadProjectToolStripMenuItemClick; + // + // saveProjectToolStripMenuItem + // + saveProjectToolStripMenuItem.Name = "saveProjectToolStripMenuItem"; + saveProjectToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + saveProjectToolStripMenuItem.Text = "Save session..."; + saveProjectToolStripMenuItem.ToolTipText = "Save a session (all open tabs)"; + saveProjectToolStripMenuItem.Click += OnSaveProjectToolStripMenuItemClick; + // + // exportBookmarksToolStripMenuItem + // + exportBookmarksToolStripMenuItem.Name = "exportBookmarksToolStripMenuItem"; + exportBookmarksToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + exportBookmarksToolStripMenuItem.Text = "Export bookmarks..."; + exportBookmarksToolStripMenuItem.ToolTipText = "Write a list of bookmarks and their comments to a CSV file"; + exportBookmarksToolStripMenuItem.Click += OnExportBookmarksToolStripMenuItemClick; + // + // ToolStripSeparator3 + // + ToolStripSeparator3.Name = "ToolStripSeparator3"; + ToolStripSeparator3.Size = new System.Drawing.Size(250, 6); + // + // lastUsedToolStripMenuItem + // + lastUsedToolStripMenuItem.Name = "lastUsedToolStripMenuItem"; + lastUsedToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + lastUsedToolStripMenuItem.Text = "Last used"; + // + // exitToolStripMenuItem + // + exitToolStripMenuItem.Image = LogExpert.Resources.Exit; + exitToolStripMenuItem.Name = "exitToolStripMenuItem"; + exitToolStripMenuItem.ShortcutKeys = Keys.Alt | Keys.F4; + exitToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + exitToolStripMenuItem.Text = "Exit"; + exitToolStripMenuItem.Click += OnExitToolStripMenuItemClick; + // + // viewNavigateToolStripMenuItem + // + 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"; + // + // goToLineToolStripMenuItem + // + goToLineToolStripMenuItem.Name = "goToLineToolStripMenuItem"; + goToLineToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.G; + goToLineToolStripMenuItem.Size = new System.Drawing.Size(189, 30); + goToLineToolStripMenuItem.Text = "Go to line..."; + goToLineToolStripMenuItem.Click += OnGoToLineToolStripMenuItemClick; + // + // searchToolStripMenuItem + // + searchToolStripMenuItem.Name = "searchToolStripMenuItem"; + searchToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F; + searchToolStripMenuItem.Size = new System.Drawing.Size(189, 30); + searchToolStripMenuItem.Text = "Search..."; + searchToolStripMenuItem.Click += OnSearchToolStripMenuItemClick; + // + // filterToolStripMenuItem + // + filterToolStripMenuItem.Image = LogExpert.Resources.Filter; + filterToolStripMenuItem.Name = "filterToolStripMenuItem"; + filterToolStripMenuItem.ShortcutKeys = Keys.F4; + filterToolStripMenuItem.Size = new System.Drawing.Size(189, 30); + filterToolStripMenuItem.Text = "Filter"; + filterToolStripMenuItem.Click += OnFilterToolStripMenuItemClick; + // + // bookmarksToolStripMenuItem + // + bookmarksToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { toggleBookmarkToolStripMenuItem, jumpToNextToolStripMenuItem, jumpToPrevToolStripMenuItem, showBookmarkListToolStripMenuItem }); + bookmarksToolStripMenuItem.Name = "bookmarksToolStripMenuItem"; + bookmarksToolStripMenuItem.Size = new System.Drawing.Size(189, 30); + bookmarksToolStripMenuItem.Text = "Bookmarks"; + // + // toggleBookmarkToolStripMenuItem + // + toggleBookmarkToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + toggleBookmarkToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + toggleBookmarkToolStripMenuItem.Image = LogExpert.Resources.Bookmark_add; + toggleBookmarkToolStripMenuItem.Name = "toggleBookmarkToolStripMenuItem"; + toggleBookmarkToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.F2; + toggleBookmarkToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + toggleBookmarkToolStripMenuItem.Text = "Toggle Bookmark"; + toggleBookmarkToolStripMenuItem.Click += OnToggleBookmarkToolStripMenuItemClick; + // + // jumpToNextToolStripMenuItem + // + jumpToNextToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + jumpToNextToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + jumpToNextToolStripMenuItem.Image = LogExpert.Resources.ArrowDown; + jumpToNextToolStripMenuItem.Name = "jumpToNextToolStripMenuItem"; + jumpToNextToolStripMenuItem.ShortcutKeys = Keys.F2; + jumpToNextToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + jumpToNextToolStripMenuItem.Text = "Jump to next"; + jumpToNextToolStripMenuItem.Click += OnJumpToNextToolStripMenuItemClick; + // + // jumpToPrevToolStripMenuItem + // + jumpToPrevToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + jumpToPrevToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + jumpToPrevToolStripMenuItem.Image = LogExpert.Resources.ArrowUp; + jumpToPrevToolStripMenuItem.Name = "jumpToPrevToolStripMenuItem"; + jumpToPrevToolStripMenuItem.ShortcutKeys = Keys.Shift | Keys.F2; + jumpToPrevToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + jumpToPrevToolStripMenuItem.Text = "Jump to prev"; + jumpToPrevToolStripMenuItem.Click += OnJumpToPrevToolStripMenuItemClick; + // + // showBookmarkListToolStripMenuItem + // + showBookmarkListToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + showBookmarkListToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + showBookmarkListToolStripMenuItem.Name = "showBookmarkListToolStripMenuItem"; + showBookmarkListToolStripMenuItem.ShortcutKeys = Keys.F6; + showBookmarkListToolStripMenuItem.Size = new System.Drawing.Size(253, 30); + showBookmarkListToolStripMenuItem.Text = "Bookmark list"; + showBookmarkListToolStripMenuItem.Click += OnShowBookmarkListToolStripMenuItemClick; + // + // columnFinderToolStripMenuItem + // + columnFinderToolStripMenuItem.CheckOnClick = true; + columnFinderToolStripMenuItem.Name = "columnFinderToolStripMenuItem"; + columnFinderToolStripMenuItem.ShortcutKeys = Keys.F8; + columnFinderToolStripMenuItem.Size = new System.Drawing.Size(189, 30); + columnFinderToolStripMenuItem.Text = "Column finder"; + columnFinderToolStripMenuItem.Click += OnColumnFinderToolStripMenuItemClick; + // + // ToolStripSeparator5 + // + ToolStripSeparator5.Name = "ToolStripSeparator5"; + ToolStripSeparator5.Size = new System.Drawing.Size(186, 6); + // + // toolStripEncodingMenuItem + // + toolStripEncodingMenuItem.DropDownItems.AddRange(new ToolStripItem[] { toolStripEncodingASCIIItem, toolStripEncodingANSIItem, toolStripEncodingISO88591Item, toolStripEncodingUTF8Item, toolStripEncodingUTF16Item }); + toolStripEncodingMenuItem.Name = "toolStripEncodingMenuItem"; + toolStripEncodingMenuItem.Size = new System.Drawing.Size(189, 30); + toolStripEncodingMenuItem.Text = "Encoding"; + // + // toolStripEncodingASCIIItem + // + toolStripEncodingASCIIItem.BackColor = System.Drawing.SystemColors.Control; + toolStripEncodingASCIIItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + toolStripEncodingASCIIItem.Name = "toolStripEncodingASCIIItem"; + toolStripEncodingASCIIItem.Size = new System.Drawing.Size(132, 22); + toolStripEncodingASCIIItem.Tag = ""; + toolStripEncodingASCIIItem.Text = "ASCII"; + toolStripEncodingASCIIItem.Click += OnASCIIToolStripMenuItemClick; + // + // toolStripEncodingANSIItem + // + toolStripEncodingANSIItem.BackColor = System.Drawing.SystemColors.Control; + toolStripEncodingANSIItem.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + toolStripEncodingANSIItem.Name = "toolStripEncodingANSIItem"; + toolStripEncodingANSIItem.Size = new System.Drawing.Size(132, 22); + toolStripEncodingANSIItem.Tag = ""; + toolStripEncodingANSIItem.Text = "ANSI"; + toolStripEncodingANSIItem.Click += OnANSIToolStripMenuItemClick; + // + // toolStripEncodingISO88591Item + // + toolStripEncodingISO88591Item.BackColor = System.Drawing.SystemColors.Control; + toolStripEncodingISO88591Item.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + toolStripEncodingISO88591Item.Name = "toolStripEncodingISO88591Item"; + toolStripEncodingISO88591Item.Size = new System.Drawing.Size(132, 22); + toolStripEncodingISO88591Item.Text = "ISO-8859-1"; + toolStripEncodingISO88591Item.Click += OnISO88591ToolStripMenuItemClick; + // + // toolStripEncodingUTF8Item + // + toolStripEncodingUTF8Item.BackColor = System.Drawing.SystemColors.Control; + toolStripEncodingUTF8Item.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + toolStripEncodingUTF8Item.Name = "toolStripEncodingUTF8Item"; + toolStripEncodingUTF8Item.Size = new System.Drawing.Size(132, 22); + toolStripEncodingUTF8Item.Text = "UTF8"; + toolStripEncodingUTF8Item.Click += OnUTF8ToolStripMenuItemClick; + // + // toolStripEncodingUTF16Item + // + toolStripEncodingUTF16Item.BackColor = System.Drawing.SystemColors.Control; + toolStripEncodingUTF16Item.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + toolStripEncodingUTF16Item.Name = "toolStripEncodingUTF16Item"; + toolStripEncodingUTF16Item.Size = new System.Drawing.Size(132, 22); + toolStripEncodingUTF16Item.Text = "Unicode"; + toolStripEncodingUTF16Item.Click += OnUTF16ToolStripMenuItemClick; + // + // ToolStripSeparator6 + // + ToolStripSeparator6.Name = "ToolStripSeparator6"; + ToolStripSeparator6.Size = new System.Drawing.Size(186, 6); + // + // timeshiftToolStripMenuItem + // + timeshiftToolStripMenuItem.CheckOnClick = true; + timeshiftToolStripMenuItem.Name = "timeshiftToolStripMenuItem"; + timeshiftToolStripMenuItem.Size = new System.Drawing.Size(189, 30); + timeshiftToolStripMenuItem.Text = "Timeshift"; + timeshiftToolStripMenuItem.ToolTipText = "If supported by the columnizer, you can set an offset to the displayed log time"; + timeshiftToolStripMenuItem.CheckStateChanged += OnTimeShiftToolStripMenuItemCheckStateChanged; + // + // timeshiftMenuTextBox + // + timeshiftMenuTextBox.BorderStyle = BorderStyle.FixedSingle; + timeshiftMenuTextBox.Enabled = false; + timeshiftMenuTextBox.Font = new System.Drawing.Font("Segoe UI", 9F); + timeshiftMenuTextBox.Name = "timeshiftMenuTextBox"; + timeshiftMenuTextBox.Size = new System.Drawing.Size(100, 23); + timeshiftMenuTextBox.Text = "+00:00:00.000"; + timeshiftMenuTextBox.ToolTipText = "Time offset (hh:mm:ss.fff)"; + timeshiftMenuTextBox.KeyDown += OnTimeShiftMenuTextBoxKeyDown; + // + // ToolStripSeparator4 + // + ToolStripSeparator4.Name = "ToolStripSeparator4"; + ToolStripSeparator4.Size = new System.Drawing.Size(186, 6); + // + // copyMarkedLinesIntoNewTabToolStripMenuItem + // + copyMarkedLinesIntoNewTabToolStripMenuItem.Name = "copyMarkedLinesIntoNewTabToolStripMenuItem"; + copyMarkedLinesIntoNewTabToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.T; + copyMarkedLinesIntoNewTabToolStripMenuItem.Size = new System.Drawing.Size(189, 30); + copyMarkedLinesIntoNewTabToolStripMenuItem.Text = "Copy to Tab"; + copyMarkedLinesIntoNewTabToolStripMenuItem.ToolTipText = "Copies all selected lines into a new tab page"; + copyMarkedLinesIntoNewTabToolStripMenuItem.Click += OnCopyMarkedLinesIntoNewTabToolStripMenuItemClick; + // + // optionToolStripMenuItem + // + 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"; + optionToolStripMenuItem.DropDownOpening += OnOptionToolStripMenuItemDropDownOpening; + // + // columnizerToolStripMenuItem + // + columnizerToolStripMenuItem.Name = "columnizerToolStripMenuItem"; + columnizerToolStripMenuItem.Size = new System.Drawing.Size(224, 30); + columnizerToolStripMenuItem.Text = "Columnizer..."; + columnizerToolStripMenuItem.ToolTipText = "Splits various kinds of logfiles into fixed columns"; + columnizerToolStripMenuItem.Click += OnSelectFilterToolStripMenuItemClick; + // + // hilightingToolStripMenuItem1 + // + hilightingToolStripMenuItem1.Name = "hilightingToolStripMenuItem1"; + hilightingToolStripMenuItem1.Size = new System.Drawing.Size(224, 30); + hilightingToolStripMenuItem1.Text = "Highlighting and triggers..."; + hilightingToolStripMenuItem1.Click += OnHighlightingToolStripMenuItemClick; + // + // ToolStripSeparator7 + // + ToolStripSeparator7.Name = "ToolStripSeparator7"; + ToolStripSeparator7.Size = new System.Drawing.Size(221, 6); + // + // settingsToolStripMenuItem + // + settingsToolStripMenuItem.Image = LogExpert.Resources.Settings; + settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; + settingsToolStripMenuItem.Size = new System.Drawing.Size(224, 30); + settingsToolStripMenuItem.Text = "Settings..."; + settingsToolStripMenuItem.Click += OnSettingsToolStripMenuItemClick; + // + // ToolStripSeparator9 + // + ToolStripSeparator9.Name = "ToolStripSeparator9"; + ToolStripSeparator9.Size = new System.Drawing.Size(221, 6); + // + // cellSelectModeToolStripMenuItem + // + cellSelectModeToolStripMenuItem.CheckOnClick = true; + cellSelectModeToolStripMenuItem.Name = "cellSelectModeToolStripMenuItem"; + cellSelectModeToolStripMenuItem.Size = new System.Drawing.Size(224, 30); + cellSelectModeToolStripMenuItem.Text = "Cell select mode"; + cellSelectModeToolStripMenuItem.ToolTipText = "Switches between foll row selection and single cell selection mode"; + cellSelectModeToolStripMenuItem.Click += OnCellSelectModeToolStripMenuItemClick; + // + // alwaysOnTopToolStripMenuItem + // + alwaysOnTopToolStripMenuItem.CheckOnClick = true; + alwaysOnTopToolStripMenuItem.Name = "alwaysOnTopToolStripMenuItem"; + alwaysOnTopToolStripMenuItem.Size = new System.Drawing.Size(224, 30); + alwaysOnTopToolStripMenuItem.Text = "Always on top"; + alwaysOnTopToolStripMenuItem.Click += OnAlwaysOnTopToolStripMenuItemClick; + // + // hideLineColumnToolStripMenuItem + // + hideLineColumnToolStripMenuItem.CheckOnClick = true; + hideLineColumnToolStripMenuItem.Name = "hideLineColumnToolStripMenuItem"; + hideLineColumnToolStripMenuItem.Size = new System.Drawing.Size(224, 30); + hideLineColumnToolStripMenuItem.Text = "Hide line column"; + hideLineColumnToolStripMenuItem.Click += OnHideLineColumnToolStripMenuItemClick; + // + // ToolStripSeparator8 + // + ToolStripSeparator8.Name = "ToolStripSeparator8"; + ToolStripSeparator8.Size = new System.Drawing.Size(221, 6); + // + // lockInstanceToolStripMenuItem + // + lockInstanceToolStripMenuItem.Name = "lockInstanceToolStripMenuItem"; + lockInstanceToolStripMenuItem.Size = new System.Drawing.Size(224, 30); + lockInstanceToolStripMenuItem.Text = "Lock instance"; + lockInstanceToolStripMenuItem.ToolTipText = "When enabled all new launched LogExpert instances will redirect to this window"; + lockInstanceToolStripMenuItem.Click += OnLockInstanceToolStripMenuItemClick; + // + // toolsToolStripMenuItem + // + toolsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { configureToolStripMenuItem, configureToolStripSeparator }); + toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; + toolsToolStripMenuItem.Size = new System.Drawing.Size(47, 19); + toolsToolStripMenuItem.Text = "Tools"; + toolsToolStripMenuItem.ToolTipText = "Launch external tools (configure in the settings)"; + toolsToolStripMenuItem.DropDownItemClicked += OnToolsToolStripMenuItemDropDownItemClicked; + // + // configureToolStripMenuItem + // + configureToolStripMenuItem.Name = "configureToolStripMenuItem"; + configureToolStripMenuItem.Size = new System.Drawing.Size(136, 22); + configureToolStripMenuItem.Text = "Configure..."; + configureToolStripMenuItem.Click += OnConfigureToolStripMenuItemClick; + // + // configureToolStripSeparator + // + configureToolStripSeparator.Name = "configureToolStripSeparator"; + configureToolStripSeparator.Size = new System.Drawing.Size(133, 6); + // + // helpToolStripMenuItem + // + helpToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { showHelpToolStripMenuItem, ToolStripSeparator11, aboutToolStripMenuItem }); + helpToolStripMenuItem.Name = "helpToolStripMenuItem"; + helpToolStripMenuItem.Size = new System.Drawing.Size(44, 19); + helpToolStripMenuItem.Text = "Help"; + // + // showHelpToolStripMenuItem + // + showHelpToolStripMenuItem.Name = "showHelpToolStripMenuItem"; + showHelpToolStripMenuItem.ShortcutKeys = Keys.F1; + showHelpToolStripMenuItem.Size = new System.Drawing.Size(148, 22); + showHelpToolStripMenuItem.Text = "Show help"; + showHelpToolStripMenuItem.Click += OnShowHelpToolStripMenuItemClick; + // + // ToolStripSeparator11 + // + ToolStripSeparator11.Name = "ToolStripSeparator11"; + ToolStripSeparator11.Size = new System.Drawing.Size(145, 6); + // + // aboutToolStripMenuItem + // + aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; + aboutToolStripMenuItem.Size = new System.Drawing.Size(148, 22); + aboutToolStripMenuItem.Text = "About"; + aboutToolStripMenuItem.Click += OnAboutToolStripMenuItemClick; + // + // debugToolStripMenuItem + // + debugToolStripMenuItem.Alignment = ToolStripItemAlignment.Right; + debugToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { dumpLogBufferInfoToolStripMenuItem, dumpBufferDiagnosticToolStripMenuItem, runGCToolStripMenuItem, gCInfoToolStripMenuItem, throwExceptionGUIThreadToolStripMenuItem, throwExceptionbackgroundThToolStripMenuItem, throwExceptionBackgroundThreadToolStripMenuItem, loglevelToolStripMenuItem, disableWordHighlightModeToolStripMenuItem }); + debugToolStripMenuItem.Name = "debugToolStripMenuItem"; + debugToolStripMenuItem.Size = new System.Drawing.Size(54, 19); + debugToolStripMenuItem.Text = "Debug"; + // + // dumpLogBufferInfoToolStripMenuItem + // + dumpLogBufferInfoToolStripMenuItem.Name = "dumpLogBufferInfoToolStripMenuItem"; + dumpLogBufferInfoToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + dumpLogBufferInfoToolStripMenuItem.Text = "Dump LogBuffer info"; + dumpLogBufferInfoToolStripMenuItem.Click += OnDumpLogBufferInfoToolStripMenuItemClick; + // + // dumpBufferDiagnosticToolStripMenuItem + // + dumpBufferDiagnosticToolStripMenuItem.Name = "dumpBufferDiagnosticToolStripMenuItem"; + dumpBufferDiagnosticToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + dumpBufferDiagnosticToolStripMenuItem.Text = "Dump buffer diagnostic"; + dumpBufferDiagnosticToolStripMenuItem.Click += OnDumpBufferDiagnosticToolStripMenuItemClick; + // + // runGCToolStripMenuItem + // + runGCToolStripMenuItem.Name = "runGCToolStripMenuItem"; + runGCToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + runGCToolStripMenuItem.Text = "Run GC"; + runGCToolStripMenuItem.Click += OnRunGCToolStripMenuItemClick; + // + // gCInfoToolStripMenuItem + // + gCInfoToolStripMenuItem.Name = "gCInfoToolStripMenuItem"; + gCInfoToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + gCInfoToolStripMenuItem.Text = "Dump GC info"; + gCInfoToolStripMenuItem.Click += OnGCInfoToolStripMenuItemClick; + // + // throwExceptionGUIThreadToolStripMenuItem + // + throwExceptionGUIThreadToolStripMenuItem.Name = "throwExceptionGUIThreadToolStripMenuItem"; + throwExceptionGUIThreadToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + throwExceptionGUIThreadToolStripMenuItem.Text = "Throw exception (GUI Thread)"; + throwExceptionGUIThreadToolStripMenuItem.Click += OnThrowExceptionGUIThreadToolStripMenuItemClick; + // + // throwExceptionbackgroundThToolStripMenuItem + // + throwExceptionbackgroundThToolStripMenuItem.Name = "throwExceptionbackgroundThToolStripMenuItem"; + throwExceptionbackgroundThToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + throwExceptionbackgroundThToolStripMenuItem.Text = "Throw exception (Async delegate)"; + throwExceptionbackgroundThToolStripMenuItem.Click += OnThrowExceptionBackgroundThToolStripMenuItemClick; + // + // throwExceptionBackgroundThreadToolStripMenuItem + // + throwExceptionBackgroundThreadToolStripMenuItem.Name = "throwExceptionBackgroundThreadToolStripMenuItem"; + throwExceptionBackgroundThreadToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + throwExceptionBackgroundThreadToolStripMenuItem.Text = "Throw exception (background thread)"; + throwExceptionBackgroundThreadToolStripMenuItem.Click += OnThrowExceptionBackgroundThreadToolStripMenuItemClick; + // + // loglevelToolStripMenuItem + // + loglevelToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { warnToolStripMenuItem, infoToolStripMenuItem, debugToolStripMenuItem1 }); + loglevelToolStripMenuItem.Name = "loglevelToolStripMenuItem"; + loglevelToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + loglevelToolStripMenuItem.Text = "Loglevel"; + loglevelToolStripMenuItem.DropDownOpening += OnLogLevelToolStripMenuItemDropDownOpening; + loglevelToolStripMenuItem.Click += OnLogLevelToolStripMenuItemClick; + // + // warnToolStripMenuItem + // + warnToolStripMenuItem.Name = "warnToolStripMenuItem"; + warnToolStripMenuItem.Size = new System.Drawing.Size(109, 22); + warnToolStripMenuItem.Text = "Warn"; + warnToolStripMenuItem.Click += OnWarnToolStripMenuItemClick; + // + // infoToolStripMenuItem + // + infoToolStripMenuItem.Name = "infoToolStripMenuItem"; + infoToolStripMenuItem.Size = new System.Drawing.Size(109, 22); + infoToolStripMenuItem.Text = "Info"; + infoToolStripMenuItem.Click += OnInfoToolStripMenuItemClick; + // + // debugToolStripMenuItem1 + // + debugToolStripMenuItem1.Name = "debugToolStripMenuItem1"; + debugToolStripMenuItem1.Size = new System.Drawing.Size(109, 22); + debugToolStripMenuItem1.Text = "Debug"; + debugToolStripMenuItem1.Click += OnDebugToolStripMenuItemClick; + // + // disableWordHighlightModeToolStripMenuItem + // + disableWordHighlightModeToolStripMenuItem.CheckOnClick = true; + disableWordHighlightModeToolStripMenuItem.Name = "disableWordHighlightModeToolStripMenuItem"; + disableWordHighlightModeToolStripMenuItem.Size = new System.Drawing.Size(274, 22); + disableWordHighlightModeToolStripMenuItem.Text = "Disable word highlight mode"; + disableWordHighlightModeToolStripMenuItem.Click += OnDisableWordHighlightModeToolStripMenuItemClick; + // + // host + // + host.AccessibleName = "host"; + host.AutoSize = true; + host.BackColor = System.Drawing.Color.Transparent; + host.Location = new System.Drawing.Point(9, 1); + host.Name = "host"; + host.Size = new System.Drawing.Size(80, 22); + host.TabIndex = 7; + host.Text = "Follow tail"; + host.UseVisualStyleBackColor = false; + // + // toolStripContainer + // + // + // toolStripContainer.BottomToolStripPanel + // + toolStripContainer.BottomToolStripPanel.RenderMode = ToolStripRenderMode.System; + toolStripContainer.BottomToolStripPanelVisible = false; + // + // toolStripContainer.ContentPanel + // + toolStripContainer.ContentPanel.Controls.Add(dockPanel); + toolStripContainer.ContentPanel.Margin = new Padding(0); + toolStripContainer.ContentPanel.Size = new System.Drawing.Size(1603, 881); + toolStripContainer.Dock = DockStyle.Fill; + // + // toolStripContainer.LeftToolStripPanel + // + toolStripContainer.LeftToolStripPanel.Enabled = false; + toolStripContainer.LeftToolStripPanelVisible = false; + toolStripContainer.Location = new System.Drawing.Point(0, 0); + toolStripContainer.Margin = new Padding(0); + toolStripContainer.Name = "toolStripContainer"; + // + // toolStripContainer.RightToolStripPanel + // + toolStripContainer.RightToolStripPanel.Enabled = false; + toolStripContainer.RightToolStripPanelVisible = false; + toolStripContainer.Size = new System.Drawing.Size(1603, 954); + toolStripContainer.TabIndex = 13; + toolStripContainer.Text = "toolStripContainer1"; + // + // toolStripContainer.TopToolStripPanel + // + toolStripContainer.TopToolStripPanel.Controls.Add(externalToolsToolStrip); + toolStripContainer.TopToolStripPanel.Controls.Add(mainMenuStrip); + toolStripContainer.TopToolStripPanel.Controls.Add(buttonToolStrip); + // + // dockPanel + // + dockPanel.ActiveAutoHideContent = null; + dockPanel.DefaultFloatWindowSize = new System.Drawing.Size(600, 400); + dockPanel.Dock = DockStyle.Fill; + dockPanel.DockBackColor = System.Drawing.SystemColors.Control; + dockPanel.DocumentStyle = DocumentStyle.DockingWindow; + dockPanel.Location = new System.Drawing.Point(0, 0); + dockPanel.Margin = new Padding(0); + dockPanel.Name = "dockPanel"; + dockPanel.ShowDocumentIcon = true; + dockPanel.Size = new System.Drawing.Size(1603, 881); + dockPanelGradient1.EndColor = System.Drawing.SystemColors.Control; + dockPanelGradient1.StartColor = System.Drawing.SystemColors.Control; + autoHideStripSkin1.DockStripGradient = dockPanelGradient1; + tabGradient1.EndColor = System.Drawing.SystemColors.Control; + tabGradient1.StartColor = System.Drawing.SystemColors.Control; + tabGradient1.TextColor = System.Drawing.SystemColors.ControlText; + autoHideStripSkin1.TabGradient = tabGradient1; + autoHideStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F); + tabGradient2.EndColor = System.Drawing.SystemColors.Control; + tabGradient2.StartColor = System.Drawing.SystemColors.Control; + tabGradient2.TextColor = System.Drawing.SystemColors.ControlText; + dockPaneStripGradient1.ActiveTabGradient = tabGradient2; + dockPanelGradient2.EndColor = System.Drawing.SystemColors.Control; + dockPanelGradient2.StartColor = System.Drawing.SystemColors.Control; + dockPaneStripGradient1.DockStripGradient = dockPanelGradient2; + tabGradient3.EndColor = System.Drawing.SystemColors.ControlLight; + tabGradient3.StartColor = System.Drawing.SystemColors.ControlLight; + tabGradient3.TextColor = System.Drawing.SystemColors.ControlText; + dockPaneStripGradient1.InactiveTabGradient = tabGradient3; + dockPaneStripSkin1.DocumentGradient = dockPaneStripGradient1; + dockPaneStripSkin1.TextFont = new System.Drawing.Font("Segoe UI", 9F); + tabGradient4.EndColor = System.Drawing.SystemColors.ActiveCaption; + tabGradient4.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical; + tabGradient4.StartColor = System.Drawing.SystemColors.GradientActiveCaption; + tabGradient4.TextColor = System.Drawing.SystemColors.ActiveCaptionText; + dockPaneStripToolWindowGradient1.ActiveCaptionGradient = tabGradient4; + tabGradient5.EndColor = System.Drawing.SystemColors.Control; + tabGradient5.StartColor = System.Drawing.SystemColors.Control; + tabGradient5.TextColor = System.Drawing.SystemColors.ControlText; + dockPaneStripToolWindowGradient1.ActiveTabGradient = tabGradient5; + dockPanelGradient3.EndColor = System.Drawing.SystemColors.ControlLight; + dockPanelGradient3.StartColor = System.Drawing.SystemColors.ControlLight; + dockPaneStripToolWindowGradient1.DockStripGradient = dockPanelGradient3; + tabGradient6.EndColor = System.Drawing.SystemColors.InactiveCaption; + tabGradient6.LinearGradientMode = System.Drawing.Drawing2D.LinearGradientMode.Vertical; + tabGradient6.StartColor = System.Drawing.SystemColors.GradientInactiveCaption; + tabGradient6.TextColor = System.Drawing.SystemColors.InactiveCaptionText; + dockPaneStripToolWindowGradient1.InactiveCaptionGradient = tabGradient6; + tabGradient7.EndColor = System.Drawing.Color.Transparent; + tabGradient7.StartColor = System.Drawing.Color.Transparent; + tabGradient7.TextColor = System.Drawing.SystemColors.Control; + dockPaneStripToolWindowGradient1.InactiveTabGradient = tabGradient7; + dockPaneStripSkin1.ToolWindowGradient = dockPaneStripToolWindowGradient1; + dockPanel.Theme = new VS2015LightTheme(); + dockPanel.Theme.Skin.DockPaneStripSkin = dockPaneStripSkin1; + dockPanel.Theme.Skin.AutoHideStripSkin = autoHideStripSkin1; + dockPanel.TabIndex = 14; + dockPanel.ActiveContentChanged += OnDockPanelActiveContentChanged; + // + // externalToolsToolStrip + // + externalToolsToolStrip.AllowMerge = false; + externalToolsToolStrip.Dock = DockStyle.None; + externalToolsToolStrip.ImageScalingSize = new System.Drawing.Size(24, 24); + externalToolsToolStrip.LayoutStyle = ToolStripLayoutStyle.Flow; + externalToolsToolStrip.Location = new System.Drawing.Point(8, 0); + externalToolsToolStrip.Name = "externalToolsToolStrip"; + externalToolsToolStrip.Size = new System.Drawing.Size(32, 19); + externalToolsToolStrip.TabIndex = 8; + externalToolsToolStrip.ItemClicked += OnExternalToolsToolStripItemClicked; + // + // buttonToolStrip + // + buttonToolStrip.AllowMerge = false; + buttonToolStrip.Dock = DockStyle.None; + buttonToolStrip.ImageScalingSize = new System.Drawing.Size(24, 24); + buttonToolStrip.Items.AddRange(new ToolStripItem[] { toolStripButtonOpen, lineToolStripSeparatorExtension1, toolStripButtonSearch, toolStripButtonFilter, lineToolStripSeparatorExtension2, toolStripButtonBookmark, toolStripButtonUp, toolStripButtonDown, lineToolStripSeparatorExtension3, toolStripButtonBubbles, lineToolStripSeparatorExtension4, toolStripButtonTail, lineToolStripSeparatorExtension5, groupsComboBoxHighlightGroups }); + buttonToolStrip.LayoutStyle = ToolStripLayoutStyle.Flow; + buttonToolStrip.Location = new System.Drawing.Point(3, 42); + buttonToolStrip.Name = "buttonToolStrip"; + buttonToolStrip.Size = new System.Drawing.Size(406, 31); + buttonToolStrip.TabIndex = 7; + // + // toolStripButtonOpen + // + toolStripButtonOpen.DisplayStyle = ToolStripItemDisplayStyle.Image; + toolStripButtonOpen.Image = LogExpert.Resources.File_open; + toolStripButtonOpen.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonOpen.Name = "toolStripButtonOpen"; + toolStripButtonOpen.Size = new System.Drawing.Size(28, 28); + toolStripButtonOpen.Text = "Open File"; + toolStripButtonOpen.ToolTipText = "Open file"; + toolStripButtonOpen.Click += OnToolStripButtonOpenClick; + // + // lineToolStripSeparatorExtension1 + // + lineToolStripSeparatorExtension1.Name = "lineToolStripSeparatorExtension1"; + lineToolStripSeparatorExtension1.Size = new System.Drawing.Size(6, 23); + // + // toolStripButtonSearch + // + toolStripButtonSearch.DisplayStyle = ToolStripItemDisplayStyle.Image; + toolStripButtonSearch.Image = LogExpert.Resources.Search; + toolStripButtonSearch.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonSearch.Name = "toolStripButtonSearch"; + toolStripButtonSearch.Size = new System.Drawing.Size(28, 28); + toolStripButtonSearch.Text = "Search"; + toolStripButtonSearch.ToolTipText = "Search"; + toolStripButtonSearch.Click += OnToolStripButtonSearchClick; + // + // toolStripButtonFilter + // + toolStripButtonFilter.DisplayStyle = ToolStripItemDisplayStyle.Image; + toolStripButtonFilter.Image = LogExpert.Resources.Filter; + toolStripButtonFilter.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonFilter.Name = "toolStripButtonFilter"; + toolStripButtonFilter.Size = new System.Drawing.Size(28, 28); + toolStripButtonFilter.Text = "Filter"; + toolStripButtonFilter.ToolTipText = "Filter window"; + toolStripButtonFilter.Click += OnToolStripButtonFilterClick; + // + // lineToolStripSeparatorExtension2 + // + lineToolStripSeparatorExtension2.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + lineToolStripSeparatorExtension2.Name = "lineToolStripSeparatorExtension2"; + lineToolStripSeparatorExtension2.Size = new System.Drawing.Size(6, 23); + // + // toolStripButtonBookmark + // + toolStripButtonBookmark.DisplayStyle = ToolStripItemDisplayStyle.Image; + toolStripButtonBookmark.Image = LogExpert.Resources.Bookmark_add; + toolStripButtonBookmark.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonBookmark.Name = "toolStripButtonBookmark"; + toolStripButtonBookmark.Size = new System.Drawing.Size(28, 28); + toolStripButtonBookmark.Text = "Toggle Bookmark"; + toolStripButtonBookmark.ToolTipText = "Toggle bookmark"; + toolStripButtonBookmark.Click += OnToolStripButtonBookmarkClick; + // + // toolStripButtonUp + // + toolStripButtonUp.DisplayStyle = ToolStripItemDisplayStyle.Image; + toolStripButtonUp.Image = LogExpert.Resources.ArrowUp; + toolStripButtonUp.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonUp.Name = "toolStripButtonUp"; + toolStripButtonUp.Size = new System.Drawing.Size(28, 28); + toolStripButtonUp.Text = "Previous Bookmark"; + toolStripButtonUp.ToolTipText = "Go to previous bookmark"; + toolStripButtonUp.Click += OnToolStripButtonUpClick; + // + // toolStripButtonDown + // + toolStripButtonDown.DisplayStyle = ToolStripItemDisplayStyle.Image; + toolStripButtonDown.Image = LogExpert.Resources.ArrowDown; + toolStripButtonDown.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonDown.Name = "toolStripButtonDown"; + toolStripButtonDown.Size = new System.Drawing.Size(28, 28); + toolStripButtonDown.Text = "Next Bookmark"; + toolStripButtonDown.ToolTipText = "Go to next bookmark"; + toolStripButtonDown.Click += OnToolStripButtonDownClick; + // + // lineToolStripSeparatorExtension3 + // + lineToolStripSeparatorExtension3.Name = "lineToolStripSeparatorExtension3"; + lineToolStripSeparatorExtension3.Size = new System.Drawing.Size(6, 23); + // + // toolStripButtonBubbles + // + toolStripButtonBubbles.CheckOnClick = true; + toolStripButtonBubbles.DisplayStyle = ToolStripItemDisplayStyle.Image; + toolStripButtonBubbles.Image = LogExpert.Resources.bookmark_bubbles; + toolStripButtonBubbles.ImageAlign = System.Drawing.ContentAlignment.BottomCenter; + toolStripButtonBubbles.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonBubbles.Name = "toolStripButtonBubbles"; + toolStripButtonBubbles.Size = new System.Drawing.Size(28, 28); + toolStripButtonBubbles.Text = "Show bookmark bubbles"; + toolStripButtonBubbles.Click += OnToolStripButtonBubblesClick; + // + // lineToolStripSeparatorExtension4 + // + lineToolStripSeparatorExtension4.Name = "lineToolStripSeparatorExtension4"; + lineToolStripSeparatorExtension4.Size = new System.Drawing.Size(6, 23); + // + // toolStripButtonTail + // + toolStripButtonTail.DisplayStyle = ToolStripItemDisplayStyle.Text; + toolStripButtonTail.Image = (System.Drawing.Image)resources.GetObject("toolStripButtonTail.Image"); + toolStripButtonTail.ImageTransparentColor = System.Drawing.Color.Magenta; + toolStripButtonTail.Name = "toolStripButtonTail"; + toolStripButtonTail.Size = new System.Drawing.Size(27, 19); + toolStripButtonTail.Text = "tail"; + // + // lineToolStripSeparatorExtension5 + // + lineToolStripSeparatorExtension5.Name = "lineToolStripSeparatorExtension5"; + lineToolStripSeparatorExtension5.Size = new System.Drawing.Size(6, 23); + // + // groupsComboBoxHighlightGroups + // + groupsComboBoxHighlightGroups.DropDownStyle = ComboBoxStyle.DropDownList; + groupsComboBoxHighlightGroups.DropDownWidth = 250; + groupsComboBoxHighlightGroups.FlatStyle = FlatStyle.Standard; + groupsComboBoxHighlightGroups.Name = "groupsComboBoxHighlightGroups"; + groupsComboBoxHighlightGroups.Size = new System.Drawing.Size(150, 23); + groupsComboBoxHighlightGroups.ToolTipText = "Select the current highlight settings for the log file (right-click to open highlight settings)"; + groupsComboBoxHighlightGroups.DropDownClosed += OnHighlightGroupsComboBoxDropDownClosed; + groupsComboBoxHighlightGroups.SelectedIndexChanged += OnHighlightGroupsComboBoxSelectedIndexChanged; + groupsComboBoxHighlightGroups.MouseUp += OnHighlightGroupsComboBoxMouseUp; + // + // checkBoxFollowTail + // + checkBoxFollowTail.AutoSize = true; + checkBoxFollowTail.Location = new System.Drawing.Point(663, 985); + checkBoxFollowTail.Margin = new Padding(4, 7, 4, 7); + checkBoxFollowTail.Name = "checkBoxFollowTail"; + checkBoxFollowTail.Size = new System.Drawing.Size(80, 19); + checkBoxFollowTail.TabIndex = 14; + checkBoxFollowTail.Text = "Follow tail"; + checkBoxFollowTail.UseVisualStyleBackColor = true; + checkBoxFollowTail.Click += OnFollowTailCheckBoxClick; + // + // tabContextMenuStrip + // + tabContextMenuStrip.ForeColor = System.Drawing.SystemColors.ControlText; + tabContextMenuStrip.ImageScalingSize = new System.Drawing.Size(24, 24); + tabContextMenuStrip.Items.AddRange(new ToolStripItem[] { closeThisTabToolStripMenuItem, closeOtherTabsToolStripMenuItem, closeAllTabsToolStripMenuItem, tabColorToolStripMenuItem, tabRenameToolStripMenuItem, copyPathToClipboardToolStripMenuItem, findInExplorerToolStripMenuItem, truncateFileToolStripMenuItem }); + tabContextMenuStrip.Name = "tabContextMenuStrip"; + tabContextMenuStrip.Size = new System.Drawing.Size(197, 158); + // + // closeThisTabToolStripMenuItem + // + closeThisTabToolStripMenuItem.BackColor = System.Drawing.SystemColors.Control; + closeThisTabToolStripMenuItem.ForeColor = System.Drawing.SystemColors.ControlText; + closeThisTabToolStripMenuItem.Name = "closeThisTabToolStripMenuItem"; + closeThisTabToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + closeThisTabToolStripMenuItem.Text = "Close this tab"; + closeThisTabToolStripMenuItem.Click += OnCloseThisTabToolStripMenuItemClick; + // + // closeOtherTabsToolStripMenuItem + // + closeOtherTabsToolStripMenuItem.Name = "closeOtherTabsToolStripMenuItem"; + closeOtherTabsToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + closeOtherTabsToolStripMenuItem.Text = "Close other tabs"; + closeOtherTabsToolStripMenuItem.ToolTipText = "Close all tabs except of this one"; + closeOtherTabsToolStripMenuItem.Click += OnCloseOtherTabsToolStripMenuItemClick; + // + // closeAllTabsToolStripMenuItem + // + closeAllTabsToolStripMenuItem.Name = "closeAllTabsToolStripMenuItem"; + closeAllTabsToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + closeAllTabsToolStripMenuItem.Text = "Close all tabs"; + closeAllTabsToolStripMenuItem.ToolTipText = "Close all tabs"; + closeAllTabsToolStripMenuItem.Click += OnCloseAllTabsToolStripMenuItemClick; + // + // tabColorToolStripMenuItem + // + tabColorToolStripMenuItem.Name = "tabColorToolStripMenuItem"; + tabColorToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + tabColorToolStripMenuItem.Text = "Tab color..."; + tabColorToolStripMenuItem.ToolTipText = "Sets the tab color"; + tabColorToolStripMenuItem.Click += OnTabColorToolStripMenuItemClick; + // + // tabRenameToolStripMenuItem + // + tabRenameToolStripMenuItem.Name = "tabRenameToolStripMenuItem"; + tabRenameToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + tabRenameToolStripMenuItem.Text = "Tab rename..."; + tabRenameToolStripMenuItem.ToolTipText = "Set the text which is shown on the tab"; + tabRenameToolStripMenuItem.Click += OnTabRenameToolStripMenuItemClick; + // + // copyPathToClipboardToolStripMenuItem + // + copyPathToClipboardToolStripMenuItem.Name = "copyPathToClipboardToolStripMenuItem"; + copyPathToClipboardToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + copyPathToClipboardToolStripMenuItem.Text = "Copy path to clipboard"; + copyPathToClipboardToolStripMenuItem.ToolTipText = "The complete file name (incl. path) is copied to clipboard"; + copyPathToClipboardToolStripMenuItem.Click += OnCopyPathToClipboardToolStripMenuItemClick; + // + // findInExplorerToolStripMenuItem + // + findInExplorerToolStripMenuItem.Name = "findInExplorerToolStripMenuItem"; + findInExplorerToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + findInExplorerToolStripMenuItem.Text = "Find in Explorer"; + findInExplorerToolStripMenuItem.ToolTipText = "Opens an Explorer window and selects the log file"; + findInExplorerToolStripMenuItem.Click += OnFindInExplorerToolStripMenuItemClick; + // + // truncateFileToolStripMenuItem + // + this.truncateFileToolStripMenuItem.Name = "truncateFileToolStripMenuItem"; + this.truncateFileToolStripMenuItem.Size = new System.Drawing.Size(196, 22); + this.truncateFileToolStripMenuItem.Text = "Truncate File"; + this.truncateFileToolStripMenuItem.ToolTipText = "Try to truncate the file opened in tab"; + this.truncateFileToolStripMenuItem.Click += new System.EventHandler(this.TruncateFileToolStripMenuItem_Click); + // + // dragControlDateTime + // + dragControlDateTime.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; + dragControlDateTime.BackColor = System.Drawing.SystemColors.Control; + dragControlDateTime.DateTime = new System.DateTime(0L); + dragControlDateTime.DragOrientation = DragOrientationsEnum.Vertical; + dragControlDateTime.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, 0); + dragControlDateTime.ForeColor = System.Drawing.SystemColors.ControlDarkDark; + dragControlDateTime.HoverColor = System.Drawing.Color.LightGray; + dragControlDateTime.Location = new System.Drawing.Point(1017, 977); + dragControlDateTime.Margin = new Padding(0); + dragControlDateTime.MaxDateTime = new System.DateTime(9999, 12, 31, 23, 59, 59, 999); + dragControlDateTime.MinDateTime = new System.DateTime(0L); + dragControlDateTime.Name = "dragControlDateTime"; + dragControlDateTime.Size = new System.Drawing.Size(313, 38); + dragControlDateTime.TabIndex = 14; + dragControlDateTime.ValueChanged += OnDateTimeDragControlValueChanged; + dragControlDateTime.ValueDragged += OnDateTimeDragControlValueDragged; + // + // LogTabWindow + // + AllowDrop = true; + ClientSize = new System.Drawing.Size(1603, 1017); + Controls.Add(checkBoxFollowTail); + Controls.Add(dragControlDateTime); + Controls.Add(toolStripContainer); + Controls.Add(statusStrip); + DoubleBuffered = true; + Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); + KeyPreview = true; + MainMenuStrip = mainMenuStrip; + Margin = new Padding(4, 7, 4, 7); + Name = "LogTabWindow"; + Text = "LogExpert"; + Activated += OnLogTabWindowActivated; + Deactivate += OnLogTabWindowDeactivate; + SizeChanged += OnLogTabWindowSizeChanged; + DragDrop += OnLogWindowDragDrop; + DragEnter += OnLogTabWindowDragEnter; + DragOver += OnLogWindowDragOver; + KeyDown += OnLogTabWindowKeyDown; + statusStrip.ResumeLayout(false); + statusStrip.PerformLayout(); + mainMenuStrip.ResumeLayout(false); + mainMenuStrip.PerformLayout(); + toolStripContainer.ContentPanel.ResumeLayout(false); + toolStripContainer.TopToolStripPanel.ResumeLayout(false); + toolStripContainer.TopToolStripPanel.PerformLayout(); + toolStripContainer.ResumeLayout(false); + toolStripContainer.PerformLayout(); + buttonToolStrip.ResumeLayout(false); + buttonToolStrip.PerformLayout(); + tabContextMenuStrip.ResumeLayout(false); + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private System.Windows.Forms.StatusStrip statusStrip; + private System.Windows.Forms.ToolStripStatusLabel labelLines; + private System.Windows.Forms.ToolStripStatusLabel labelSize; + private System.Windows.Forms.MenuStrip mainMenuStrip; + private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem viewNavigateToolStripMenuItem; + private System.Windows.Forms.ToolStripStatusLabel labelCurrentLine; + private System.Windows.Forms.ToolStripProgressBar loadProgessBar; + private System.Windows.Forms.ToolStripStatusLabel labelStatus; + private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; + private System.Windows.Forms.ToolStripContainer toolStripContainer; + private System.Windows.Forms.ToolStripMenuItem closeFileToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem multiFileToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem goToLineToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem searchToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem timeshiftToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem filterToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem copyMarkedLinesIntoNewTabToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem optionToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem hilightingToolStripMenuItem1; + private System.Windows.Forms.ToolStripMenuItem cellSelectModeToolStripMenuItem; + private System.Windows.Forms.ToolStripTextBox timeshiftMenuTextBox; + private System.Windows.Forms.ToolStripMenuItem alwaysOnTopToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem bookmarksToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem toggleBookmarkToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem jumpToNextToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem jumpToPrevToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem toolStripEncodingMenuItem; + private System.Windows.Forms.ToolStripMenuItem toolStripEncodingASCIIItem; + private System.Windows.Forms.ToolStripMenuItem toolStripEncodingANSIItem; + private System.Windows.Forms.ToolStripMenuItem toolStripEncodingUTF8Item; + private System.Windows.Forms.ToolStripMenuItem toolStripEncodingUTF16Item; + private System.Windows.Forms.ToolStripMenuItem reloadToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem columnizerToolStripMenuItem; + private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem; + private DateTimeDragControl dragControlDateTime; + private System.Windows.Forms.ToolStripMenuItem showBookmarkListToolStripMenuItem; + private System.Windows.Forms.ToolStrip buttonToolStrip; + private System.Windows.Forms.ToolStripButton toolStripButtonOpen; + private System.Windows.Forms.ToolStripButton toolStripButtonSearch; + private System.Windows.Forms.ToolStripButton toolStripButtonFilter; + private System.Windows.Forms.ToolStripButton toolStripButtonBookmark; + private System.Windows.Forms.ToolStripButton toolStripButtonUp; + private System.Windows.Forms.ToolStripButton toolStripButtonDown; + private CheckBox host; + private CheckBox checkBoxFollowTail; + private ToolStripButton toolStripButtonTail; + private ToolStripMenuItem showHelpToolStripMenuItem; + private ToolStripMenuItem hideLineColumnToolStripMenuItem; + private ToolStripMenuItem lastUsedToolStripMenuItem; + private ContextMenuStrip tabContextMenuStrip; + private ToolStripMenuItem closeThisTabToolStripMenuItem; + private ToolStripMenuItem closeOtherTabsToolStripMenuItem; + private ToolStripMenuItem closeAllTabsToolStripMenuItem; + private ToolStripMenuItem tabColorToolStripMenuItem; + private ToolStripMenuItem loadProjectToolStripMenuItem; + private ToolStripMenuItem saveProjectToolStripMenuItem; + private ToolStripButton toolStripButtonBubbles; + private ToolStripMenuItem copyPathToClipboardToolStripMenuItem; + private ToolStripMenuItem findInExplorerToolStripMenuItem; + private ToolStripMenuItem truncateFileToolStripMenuItem; + private ToolStripMenuItem exportBookmarksToolStripMenuItem; + private ToolStripComboBox groupsComboBoxHighlightGroups; + private ToolStripMenuItem debugToolStripMenuItem; + private ToolStripMenuItem dumpLogBufferInfoToolStripMenuItem; + private ToolStripMenuItem dumpBufferDiagnosticToolStripMenuItem; + private ToolStripMenuItem runGCToolStripMenuItem; + private ToolStripMenuItem gCInfoToolStripMenuItem; + private ToolStrip externalToolsToolStrip; + private ToolStripMenuItem toolsToolStripMenuItem; + private ToolStripMenuItem configureToolStripMenuItem; + private ToolStripMenuItem throwExceptionGUIThreadToolStripMenuItem; + private ToolStripMenuItem throwExceptionbackgroundThToolStripMenuItem; + private ToolStripMenuItem throwExceptionBackgroundThreadToolStripMenuItem; + private ToolStripMenuItem loglevelToolStripMenuItem; + private ToolStripMenuItem warnToolStripMenuItem; + private ToolStripMenuItem infoToolStripMenuItem; + private ToolStripMenuItem debugToolStripMenuItem1; + private ToolStripMenuItem disableWordHighlightModeToolStripMenuItem; + private ToolStripMenuItem multifileMaskToolStripMenuItem; + private ToolStripMenuItem multiFileEnabledStripMenuItem; + private ToolStripMenuItem toolStripEncodingISO88591Item; + private ToolStripMenuItem lockInstanceToolStripMenuItem; + private ToolStripMenuItem newFromClipboardToolStripMenuItem; + private ToolStripMenuItem openURIToolStripMenuItem; + private ToolStripMenuItem columnFinderToolStripMenuItem; + private DockPanel dockPanel; + private ToolStripMenuItem tabRenameToolStripMenuItem; + 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/Controls/LogTabWindow/LogTabWindow.resx b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.resx similarity index 98% rename from src/LogExpert/Controls/LogTabWindow/LogTabWindow.resx rename to src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.resx index ff6cd4c1..1b6f6b7d 100644 --- a/src/LogExpert/Controls/LogTabWindow/LogTabWindow.resx +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/LogTabWindow.resx @@ -1,164 +1,164 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - 17, 17 - - - 133, 17 - - - 522, 17 - - - 417, 17 - - - - - iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 - YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAIFSURBVDhPpZLtS1NhGMbPPxJmmlYSgqHiKzGU1EDxg4iK - YKyG2WBogqMYJQOtCEVRFBGdTBCJfRnkS4VaaWNT5sqx1BUxRXxDHYxAJLvkusEeBaPAB+5z4Jzn+t3X - /aLhnEfjo8m+dCoa+7/C3O2Hqe0zDC+8KG+cRZHZhdzaaWTVTCLDMIY0vfM04Nfh77/G/sEhwpEDbO3t - I7TxE8urEVy99fT/AL5gWDLrTB/hnF4XsW0khCu5ln8DmJliT2AXrcNBsU1gj/MH4nMeKwBrPktM28xM - cX79DFKrHHD5d9D26hvicx4pABt2lpg10zYzU0zr7+e3xXGcrkEB2O2TNec9nJFwB3alZn5jZorfeDZh - 6Q3g8s06BeCoKF4MRURoH1+BY2oNCbeb0TIclIYxOhzf8frTOuo7FxCbbVIAzpni0iceEc8vhzEwGkJD - lx83ymxifejdKjRNk/8PWnyIyTQqAJek0jqHwfEVscu31baIu8+90sTE4nY025dQ2/5FIPpnXlzKuK8A - HBUzHot52djqQ6HZhfR7IwK4mKpHtvEDMqvfCiQ6zaAAXM8x94aIWTNrLLG4kVUzgaTSPlzLtyJOZxbb - 1wtfyg4Q+AfA3aZlButjSfxGcUJBk4g5tuP3haQKRKXcUQDOmbvNTpPOJeFFjordZmbWTNvMTHFUcpUC - nOccAdABIDXXE1nzAAAAAElFTkSuQmCC - - - - 248, 17 - - - 49 - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 17, 17 + + + 133, 17 + + + 522, 17 + + + 417, 17 + + + + + iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8 + YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAIFSURBVDhPpZLtS1NhGMbPPxJmmlYSgqHiKzGU1EDxg4iK + YKyG2WBogqMYJQOtCEVRFBGdTBCJfRnkS4VaaWNT5sqx1BUxRXxDHYxAJLvkusEeBaPAB+5z4Jzn+t3X + /aLhnEfjo8m+dCoa+7/C3O2Hqe0zDC+8KG+cRZHZhdzaaWTVTCLDMIY0vfM04Nfh77/G/sEhwpEDbO3t + I7TxE8urEVy99fT/AL5gWDLrTB/hnF4XsW0khCu5ln8DmJliT2AXrcNBsU1gj/MH4nMeKwBrPktM28xM + cX79DFKrHHD5d9D26hvicx4pABt2lpg10zYzU0zr7+e3xXGcrkEB2O2TNec9nJFwB3alZn5jZorfeDZh + 6Q3g8s06BeCoKF4MRURoH1+BY2oNCbeb0TIclIYxOhzf8frTOuo7FxCbbVIAzpni0iceEc8vhzEwGkJD + lx83ymxifejdKjRNk/8PWnyIyTQqAJek0jqHwfEVscu31baIu8+90sTE4nY025dQ2/5FIPpnXlzKuK8A + HBUzHot52djqQ6HZhfR7IwK4mKpHtvEDMqvfCiQ6zaAAXM8x94aIWTNrLLG4kVUzgaTSPlzLtyJOZxbb + 1wtfyg4Q+AfA3aZlButjSfxGcUJBk4g5tuP3haQKRKXcUQDOmbvNTpPOJeFFjordZmbWTNvMTHFUcpUC + nOccAdABIDXXE1nzAAAAAElFTkSuQmCC + + + + 248, 17 + + + 49 + + + + 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/Dialogs/LogTabWindow/SettingsDialog.Designer.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.Designer.cs new file mode 100644 index 00000000..b4d5bad8 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.Designer.cs @@ -0,0 +1,1845 @@ +namespace LogExpert.Dialogs; + +partial class SettingsDialog +{ + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsDialog)); + tabControlSettings = new System.Windows.Forms.TabControl(); + tabPageViewSettings = new System.Windows.Forms.TabPage(); + labelWarningMaximumLineLenght = new System.Windows.Forms.Label(); + upDownMaximumLineLength = new System.Windows.Forms.NumericUpDown(); + labelMaximumLineLength = new System.Windows.Forms.Label(); + upDownMaximumFilterEntriesDisplayed = new System.Windows.Forms.NumericUpDown(); + labelMaximumFilterEntriesDisplayed = new System.Windows.Forms.Label(); + upDownMaximumFilterEntries = new System.Windows.Forms.NumericUpDown(); + labelMaximumFilterEntries = new System.Windows.Forms.Label(); + labelDefaultEncoding = new System.Windows.Forms.Label(); + comboBoxEncoding = new System.Windows.Forms.ComboBox(); + groupBoxMisc = new System.Windows.Forms.GroupBox(); + checkBoxShowErrorMessageOnlyOneInstance = new System.Windows.Forms.CheckBox(); + cpDownColumnWidth = new System.Windows.Forms.NumericUpDown(); + checkBoxColumnSize = new System.Windows.Forms.CheckBox(); + buttonTailColor = new System.Windows.Forms.Button(); + checkBoxTailState = new System.Windows.Forms.CheckBox(); + checkBoxOpenLastFiles = new System.Windows.Forms.CheckBox(); + checkBoxSingleInstance = new System.Windows.Forms.CheckBox(); + checkBoxAskCloseTabs = new System.Windows.Forms.CheckBox(); + groupBoxDefaults = new System.Windows.Forms.GroupBox(); + checkBoxDarkMode = new System.Windows.Forms.CheckBox(); + checkBoxFollowTail = new System.Windows.Forms.CheckBox(); + checkBoxColumnFinder = new System.Windows.Forms.CheckBox(); + checkBoxSyncFilter = new System.Windows.Forms.CheckBox(); + checkBoxFilterTail = new System.Windows.Forms.CheckBox(); + groupBoxFont = new System.Windows.Forms.GroupBox(); + buttonChangeFont = new System.Windows.Forms.Button(); + labelFont = new System.Windows.Forms.Label(); + tabPageTimeStampFeatures = new System.Windows.Forms.TabPage(); + groupBoxTimeSpreadDisplay = new System.Windows.Forms.GroupBox(); + groupBoxDisplayMode = new System.Windows.Forms.GroupBox(); + radioButtonLineView = new System.Windows.Forms.RadioButton(); + radioButtonTimeView = new System.Windows.Forms.RadioButton(); + checkBoxReverseAlpha = new System.Windows.Forms.CheckBox(); + buttonTimespreadColor = new System.Windows.Forms.Button(); + checkBoxTimeSpread = new System.Windows.Forms.CheckBox(); + groupBoxTimeStampNavigationControl = new System.Windows.Forms.GroupBox(); + checkBoxTimestamp = new System.Windows.Forms.CheckBox(); + groupBoxMouseDragDefaults = new System.Windows.Forms.GroupBox(); + radioButtonVerticalMouseDragInverted = new System.Windows.Forms.RadioButton(); + radioButtonHorizMouseDrag = new System.Windows.Forms.RadioButton(); + radioButtonVerticalMouseDrag = new System.Windows.Forms.RadioButton(); + tabPageExternalTools = new System.Windows.Forms.TabPage(); + labelToolsDescription = new System.Windows.Forms.Label(); + buttonToolDelete = new System.Windows.Forms.Button(); + buttonToolAdd = new System.Windows.Forms.Button(); + buttonToolDown = new System.Windows.Forms.Button(); + buttonToolUp = new System.Windows.Forms.Button(); + listBoxTools = new System.Windows.Forms.CheckedListBox(); + groupBoxToolSettings = new System.Windows.Forms.GroupBox(); + labelWorkingDir = new System.Windows.Forms.Label(); + buttonWorkingDir = new System.Windows.Forms.Button(); + textBoxWorkingDir = new System.Windows.Forms.TextBox(); + buttonIcon = new System.Windows.Forms.Button(); + labelToolName = new System.Windows.Forms.Label(); + labelToolColumnizerForOutput = new System.Windows.Forms.Label(); + comboBoxColumnizer = new System.Windows.Forms.ComboBox(); + textBoxToolName = new System.Windows.Forms.TextBox(); + checkBoxSysout = new System.Windows.Forms.CheckBox(); + buttonArguments = new System.Windows.Forms.Button(); + labelTool = new System.Windows.Forms.Label(); + buttonTool = new System.Windows.Forms.Button(); + textBoxTool = new System.Windows.Forms.TextBox(); + labelArguments = new System.Windows.Forms.Label(); + textBoxArguments = new System.Windows.Forms.TextBox(); + tabPageColumnizers = new System.Windows.Forms.TabPage(); + checkBoxAutoPick = new System.Windows.Forms.CheckBox(); + checkBoxMaskPrio = new System.Windows.Forms.CheckBox(); + buttonDelete = new System.Windows.Forms.Button(); + dataGridViewColumnizer = new System.Windows.Forms.DataGridView(); + columnFileMask = new System.Windows.Forms.DataGridViewTextBoxColumn(); + columnColumnizer = new System.Windows.Forms.DataGridViewComboBoxColumn(); + tabPageHighlightMask = new System.Windows.Forms.TabPage(); + dataGridViewHighlightMask = new System.Windows.Forms.DataGridView(); + columnFileName = new System.Windows.Forms.DataGridViewTextBoxColumn(); + columnHighlightGroup = new System.Windows.Forms.DataGridViewComboBoxColumn(); + tabPageMultiFile = new System.Windows.Forms.TabPage(); + groupBoxDefaultFileNamePattern = new System.Windows.Forms.GroupBox(); + labelMaxDays = new System.Windows.Forms.Label(); + labelPattern = new System.Windows.Forms.Label(); + upDownMultifileDays = new System.Windows.Forms.NumericUpDown(); + textBoxMultifilePattern = new System.Windows.Forms.TextBox(); + labelHintMultiFile = new System.Windows.Forms.Label(); + labelNoteMultiFile = new System.Windows.Forms.Label(); + groupBoxWhenOpeningMultiFile = new System.Windows.Forms.GroupBox(); + radioButtonAskWhatToDo = new System.Windows.Forms.RadioButton(); + radioButtonTreatAllFilesAsOneMultifile = new System.Windows.Forms.RadioButton(); + radioButtonLoadEveryFileIntoSeperatedTab = new System.Windows.Forms.RadioButton(); + tabPagePlugins = new System.Windows.Forms.TabPage(); + groupBoxPlugins = new System.Windows.Forms.GroupBox(); + listBoxPlugin = new System.Windows.Forms.ListBox(); + groupBoxSettings = new System.Windows.Forms.GroupBox(); + panelPlugin = new System.Windows.Forms.Panel(); + buttonConfigPlugin = new System.Windows.Forms.Button(); + tabPageSessions = new System.Windows.Forms.TabPage(); + checkBoxPortableMode = new System.Windows.Forms.CheckBox(); + checkBoxSaveFilter = new System.Windows.Forms.CheckBox(); + groupBoxPersistantFileLocation = new System.Windows.Forms.GroupBox(); + labelSessionSaveOwnDir = new System.Windows.Forms.Label(); + buttonSessionSaveDir = new System.Windows.Forms.Button(); + radioButtonSessionSaveOwn = new System.Windows.Forms.RadioButton(); + radioButtonsessionSaveDocuments = new System.Windows.Forms.RadioButton(); + radioButtonSessionSameDir = new System.Windows.Forms.RadioButton(); + radioButtonSessionApplicationStartupDir = new System.Windows.Forms.RadioButton(); + checkBoxSaveSessions = new System.Windows.Forms.CheckBox(); + tabPageMemory = new System.Windows.Forms.TabPage(); + groupBoxCPUAndStuff = new System.Windows.Forms.GroupBox(); + checkBoxLegacyReader = new System.Windows.Forms.CheckBox(); + checkBoxMultiThread = new System.Windows.Forms.CheckBox(); + labelFilePollingInterval = new System.Windows.Forms.Label(); + upDownPollingInterval = new System.Windows.Forms.NumericUpDown(); + groupBoxLineBufferUsage = new System.Windows.Forms.GroupBox(); + labelInfo = new System.Windows.Forms.Label(); + labelNumberOfBlocks = new System.Windows.Forms.Label(); + upDownLinesPerBlock = new System.Windows.Forms.NumericUpDown(); + upDownBlockCount = new System.Windows.Forms.NumericUpDown(); + labelLinesPerBlock = new System.Windows.Forms.Label(); + buttonCancel = new System.Windows.Forms.Button(); + buttonOk = new System.Windows.Forms.Button(); + helpProvider = new System.Windows.Forms.HelpProvider(); + toolTip = new System.Windows.Forms.ToolTip(components); + buttonExport = new System.Windows.Forms.Button(); + buttonImport = new System.Windows.Forms.Button(); + dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); + tabControlSettings.SuspendLayout(); + tabPageViewSettings.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)upDownMaximumLineLength).BeginInit(); + ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntriesDisplayed).BeginInit(); + ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntries).BeginInit(); + groupBoxMisc.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)cpDownColumnWidth).BeginInit(); + groupBoxDefaults.SuspendLayout(); + groupBoxFont.SuspendLayout(); + tabPageTimeStampFeatures.SuspendLayout(); + groupBoxTimeSpreadDisplay.SuspendLayout(); + groupBoxDisplayMode.SuspendLayout(); + groupBoxTimeStampNavigationControl.SuspendLayout(); + groupBoxMouseDragDefaults.SuspendLayout(); + tabPageExternalTools.SuspendLayout(); + groupBoxToolSettings.SuspendLayout(); + tabPageColumnizers.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridViewColumnizer).BeginInit(); + tabPageHighlightMask.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridViewHighlightMask).BeginInit(); + tabPageMultiFile.SuspendLayout(); + groupBoxDefaultFileNamePattern.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)upDownMultifileDays).BeginInit(); + groupBoxWhenOpeningMultiFile.SuspendLayout(); + tabPagePlugins.SuspendLayout(); + groupBoxPlugins.SuspendLayout(); + groupBoxSettings.SuspendLayout(); + panelPlugin.SuspendLayout(); + tabPageSessions.SuspendLayout(); + groupBoxPersistantFileLocation.SuspendLayout(); + tabPageMemory.SuspendLayout(); + groupBoxCPUAndStuff.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)upDownPollingInterval).BeginInit(); + groupBoxLineBufferUsage.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)upDownLinesPerBlock).BeginInit(); + ((System.ComponentModel.ISupportInitialize)upDownBlockCount).BeginInit(); + SuspendLayout(); + // + // tabControlSettings + // + tabControlSettings.Controls.Add(tabPageViewSettings); + tabControlSettings.Controls.Add(tabPageTimeStampFeatures); + tabControlSettings.Controls.Add(tabPageExternalTools); + tabControlSettings.Controls.Add(tabPageColumnizers); + tabControlSettings.Controls.Add(tabPageHighlightMask); + tabControlSettings.Controls.Add(tabPageMultiFile); + tabControlSettings.Controls.Add(tabPagePlugins); + tabControlSettings.Controls.Add(tabPageSessions); + tabControlSettings.Controls.Add(tabPageMemory); + tabControlSettings.Location = new System.Drawing.Point(2, 3); + tabControlSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabControlSettings.Name = "tabControlSettings"; + tabControlSettings.SelectedIndex = 0; + tabControlSettings.Size = new System.Drawing.Size(950, 468); + tabControlSettings.TabIndex = 0; + // + // tabPageViewSettings + // + tabPageViewSettings.Controls.Add(labelWarningMaximumLineLenght); + tabPageViewSettings.Controls.Add(upDownMaximumLineLength); + tabPageViewSettings.Controls.Add(labelMaximumLineLength); + tabPageViewSettings.Controls.Add(upDownMaximumFilterEntriesDisplayed); + tabPageViewSettings.Controls.Add(labelMaximumFilterEntriesDisplayed); + tabPageViewSettings.Controls.Add(upDownMaximumFilterEntries); + tabPageViewSettings.Controls.Add(labelMaximumFilterEntries); + tabPageViewSettings.Controls.Add(labelDefaultEncoding); + tabPageViewSettings.Controls.Add(comboBoxEncoding); + tabPageViewSettings.Controls.Add(groupBoxMisc); + tabPageViewSettings.Controls.Add(groupBoxDefaults); + tabPageViewSettings.Controls.Add(groupBoxFont); + tabPageViewSettings.Location = new System.Drawing.Point(4, 24); + tabPageViewSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageViewSettings.Name = "tabPageViewSettings"; + tabPageViewSettings.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageViewSettings.Size = new System.Drawing.Size(942, 440); + tabPageViewSettings.TabIndex = 0; + tabPageViewSettings.Text = "View settings"; + tabPageViewSettings.UseVisualStyleBackColor = true; + // + // labelWarningMaximumLineLenght + // + labelWarningMaximumLineLenght.AutoSize = true; + labelWarningMaximumLineLenght.Location = new System.Drawing.Point(446, 118); + labelWarningMaximumLineLenght.Name = "labelWarningMaximumLineLenght"; + labelWarningMaximumLineLenght.Size = new System.Drawing.Size(482, 15); + labelWarningMaximumLineLenght.TabIndex = 16; + labelWarningMaximumLineLenght.Text = "! Changing the Maximum Line Length can impact performance and is not recommended !"; + // + // upDownMaximumLineLength + // + upDownMaximumLineLength.Location = new System.Drawing.Point(762, 138); + upDownMaximumLineLength.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + upDownMaximumLineLength.Maximum = new decimal(new int[] { 1000000, 0, 0, 0 }); + upDownMaximumLineLength.Minimum = new decimal(new int[] { 20000, 0, 0, 0 }); + upDownMaximumLineLength.Name = "upDownMaximumLineLength"; + upDownMaximumLineLength.Size = new System.Drawing.Size(106, 23); + upDownMaximumLineLength.TabIndex = 15; + upDownMaximumLineLength.Value = new decimal(new int[] { 20000, 0, 0, 0 }); + // + // labelMaximumLineLength + // + labelMaximumLineLength.AutoSize = true; + labelMaximumLineLength.Location = new System.Drawing.Point(467, 140); + labelMaximumLineLength.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelMaximumLineLength.Name = "labelMaximumLineLength"; + labelMaximumLineLength.Size = new System.Drawing.Size(217, 15); + labelMaximumLineLength.TabIndex = 14; + labelMaximumLineLength.Text = "Maximum Line Length (restart required)"; + // + // upDownMaximumFilterEntriesDisplayed + // + upDownMaximumFilterEntriesDisplayed.Location = new System.Drawing.Point(762, 86); + upDownMaximumFilterEntriesDisplayed.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + upDownMaximumFilterEntriesDisplayed.Maximum = new decimal(new int[] { 30, 0, 0, 0 }); + upDownMaximumFilterEntriesDisplayed.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); + upDownMaximumFilterEntriesDisplayed.Name = "upDownMaximumFilterEntriesDisplayed"; + upDownMaximumFilterEntriesDisplayed.Size = new System.Drawing.Size(106, 23); + upDownMaximumFilterEntriesDisplayed.TabIndex = 13; + upDownMaximumFilterEntriesDisplayed.Value = new decimal(new int[] { 20, 0, 0, 0 }); + // + // labelMaximumFilterEntriesDisplayed + // + labelMaximumFilterEntriesDisplayed.AutoSize = true; + labelMaximumFilterEntriesDisplayed.Location = new System.Drawing.Point(467, 88); + labelMaximumFilterEntriesDisplayed.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelMaximumFilterEntriesDisplayed.Name = "labelMaximumFilterEntriesDisplayed"; + labelMaximumFilterEntriesDisplayed.Size = new System.Drawing.Size(179, 15); + labelMaximumFilterEntriesDisplayed.TabIndex = 12; + labelMaximumFilterEntriesDisplayed.Text = "Maximum filter entries displayed"; + // + // upDownMaximumFilterEntries + // + upDownMaximumFilterEntries.Location = new System.Drawing.Point(762, 59); + upDownMaximumFilterEntries.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + upDownMaximumFilterEntries.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); + upDownMaximumFilterEntries.Name = "upDownMaximumFilterEntries"; + upDownMaximumFilterEntries.Size = new System.Drawing.Size(106, 23); + upDownMaximumFilterEntries.TabIndex = 11; + upDownMaximumFilterEntries.Value = new decimal(new int[] { 30, 0, 0, 0 }); + // + // labelMaximumFilterEntries + // + labelMaximumFilterEntries.AutoSize = true; + labelMaximumFilterEntries.Location = new System.Drawing.Point(467, 61); + labelMaximumFilterEntries.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelMaximumFilterEntries.Name = "labelMaximumFilterEntries"; + labelMaximumFilterEntries.Size = new System.Drawing.Size(126, 15); + labelMaximumFilterEntries.TabIndex = 10; + labelMaximumFilterEntries.Text = "Maximum filter entries"; + // + // labelDefaultEncoding + // + labelDefaultEncoding.AutoSize = true; + labelDefaultEncoding.Location = new System.Drawing.Point(467, 34); + labelDefaultEncoding.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelDefaultEncoding.Name = "labelDefaultEncoding"; + labelDefaultEncoding.Size = new System.Drawing.Size(98, 15); + labelDefaultEncoding.TabIndex = 9; + labelDefaultEncoding.Text = "Default encoding"; + // + // comboBoxEncoding + // + comboBoxEncoding.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + comboBoxEncoding.FormattingEnabled = true; + comboBoxEncoding.Location = new System.Drawing.Point(691, 26); + comboBoxEncoding.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + comboBoxEncoding.Name = "comboBoxEncoding"; + comboBoxEncoding.Size = new System.Drawing.Size(177, 23); + comboBoxEncoding.TabIndex = 8; + toolTip.SetToolTip(comboBoxEncoding, "Encoding to be used when no BOM header and no persistence data is available."); + // + // groupBoxMisc + // + groupBoxMisc.Controls.Add(checkBoxShowErrorMessageOnlyOneInstance); + groupBoxMisc.Controls.Add(cpDownColumnWidth); + groupBoxMisc.Controls.Add(checkBoxColumnSize); + groupBoxMisc.Controls.Add(buttonTailColor); + groupBoxMisc.Controls.Add(checkBoxTailState); + groupBoxMisc.Controls.Add(checkBoxOpenLastFiles); + groupBoxMisc.Controls.Add(checkBoxSingleInstance); + groupBoxMisc.Controls.Add(checkBoxAskCloseTabs); + groupBoxMisc.Location = new System.Drawing.Point(458, 171); + groupBoxMisc.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxMisc.Name = "groupBoxMisc"; + groupBoxMisc.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxMisc.Size = new System.Drawing.Size(410, 226); + groupBoxMisc.TabIndex = 7; + groupBoxMisc.TabStop = false; + groupBoxMisc.Text = "Misc"; + // + // checkBoxShowErrorMessageOnlyOneInstance + // + checkBoxShowErrorMessageOnlyOneInstance.AutoSize = true; + checkBoxShowErrorMessageOnlyOneInstance.Location = new System.Drawing.Point(210, 66); + checkBoxShowErrorMessageOnlyOneInstance.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxShowErrorMessageOnlyOneInstance.Name = "checkBoxShowErrorMessageOnlyOneInstance"; + checkBoxShowErrorMessageOnlyOneInstance.Size = new System.Drawing.Size(137, 19); + checkBoxShowErrorMessageOnlyOneInstance.TabIndex = 7; + checkBoxShowErrorMessageOnlyOneInstance.Text = "Show Error Message?"; + checkBoxShowErrorMessageOnlyOneInstance.UseVisualStyleBackColor = true; + // + // cpDownColumnWidth + // + cpDownColumnWidth.Location = new System.Drawing.Point(304, 175); + cpDownColumnWidth.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + cpDownColumnWidth.Maximum = new decimal(new int[] { 9000, 0, 0, 0 }); + cpDownColumnWidth.Minimum = new decimal(new int[] { 300, 0, 0, 0 }); + cpDownColumnWidth.Name = "cpDownColumnWidth"; + cpDownColumnWidth.Size = new System.Drawing.Size(84, 23); + cpDownColumnWidth.TabIndex = 6; + cpDownColumnWidth.Value = new decimal(new int[] { 2000, 0, 0, 0 }); + // + // checkBoxColumnSize + // + checkBoxColumnSize.AutoSize = true; + checkBoxColumnSize.Location = new System.Drawing.Point(9, 177); + checkBoxColumnSize.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxColumnSize.Name = "checkBoxColumnSize"; + checkBoxColumnSize.Size = new System.Drawing.Size(140, 19); + checkBoxColumnSize.TabIndex = 5; + checkBoxColumnSize.Text = "Set last column width"; + checkBoxColumnSize.UseVisualStyleBackColor = true; + checkBoxColumnSize.CheckedChanged += OnChkBoxColumnSizeCheckedChanged; + // + // buttonTailColor + // + buttonTailColor.Location = new System.Drawing.Point(304, 135); + buttonTailColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonTailColor.Name = "buttonTailColor"; + buttonTailColor.Size = new System.Drawing.Size(84, 32); + buttonTailColor.TabIndex = 4; + buttonTailColor.Text = "Color..."; + buttonTailColor.UseVisualStyleBackColor = true; + buttonTailColor.Click += OnBtnTailColorClick; + // + // checkBoxTailState + // + checkBoxTailState.AutoSize = true; + checkBoxTailState.Location = new System.Drawing.Point(9, 140); + checkBoxTailState.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxTailState.Name = "checkBoxTailState"; + checkBoxTailState.Size = new System.Drawing.Size(144, 19); + checkBoxTailState.TabIndex = 3; + checkBoxTailState.Text = "Show tail state on tabs"; + checkBoxTailState.UseVisualStyleBackColor = true; + // + // checkBoxOpenLastFiles + // + checkBoxOpenLastFiles.AutoSize = true; + checkBoxOpenLastFiles.Location = new System.Drawing.Point(9, 103); + checkBoxOpenLastFiles.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxOpenLastFiles.Name = "checkBoxOpenLastFiles"; + checkBoxOpenLastFiles.Size = new System.Drawing.Size(144, 19); + checkBoxOpenLastFiles.TabIndex = 2; + checkBoxOpenLastFiles.Text = "Re-open last used files"; + checkBoxOpenLastFiles.UseVisualStyleBackColor = true; + // + // checkBoxSingleInstance + // + checkBoxSingleInstance.AutoSize = true; + checkBoxSingleInstance.Location = new System.Drawing.Point(9, 66); + checkBoxSingleInstance.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxSingleInstance.Name = "checkBoxSingleInstance"; + checkBoxSingleInstance.Size = new System.Drawing.Size(138, 19); + checkBoxSingleInstance.TabIndex = 1; + checkBoxSingleInstance.Text = "Allow only 1 Instance"; + checkBoxSingleInstance.UseVisualStyleBackColor = true; + // + // checkBoxAskCloseTabs + // + checkBoxAskCloseTabs.AutoSize = true; + checkBoxAskCloseTabs.Location = new System.Drawing.Point(9, 29); + checkBoxAskCloseTabs.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxAskCloseTabs.Name = "checkBoxAskCloseTabs"; + checkBoxAskCloseTabs.Size = new System.Drawing.Size(148, 19); + checkBoxAskCloseTabs.TabIndex = 0; + checkBoxAskCloseTabs.Text = "Ask before closing tabs"; + checkBoxAskCloseTabs.UseVisualStyleBackColor = true; + // + // groupBoxDefaults + // + groupBoxDefaults.Controls.Add(checkBoxDarkMode); + groupBoxDefaults.Controls.Add(checkBoxFollowTail); + groupBoxDefaults.Controls.Add(checkBoxColumnFinder); + groupBoxDefaults.Controls.Add(checkBoxSyncFilter); + groupBoxDefaults.Controls.Add(checkBoxFilterTail); + groupBoxDefaults.Location = new System.Drawing.Point(10, 171); + groupBoxDefaults.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxDefaults.Name = "groupBoxDefaults"; + groupBoxDefaults.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxDefaults.Size = new System.Drawing.Size(411, 226); + groupBoxDefaults.TabIndex = 6; + groupBoxDefaults.TabStop = false; + groupBoxDefaults.Text = "Defaults"; + // + // checkBoxDarkMode + // + checkBoxDarkMode.AutoSize = true; + checkBoxDarkMode.Location = new System.Drawing.Point(7, 141); + checkBoxDarkMode.Margin = new System.Windows.Forms.Padding(4); + checkBoxDarkMode.Name = "checkBoxDarkMode"; + checkBoxDarkMode.Size = new System.Drawing.Size(175, 19); + checkBoxDarkMode.TabIndex = 6; + checkBoxDarkMode.Text = "Dark Mode (restart required)"; + checkBoxDarkMode.UseVisualStyleBackColor = true; + // + // checkBoxFollowTail + // + checkBoxFollowTail.AutoSize = true; + checkBoxFollowTail.Location = new System.Drawing.Point(9, 29); + checkBoxFollowTail.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxFollowTail.Name = "checkBoxFollowTail"; + checkBoxFollowTail.Size = new System.Drawing.Size(125, 19); + checkBoxFollowTail.TabIndex = 3; + checkBoxFollowTail.Text = "Follow tail enabled"; + checkBoxFollowTail.UseVisualStyleBackColor = true; + // + // checkBoxColumnFinder + // + checkBoxColumnFinder.AutoSize = true; + checkBoxColumnFinder.Location = new System.Drawing.Point(9, 140); + checkBoxColumnFinder.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxColumnFinder.Name = "checkBoxColumnFinder"; + checkBoxColumnFinder.Size = new System.Drawing.Size(133, 19); + checkBoxColumnFinder.TabIndex = 5; + checkBoxColumnFinder.Text = "Show column finder"; + checkBoxColumnFinder.UseVisualStyleBackColor = true; + // + // checkBoxSyncFilter + // + checkBoxSyncFilter.AutoSize = true; + checkBoxSyncFilter.Location = new System.Drawing.Point(9, 103); + checkBoxSyncFilter.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxSyncFilter.Name = "checkBoxSyncFilter"; + checkBoxSyncFilter.Size = new System.Drawing.Size(141, 19); + checkBoxSyncFilter.TabIndex = 5; + checkBoxSyncFilter.Text = "Sync filter list enabled"; + checkBoxSyncFilter.UseVisualStyleBackColor = true; + // + // checkBoxFilterTail + // + checkBoxFilterTail.AutoSize = true; + checkBoxFilterTail.Location = new System.Drawing.Point(9, 66); + checkBoxFilterTail.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxFilterTail.Name = "checkBoxFilterTail"; + checkBoxFilterTail.Size = new System.Drawing.Size(116, 19); + checkBoxFilterTail.TabIndex = 4; + checkBoxFilterTail.Text = "Filter tail enabled"; + checkBoxFilterTail.UseVisualStyleBackColor = true; + // + // groupBoxFont + // + groupBoxFont.Controls.Add(buttonChangeFont); + groupBoxFont.Controls.Add(labelFont); + groupBoxFont.Location = new System.Drawing.Point(10, 9); + groupBoxFont.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxFont.Name = "groupBoxFont"; + groupBoxFont.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxFont.Size = new System.Drawing.Size(408, 128); + groupBoxFont.TabIndex = 1; + groupBoxFont.TabStop = false; + groupBoxFont.Text = "Font"; + // + // buttonChangeFont + // + buttonChangeFont.Location = new System.Drawing.Point(9, 77); + buttonChangeFont.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonChangeFont.Name = "buttonChangeFont"; + buttonChangeFont.Size = new System.Drawing.Size(112, 35); + buttonChangeFont.TabIndex = 1; + buttonChangeFont.Text = "Change..."; + buttonChangeFont.UseVisualStyleBackColor = true; + buttonChangeFont.Click += OnBtnChangeFontClick; + // + // labelFont + // + labelFont.Location = new System.Drawing.Point(9, 25); + labelFont.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelFont.Name = "labelFont"; + labelFont.Size = new System.Drawing.Size(312, 48); + labelFont.TabIndex = 0; + labelFont.Text = "Font"; + labelFont.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; + // + // tabPageTimeStampFeatures + // + tabPageTimeStampFeatures.Controls.Add(groupBoxTimeSpreadDisplay); + tabPageTimeStampFeatures.Controls.Add(groupBoxTimeStampNavigationControl); + tabPageTimeStampFeatures.Location = new System.Drawing.Point(4, 24); + tabPageTimeStampFeatures.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageTimeStampFeatures.Name = "tabPageTimeStampFeatures"; + tabPageTimeStampFeatures.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageTimeStampFeatures.Size = new System.Drawing.Size(942, 440); + tabPageTimeStampFeatures.TabIndex = 1; + tabPageTimeStampFeatures.Text = "Timestamp features"; + tabPageTimeStampFeatures.UseVisualStyleBackColor = true; + // + // groupBoxTimeSpreadDisplay + // + groupBoxTimeSpreadDisplay.Controls.Add(groupBoxDisplayMode); + groupBoxTimeSpreadDisplay.Controls.Add(checkBoxReverseAlpha); + groupBoxTimeSpreadDisplay.Controls.Add(buttonTimespreadColor); + groupBoxTimeSpreadDisplay.Controls.Add(checkBoxTimeSpread); + groupBoxTimeSpreadDisplay.Location = new System.Drawing.Point(490, 25); + groupBoxTimeSpreadDisplay.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxTimeSpreadDisplay.Name = "groupBoxTimeSpreadDisplay"; + groupBoxTimeSpreadDisplay.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxTimeSpreadDisplay.Size = new System.Drawing.Size(300, 246); + groupBoxTimeSpreadDisplay.TabIndex = 8; + groupBoxTimeSpreadDisplay.TabStop = false; + groupBoxTimeSpreadDisplay.Text = "Time spread display"; + // + // groupBoxDisplayMode + // + groupBoxDisplayMode.Controls.Add(radioButtonLineView); + groupBoxDisplayMode.Controls.Add(radioButtonTimeView); + groupBoxDisplayMode.Location = new System.Drawing.Point(22, 109); + groupBoxDisplayMode.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxDisplayMode.Name = "groupBoxDisplayMode"; + groupBoxDisplayMode.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxDisplayMode.Size = new System.Drawing.Size(188, 118); + groupBoxDisplayMode.TabIndex = 11; + groupBoxDisplayMode.TabStop = false; + groupBoxDisplayMode.Text = "Display mode"; + // + // radioButtonLineView + // + radioButtonLineView.AutoSize = true; + radioButtonLineView.Location = new System.Drawing.Point(9, 65); + radioButtonLineView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonLineView.Name = "radioButtonLineView"; + radioButtonLineView.Size = new System.Drawing.Size(74, 19); + radioButtonLineView.TabIndex = 9; + radioButtonLineView.TabStop = true; + radioButtonLineView.Text = "Line view"; + radioButtonLineView.UseVisualStyleBackColor = true; + // + // radioButtonTimeView + // + radioButtonTimeView.AutoSize = true; + radioButtonTimeView.Location = new System.Drawing.Point(9, 29); + radioButtonTimeView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonTimeView.Name = "radioButtonTimeView"; + radioButtonTimeView.Size = new System.Drawing.Size(79, 19); + radioButtonTimeView.TabIndex = 10; + radioButtonTimeView.TabStop = true; + radioButtonTimeView.Text = "Time view"; + radioButtonTimeView.UseVisualStyleBackColor = true; + // + // checkBoxReverseAlpha + // + checkBoxReverseAlpha.AutoSize = true; + checkBoxReverseAlpha.Location = new System.Drawing.Point(22, 74); + checkBoxReverseAlpha.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxReverseAlpha.Name = "checkBoxReverseAlpha"; + checkBoxReverseAlpha.Size = new System.Drawing.Size(98, 19); + checkBoxReverseAlpha.TabIndex = 8; + checkBoxReverseAlpha.Text = "Reverse alpha"; + checkBoxReverseAlpha.UseVisualStyleBackColor = true; + // + // buttonTimespreadColor + // + buttonTimespreadColor.Location = new System.Drawing.Point(207, 32); + buttonTimespreadColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonTimespreadColor.Name = "buttonTimespreadColor"; + buttonTimespreadColor.Size = new System.Drawing.Size(84, 32); + buttonTimespreadColor.TabIndex = 7; + buttonTimespreadColor.Text = "Color..."; + buttonTimespreadColor.UseVisualStyleBackColor = true; + buttonTimespreadColor.Click += OnBtnTimespreadColorClick; + // + // checkBoxTimeSpread + // + checkBoxTimeSpread.AutoSize = true; + checkBoxTimeSpread.Location = new System.Drawing.Point(22, 37); + checkBoxTimeSpread.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxTimeSpread.Name = "checkBoxTimeSpread"; + checkBoxTimeSpread.Size = new System.Drawing.Size(120, 19); + checkBoxTimeSpread.TabIndex = 6; + checkBoxTimeSpread.Text = "Show time spread"; + checkBoxTimeSpread.UseVisualStyleBackColor = true; + // + // groupBoxTimeStampNavigationControl + // + groupBoxTimeStampNavigationControl.Controls.Add(checkBoxTimestamp); + groupBoxTimeStampNavigationControl.Controls.Add(groupBoxMouseDragDefaults); + groupBoxTimeStampNavigationControl.Location = new System.Drawing.Point(10, 25); + groupBoxTimeStampNavigationControl.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxTimeStampNavigationControl.Name = "groupBoxTimeStampNavigationControl"; + groupBoxTimeStampNavigationControl.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxTimeStampNavigationControl.Size = new System.Drawing.Size(450, 246); + groupBoxTimeStampNavigationControl.TabIndex = 7; + groupBoxTimeStampNavigationControl.TabStop = false; + groupBoxTimeStampNavigationControl.Text = "Timestamp navigation control"; + // + // checkBoxTimestamp + // + checkBoxTimestamp.AutoSize = true; + checkBoxTimestamp.Location = new System.Drawing.Point(27, 37); + checkBoxTimestamp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxTimestamp.Name = "checkBoxTimestamp"; + checkBoxTimestamp.Size = new System.Drawing.Size(304, 19); + checkBoxTimestamp.TabIndex = 3; + checkBoxTimestamp.Text = "Show timestamp control, if supported by columnizer"; + checkBoxTimestamp.UseVisualStyleBackColor = true; + // + // groupBoxMouseDragDefaults + // + groupBoxMouseDragDefaults.Controls.Add(radioButtonVerticalMouseDragInverted); + groupBoxMouseDragDefaults.Controls.Add(radioButtonHorizMouseDrag); + groupBoxMouseDragDefaults.Controls.Add(radioButtonVerticalMouseDrag); + groupBoxMouseDragDefaults.Location = new System.Drawing.Point(27, 80); + groupBoxMouseDragDefaults.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxMouseDragDefaults.Name = "groupBoxMouseDragDefaults"; + groupBoxMouseDragDefaults.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxMouseDragDefaults.Size = new System.Drawing.Size(186, 148); + groupBoxMouseDragDefaults.TabIndex = 5; + groupBoxMouseDragDefaults.TabStop = false; + groupBoxMouseDragDefaults.Text = "Mouse Drag Default"; + // + // radioButtonVerticalMouseDragInverted + // + radioButtonVerticalMouseDragInverted.AutoSize = true; + radioButtonVerticalMouseDragInverted.Location = new System.Drawing.Point(9, 102); + radioButtonVerticalMouseDragInverted.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonVerticalMouseDragInverted.Name = "radioButtonVerticalMouseDragInverted"; + radioButtonVerticalMouseDragInverted.Size = new System.Drawing.Size(109, 19); + radioButtonVerticalMouseDragInverted.TabIndex = 6; + radioButtonVerticalMouseDragInverted.TabStop = true; + radioButtonVerticalMouseDragInverted.Text = "Vertical Inverted"; + radioButtonVerticalMouseDragInverted.UseVisualStyleBackColor = true; + // + // radioButtonHorizMouseDrag + // + radioButtonHorizMouseDrag.AutoSize = true; + radioButtonHorizMouseDrag.Location = new System.Drawing.Point(9, 29); + radioButtonHorizMouseDrag.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonHorizMouseDrag.Name = "radioButtonHorizMouseDrag"; + radioButtonHorizMouseDrag.Size = new System.Drawing.Size(80, 19); + radioButtonHorizMouseDrag.TabIndex = 5; + radioButtonHorizMouseDrag.TabStop = true; + radioButtonHorizMouseDrag.Text = "Horizontal"; + radioButtonHorizMouseDrag.UseVisualStyleBackColor = true; + // + // radioButtonVerticalMouseDrag + // + radioButtonVerticalMouseDrag.AutoSize = true; + radioButtonVerticalMouseDrag.Location = new System.Drawing.Point(9, 65); + radioButtonVerticalMouseDrag.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonVerticalMouseDrag.Name = "radioButtonVerticalMouseDrag"; + radioButtonVerticalMouseDrag.Size = new System.Drawing.Size(63, 19); + radioButtonVerticalMouseDrag.TabIndex = 4; + radioButtonVerticalMouseDrag.TabStop = true; + radioButtonVerticalMouseDrag.Text = "Vertical"; + radioButtonVerticalMouseDrag.UseVisualStyleBackColor = true; + // + // tabPageExternalTools + // + tabPageExternalTools.Controls.Add(labelToolsDescription); + tabPageExternalTools.Controls.Add(buttonToolDelete); + tabPageExternalTools.Controls.Add(buttonToolAdd); + tabPageExternalTools.Controls.Add(buttonToolDown); + tabPageExternalTools.Controls.Add(buttonToolUp); + tabPageExternalTools.Controls.Add(listBoxTools); + tabPageExternalTools.Controls.Add(groupBoxToolSettings); + tabPageExternalTools.Location = new System.Drawing.Point(4, 24); + tabPageExternalTools.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageExternalTools.Name = "tabPageExternalTools"; + tabPageExternalTools.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageExternalTools.Size = new System.Drawing.Size(942, 440); + tabPageExternalTools.TabIndex = 2; + tabPageExternalTools.Text = "External Tools"; + tabPageExternalTools.UseVisualStyleBackColor = true; + // + // labelToolsDescription + // + labelToolsDescription.Location = new System.Drawing.Point(546, 102); + labelToolsDescription.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelToolsDescription.Name = "labelToolsDescription"; + labelToolsDescription.Size = new System.Drawing.Size(376, 80); + labelToolsDescription.TabIndex = 6; + labelToolsDescription.Text = "You can configure as many tools as you want. \r\nChecked tools will appear in the icon bar. All other tools are available in the tools menu."; + // + // buttonToolDelete + // + buttonToolDelete.Location = new System.Drawing.Point(550, 14); + buttonToolDelete.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonToolDelete.Name = "buttonToolDelete"; + buttonToolDelete.Size = new System.Drawing.Size(112, 35); + buttonToolDelete.TabIndex = 2; + buttonToolDelete.Text = "Remove"; + buttonToolDelete.UseVisualStyleBackColor = true; + buttonToolDelete.Click += OnToolDeleteButtonClick; + // + // buttonToolAdd + // + buttonToolAdd.Location = new System.Drawing.Point(429, 14); + buttonToolAdd.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonToolAdd.Name = "buttonToolAdd"; + buttonToolAdd.Size = new System.Drawing.Size(112, 35); + buttonToolAdd.TabIndex = 1; + buttonToolAdd.Text = "Add new"; + buttonToolAdd.UseVisualStyleBackColor = true; + buttonToolAdd.Click += OnBtnToolAddClick; + // + // buttonToolDown + // + buttonToolDown.Location = new System.Drawing.Point(429, 146); + buttonToolDown.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonToolDown.Name = "buttonToolDown"; + buttonToolDown.Size = new System.Drawing.Size(64, 35); + buttonToolDown.TabIndex = 4; + buttonToolDown.Text = "Down"; + buttonToolDown.UseVisualStyleBackColor = true; + buttonToolDown.Click += OnBtnToolDownClick; + // + // buttonToolUp + // + buttonToolUp.Location = new System.Drawing.Point(429, 102); + buttonToolUp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonToolUp.Name = "buttonToolUp"; + buttonToolUp.Size = new System.Drawing.Size(64, 35); + buttonToolUp.TabIndex = 3; + buttonToolUp.Text = "Up"; + buttonToolUp.UseVisualStyleBackColor = true; + buttonToolUp.Click += OnBtnToolUpClick; + // + // listBoxTools + // + listBoxTools.FormattingEnabled = true; + listBoxTools.Location = new System.Drawing.Point(10, 14); + listBoxTools.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + listBoxTools.Name = "listBoxTools"; + listBoxTools.Size = new System.Drawing.Size(406, 148); + listBoxTools.TabIndex = 0; + listBoxTools.SelectedIndexChanged += OnListBoxToolSelectedIndexChanged; + // + // groupBoxToolSettings + // + groupBoxToolSettings.Controls.Add(labelWorkingDir); + groupBoxToolSettings.Controls.Add(buttonWorkingDir); + groupBoxToolSettings.Controls.Add(textBoxWorkingDir); + groupBoxToolSettings.Controls.Add(buttonIcon); + groupBoxToolSettings.Controls.Add(labelToolName); + groupBoxToolSettings.Controls.Add(labelToolColumnizerForOutput); + groupBoxToolSettings.Controls.Add(comboBoxColumnizer); + groupBoxToolSettings.Controls.Add(textBoxToolName); + groupBoxToolSettings.Controls.Add(checkBoxSysout); + groupBoxToolSettings.Controls.Add(buttonArguments); + groupBoxToolSettings.Controls.Add(labelTool); + groupBoxToolSettings.Controls.Add(buttonTool); + groupBoxToolSettings.Controls.Add(textBoxTool); + groupBoxToolSettings.Controls.Add(labelArguments); + groupBoxToolSettings.Controls.Add(textBoxArguments); + groupBoxToolSettings.Location = new System.Drawing.Point(10, 191); + groupBoxToolSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxToolSettings.Name = "groupBoxToolSettings"; + groupBoxToolSettings.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxToolSettings.Size = new System.Drawing.Size(912, 228); + groupBoxToolSettings.TabIndex = 0; + groupBoxToolSettings.TabStop = false; + groupBoxToolSettings.Text = "Tool settings"; + // + // labelWorkingDir + // + labelWorkingDir.AutoSize = true; + labelWorkingDir.Location = new System.Drawing.Point(474, 86); + labelWorkingDir.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelWorkingDir.Name = "labelWorkingDir"; + labelWorkingDir.Size = new System.Drawing.Size(72, 15); + labelWorkingDir.TabIndex = 11; + labelWorkingDir.Text = "Working dir:"; + // + // buttonWorkingDir + // + buttonWorkingDir.Location = new System.Drawing.Point(856, 80); + buttonWorkingDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonWorkingDir.Name = "buttonWorkingDir"; + buttonWorkingDir.Size = new System.Drawing.Size(45, 31); + buttonWorkingDir.TabIndex = 10; + buttonWorkingDir.Text = "..."; + buttonWorkingDir.UseVisualStyleBackColor = true; + buttonWorkingDir.Click += OnBtnWorkingDirClick; + // + // textBoxWorkingDir + // + textBoxWorkingDir.Location = new System.Drawing.Point(576, 82); + textBoxWorkingDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + textBoxWorkingDir.Name = "textBoxWorkingDir"; + textBoxWorkingDir.Size = new System.Drawing.Size(270, 23); + textBoxWorkingDir.TabIndex = 9; + // + // buttonIcon + // + buttonIcon.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; + buttonIcon.Location = new System.Drawing.Point(418, 26); + buttonIcon.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonIcon.Name = "buttonIcon"; + buttonIcon.Size = new System.Drawing.Size(112, 35); + buttonIcon.TabIndex = 1; + buttonIcon.Text = " Icon..."; + buttonIcon.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; + buttonIcon.UseVisualStyleBackColor = true; + buttonIcon.Click += OnBtnIconClick; + // + // labelToolName + // + labelToolName.AutoSize = true; + labelToolName.Location = new System.Drawing.Point(9, 34); + labelToolName.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelToolName.Name = "labelToolName"; + labelToolName.Size = new System.Drawing.Size(42, 15); + labelToolName.TabIndex = 8; + labelToolName.Text = "Name:"; + // + // labelToolColumnizerForOutput + // + labelToolColumnizerForOutput.AutoSize = true; + labelToolColumnizerForOutput.Location = new System.Drawing.Point(404, 185); + labelToolColumnizerForOutput.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelToolColumnizerForOutput.Name = "labelToolColumnizerForOutput"; + labelToolColumnizerForOutput.Size = new System.Drawing.Size(128, 15); + labelToolColumnizerForOutput.TabIndex = 6; + labelToolColumnizerForOutput.Text = "Columnizer for output:"; + // + // comboBoxColumnizer + // + comboBoxColumnizer.FormattingEnabled = true; + comboBoxColumnizer.Location = new System.Drawing.Point(576, 180); + comboBoxColumnizer.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + comboBoxColumnizer.Name = "comboBoxColumnizer"; + comboBoxColumnizer.Size = new System.Drawing.Size(270, 23); + comboBoxColumnizer.TabIndex = 7; + // + // textBoxToolName + // + textBoxToolName.Location = new System.Drawing.Point(108, 29); + textBoxToolName.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + textBoxToolName.Name = "textBoxToolName"; + textBoxToolName.Size = new System.Drawing.Size(298, 23); + textBoxToolName.TabIndex = 0; + // + // checkBoxSysout + // + checkBoxSysout.AutoSize = true; + checkBoxSysout.Location = new System.Drawing.Point(108, 183); + checkBoxSysout.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxSysout.Name = "checkBoxSysout"; + checkBoxSysout.Size = new System.Drawing.Size(120, 19); + checkBoxSysout.TabIndex = 6; + checkBoxSysout.Text = "Pipe sysout to tab"; + checkBoxSysout.UseVisualStyleBackColor = true; + checkBoxSysout.CheckedChanged += OnChkBoxSysoutCheckedChanged; + // + // buttonArguments + // + buttonArguments.Location = new System.Drawing.Point(856, 128); + buttonArguments.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonArguments.Name = "buttonArguments"; + buttonArguments.Size = new System.Drawing.Size(46, 32); + buttonArguments.TabIndex = 5; + buttonArguments.Text = "..."; + buttonArguments.UseVisualStyleBackColor = true; + buttonArguments.Click += OnBtnArgClick; + // + // labelTool + // + labelTool.AutoSize = true; + labelTool.Location = new System.Drawing.Point(9, 86); + labelTool.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelTool.Name = "labelTool"; + labelTool.Size = new System.Drawing.Size(56, 15); + labelTool.TabIndex = 4; + labelTool.Text = "Program:"; + // + // buttonTool + // + buttonTool.Location = new System.Drawing.Point(418, 78); + buttonTool.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonTool.Name = "buttonTool"; + buttonTool.Size = new System.Drawing.Size(45, 31); + buttonTool.TabIndex = 3; + buttonTool.Text = "..."; + buttonTool.UseVisualStyleBackColor = true; + buttonTool.Click += OnBtnToolClick; + // + // textBoxTool + // + textBoxTool.Location = new System.Drawing.Point(108, 80); + textBoxTool.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + textBoxTool.Name = "textBoxTool"; + textBoxTool.Size = new System.Drawing.Size(298, 23); + textBoxTool.TabIndex = 2; + // + // labelArguments + // + labelArguments.AutoSize = true; + labelArguments.Location = new System.Drawing.Point(9, 134); + labelArguments.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelArguments.Name = "labelArguments"; + labelArguments.Size = new System.Drawing.Size(69, 15); + labelArguments.TabIndex = 1; + labelArguments.Text = "Arguments:"; + // + // textBoxArguments + // + textBoxArguments.Location = new System.Drawing.Point(108, 129); + textBoxArguments.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + textBoxArguments.Name = "textBoxArguments"; + textBoxArguments.Size = new System.Drawing.Size(738, 23); + textBoxArguments.TabIndex = 4; + // + // tabPageColumnizers + // + tabPageColumnizers.Controls.Add(checkBoxAutoPick); + tabPageColumnizers.Controls.Add(checkBoxMaskPrio); + tabPageColumnizers.Controls.Add(buttonDelete); + tabPageColumnizers.Controls.Add(dataGridViewColumnizer); + tabPageColumnizers.Location = new System.Drawing.Point(4, 24); + tabPageColumnizers.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageColumnizers.Name = "tabPageColumnizers"; + tabPageColumnizers.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageColumnizers.Size = new System.Drawing.Size(942, 440); + tabPageColumnizers.TabIndex = 3; + tabPageColumnizers.Text = "Columnizers"; + tabPageColumnizers.UseVisualStyleBackColor = true; + // + // checkBoxAutoPick + // + checkBoxAutoPick.AutoSize = true; + checkBoxAutoPick.Checked = true; + checkBoxAutoPick.CheckState = System.Windows.Forms.CheckState.Checked; + checkBoxAutoPick.Location = new System.Drawing.Point(530, 386); + checkBoxAutoPick.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxAutoPick.Name = "checkBoxAutoPick"; + checkBoxAutoPick.Size = new System.Drawing.Size(192, 19); + checkBoxAutoPick.TabIndex = 5; + checkBoxAutoPick.Text = "Automatically pick for new files"; + checkBoxAutoPick.UseVisualStyleBackColor = true; + // + // checkBoxMaskPrio + // + checkBoxMaskPrio.AutoSize = true; + checkBoxMaskPrio.Location = new System.Drawing.Point(213, 388); + checkBoxMaskPrio.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxMaskPrio.Name = "checkBoxMaskPrio"; + checkBoxMaskPrio.Size = new System.Drawing.Size(192, 19); + checkBoxMaskPrio.TabIndex = 4; + checkBoxMaskPrio.Text = "Mask has priority before history"; + checkBoxMaskPrio.UseVisualStyleBackColor = true; + // + // buttonDelete + // + buttonDelete.Location = new System.Drawing.Point(12, 380); + buttonDelete.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonDelete.Name = "buttonDelete"; + buttonDelete.Size = new System.Drawing.Size(112, 35); + buttonDelete.TabIndex = 3; + buttonDelete.Text = "Delete"; + buttonDelete.UseVisualStyleBackColor = true; + buttonDelete.Click += OnBtnDeleteClick; + // + // dataGridViewColumnizer + // + dataGridViewColumnizer.AllowUserToResizeRows = false; + dataGridViewColumnizer.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + dataGridViewColumnizer.BackgroundColor = System.Drawing.SystemColors.ControlLight; + dataGridViewColumnizer.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridViewColumnizer.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { columnFileMask, columnColumnizer }); + dataGridViewColumnizer.Dock = System.Windows.Forms.DockStyle.Top; + dataGridViewColumnizer.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; + dataGridViewColumnizer.Location = new System.Drawing.Point(4, 5); + dataGridViewColumnizer.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + dataGridViewColumnizer.Name = "dataGridViewColumnizer"; + dataGridViewColumnizer.RowHeadersWidth = 62; + dataGridViewColumnizer.Size = new System.Drawing.Size(934, 365); + dataGridViewColumnizer.TabIndex = 2; + dataGridViewColumnizer.RowsAdded += OnDataGridViewColumnizerRowsAdded; + // + // columnFileMask + // + columnFileMask.HeaderText = "File name mask (RegEx)"; + columnFileMask.MinimumWidth = 40; + columnFileMask.Name = "columnFileMask"; + // + // columnColumnizer + // + columnColumnizer.HeaderText = "Columnizer"; + columnColumnizer.MinimumWidth = 230; + columnColumnizer.Name = "columnColumnizer"; + // + // tabPageHighlightMask + // + tabPageHighlightMask.Controls.Add(dataGridViewHighlightMask); + tabPageHighlightMask.Location = new System.Drawing.Point(4, 24); + tabPageHighlightMask.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageHighlightMask.Name = "tabPageHighlightMask"; + tabPageHighlightMask.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageHighlightMask.Size = new System.Drawing.Size(942, 440); + tabPageHighlightMask.TabIndex = 8; + tabPageHighlightMask.Text = "Highlight"; + tabPageHighlightMask.UseVisualStyleBackColor = true; + // + // dataGridViewHighlightMask + // + dataGridViewHighlightMask.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; + dataGridViewHighlightMask.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + dataGridViewHighlightMask.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { columnFileName, columnHighlightGroup }); + dataGridViewHighlightMask.Dock = System.Windows.Forms.DockStyle.Fill; + dataGridViewHighlightMask.Location = new System.Drawing.Point(4, 5); + dataGridViewHighlightMask.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + dataGridViewHighlightMask.Name = "dataGridViewHighlightMask"; + dataGridViewHighlightMask.RowHeadersWidth = 62; + dataGridViewHighlightMask.Size = new System.Drawing.Size(934, 430); + dataGridViewHighlightMask.TabIndex = 0; + // + // columnFileName + // + columnFileName.HeaderText = "File name mask (RegEx)"; + columnFileName.MinimumWidth = 40; + columnFileName.Name = "columnFileName"; + // + // columnHighlightGroup + // + columnHighlightGroup.HeaderText = "Highlight group"; + columnHighlightGroup.MinimumWidth = 50; + columnHighlightGroup.Name = "columnHighlightGroup"; + // + // tabPageMultiFile + // + tabPageMultiFile.Controls.Add(groupBoxDefaultFileNamePattern); + tabPageMultiFile.Controls.Add(labelHintMultiFile); + tabPageMultiFile.Controls.Add(labelNoteMultiFile); + tabPageMultiFile.Controls.Add(groupBoxWhenOpeningMultiFile); + tabPageMultiFile.Location = new System.Drawing.Point(4, 24); + tabPageMultiFile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageMultiFile.Name = "tabPageMultiFile"; + tabPageMultiFile.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageMultiFile.Size = new System.Drawing.Size(942, 440); + tabPageMultiFile.TabIndex = 4; + tabPageMultiFile.Text = "MultiFile"; + tabPageMultiFile.UseVisualStyleBackColor = true; + // + // groupBoxDefaultFileNamePattern + // + groupBoxDefaultFileNamePattern.Controls.Add(labelMaxDays); + groupBoxDefaultFileNamePattern.Controls.Add(labelPattern); + groupBoxDefaultFileNamePattern.Controls.Add(upDownMultifileDays); + groupBoxDefaultFileNamePattern.Controls.Add(textBoxMultifilePattern); + groupBoxDefaultFileNamePattern.Location = new System.Drawing.Point(364, 28); + groupBoxDefaultFileNamePattern.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxDefaultFileNamePattern.Name = "groupBoxDefaultFileNamePattern"; + groupBoxDefaultFileNamePattern.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxDefaultFileNamePattern.Size = new System.Drawing.Size(436, 154); + groupBoxDefaultFileNamePattern.TabIndex = 3; + groupBoxDefaultFileNamePattern.TabStop = false; + groupBoxDefaultFileNamePattern.Text = "Default filename pattern"; + // + // labelMaxDays + // + labelMaxDays.AutoSize = true; + labelMaxDays.Location = new System.Drawing.Point(10, 75); + labelMaxDays.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelMaxDays.Name = "labelMaxDays"; + labelMaxDays.Size = new System.Drawing.Size(59, 15); + labelMaxDays.TabIndex = 3; + labelMaxDays.Text = "Max days:"; + // + // labelPattern + // + labelPattern.AutoSize = true; + labelPattern.Location = new System.Drawing.Point(10, 37); + labelPattern.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelPattern.Name = "labelPattern"; + labelPattern.Size = new System.Drawing.Size(48, 15); + labelPattern.TabIndex = 2; + labelPattern.Text = "Pattern:"; + // + // upDownMultifileDays + // + upDownMultifileDays.Location = new System.Drawing.Point(102, 72); + upDownMultifileDays.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + upDownMultifileDays.Maximum = new decimal(new int[] { 40, 0, 0, 0 }); + upDownMultifileDays.Name = "upDownMultifileDays"; + helpProvider.SetShowHelp(upDownMultifileDays, false); + upDownMultifileDays.Size = new System.Drawing.Size(92, 23); + upDownMultifileDays.TabIndex = 1; + upDownMultifileDays.Value = new decimal(new int[] { 1, 0, 0, 0 }); + // + // textBoxMultifilePattern + // + textBoxMultifilePattern.Location = new System.Drawing.Point(102, 32); + textBoxMultifilePattern.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + textBoxMultifilePattern.Name = "textBoxMultifilePattern"; + textBoxMultifilePattern.Size = new System.Drawing.Size(278, 23); + textBoxMultifilePattern.TabIndex = 0; + textBoxMultifilePattern.TextChanged += OnMultiFilePatternTextChanged; + // + // labelHintMultiFile + // + labelHintMultiFile.Location = new System.Drawing.Point(6, 203); + labelHintMultiFile.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelHintMultiFile.Name = "labelHintMultiFile"; + labelHintMultiFile.Size = new System.Drawing.Size(304, 111); + labelHintMultiFile.TabIndex = 2; + labelHintMultiFile.Text = "Hint: Pressing the Shift key while dropping files onto LogExpert will switch the behaviour from single to multi and vice versa."; + // + // labelNoteMultiFile + // + labelNoteMultiFile.Location = new System.Drawing.Point(6, 314); + labelNoteMultiFile.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelNoteMultiFile.Name = "labelNoteMultiFile"; + labelNoteMultiFile.Size = new System.Drawing.Size(705, 82); + labelNoteMultiFile.TabIndex = 1; + labelNoteMultiFile.Text = resources.GetString("labelNoteMultiFile.Text"); + // + // groupBoxWhenOpeningMultiFile + // + groupBoxWhenOpeningMultiFile.Controls.Add(radioButtonAskWhatToDo); + groupBoxWhenOpeningMultiFile.Controls.Add(radioButtonTreatAllFilesAsOneMultifile); + groupBoxWhenOpeningMultiFile.Controls.Add(radioButtonLoadEveryFileIntoSeperatedTab); + groupBoxWhenOpeningMultiFile.Location = new System.Drawing.Point(10, 28); + groupBoxWhenOpeningMultiFile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxWhenOpeningMultiFile.Name = "groupBoxWhenOpeningMultiFile"; + groupBoxWhenOpeningMultiFile.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxWhenOpeningMultiFile.Size = new System.Drawing.Size(300, 154); + groupBoxWhenOpeningMultiFile.TabIndex = 0; + groupBoxWhenOpeningMultiFile.TabStop = false; + groupBoxWhenOpeningMultiFile.Text = "When opening multiple files..."; + // + // radioButtonAskWhatToDo + // + radioButtonAskWhatToDo.AutoSize = true; + radioButtonAskWhatToDo.Location = new System.Drawing.Point(10, 105); + radioButtonAskWhatToDo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonAskWhatToDo.Name = "radioButtonAskWhatToDo"; + radioButtonAskWhatToDo.Size = new System.Drawing.Size(104, 19); + radioButtonAskWhatToDo.TabIndex = 2; + radioButtonAskWhatToDo.TabStop = true; + radioButtonAskWhatToDo.Text = "Ask what to do"; + radioButtonAskWhatToDo.UseVisualStyleBackColor = true; + // + // radioButtonTreatAllFilesAsOneMultifile + // + radioButtonTreatAllFilesAsOneMultifile.AutoSize = true; + radioButtonTreatAllFilesAsOneMultifile.Location = new System.Drawing.Point(10, 68); + radioButtonTreatAllFilesAsOneMultifile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonTreatAllFilesAsOneMultifile.Name = "radioButtonTreatAllFilesAsOneMultifile"; + radioButtonTreatAllFilesAsOneMultifile.Size = new System.Drawing.Size(182, 19); + radioButtonTreatAllFilesAsOneMultifile.TabIndex = 1; + radioButtonTreatAllFilesAsOneMultifile.TabStop = true; + radioButtonTreatAllFilesAsOneMultifile.Text = "Treat all files as one 'MultiFile'"; + radioButtonTreatAllFilesAsOneMultifile.UseVisualStyleBackColor = true; + // + // radioButtonLoadEveryFileIntoSeperatedTab + // + radioButtonLoadEveryFileIntoSeperatedTab.AutoSize = true; + radioButtonLoadEveryFileIntoSeperatedTab.Location = new System.Drawing.Point(10, 31); + radioButtonLoadEveryFileIntoSeperatedTab.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonLoadEveryFileIntoSeperatedTab.Name = "radioButtonLoadEveryFileIntoSeperatedTab"; + radioButtonLoadEveryFileIntoSeperatedTab.Size = new System.Drawing.Size(201, 19); + radioButtonLoadEveryFileIntoSeperatedTab.TabIndex = 0; + radioButtonLoadEveryFileIntoSeperatedTab.TabStop = true; + radioButtonLoadEveryFileIntoSeperatedTab.Text = "Load every file into a separate tab"; + radioButtonLoadEveryFileIntoSeperatedTab.UseVisualStyleBackColor = true; + // + // tabPagePlugins + // + tabPagePlugins.Controls.Add(groupBoxPlugins); + tabPagePlugins.Controls.Add(groupBoxSettings); + tabPagePlugins.Location = new System.Drawing.Point(4, 24); + tabPagePlugins.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPagePlugins.Name = "tabPagePlugins"; + tabPagePlugins.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPagePlugins.Size = new System.Drawing.Size(942, 440); + tabPagePlugins.TabIndex = 5; + tabPagePlugins.Text = "Plugins"; + tabPagePlugins.UseVisualStyleBackColor = true; + // + // groupBoxPlugins + // + groupBoxPlugins.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + groupBoxPlugins.Controls.Add(listBoxPlugin); + groupBoxPlugins.Location = new System.Drawing.Point(10, 23); + groupBoxPlugins.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxPlugins.Name = "groupBoxPlugins"; + groupBoxPlugins.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxPlugins.Size = new System.Drawing.Size(342, 400); + groupBoxPlugins.TabIndex = 3; + groupBoxPlugins.TabStop = false; + groupBoxPlugins.Text = "Plugins"; + // + // listBoxPlugin + // + listBoxPlugin.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + listBoxPlugin.DisplayMember = "Text"; + listBoxPlugin.FormattingEnabled = true; + listBoxPlugin.ItemHeight = 15; + listBoxPlugin.Location = new System.Drawing.Point(9, 29); + listBoxPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + listBoxPlugin.Name = "listBoxPlugin"; + listBoxPlugin.Size = new System.Drawing.Size(322, 349); + listBoxPlugin.TabIndex = 0; + listBoxPlugin.ValueMember = "Text"; + listBoxPlugin.SelectedIndexChanged += OnListBoxPluginSelectedIndexChanged; + // + // groupBoxSettings + // + groupBoxSettings.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + groupBoxSettings.Controls.Add(panelPlugin); + groupBoxSettings.Location = new System.Drawing.Point(362, 23); + groupBoxSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxSettings.Name = "groupBoxSettings"; + groupBoxSettings.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxSettings.Size = new System.Drawing.Size(567, 400); + groupBoxSettings.TabIndex = 2; + groupBoxSettings.TabStop = false; + groupBoxSettings.Text = "Settings"; + // + // panelPlugin + // + panelPlugin.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; + panelPlugin.AutoScroll = true; + panelPlugin.Controls.Add(buttonConfigPlugin); + panelPlugin.Location = new System.Drawing.Point(9, 29); + panelPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + panelPlugin.Name = "panelPlugin"; + panelPlugin.Size = new System.Drawing.Size(549, 362); + panelPlugin.TabIndex = 1; + // + // buttonConfigPlugin + // + buttonConfigPlugin.Location = new System.Drawing.Point(164, 163); + buttonConfigPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonConfigPlugin.Name = "buttonConfigPlugin"; + buttonConfigPlugin.Size = new System.Drawing.Size(170, 35); + buttonConfigPlugin.TabIndex = 0; + buttonConfigPlugin.Text = "Configure..."; + buttonConfigPlugin.UseVisualStyleBackColor = true; + buttonConfigPlugin.Click += OnBtnConfigPluginClick; + // + // tabPageSessions + // + tabPageSessions.Controls.Add(checkBoxPortableMode); + tabPageSessions.Controls.Add(checkBoxSaveFilter); + tabPageSessions.Controls.Add(groupBoxPersistantFileLocation); + tabPageSessions.Controls.Add(checkBoxSaveSessions); + tabPageSessions.Location = new System.Drawing.Point(4, 24); + tabPageSessions.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageSessions.Name = "tabPageSessions"; + tabPageSessions.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageSessions.Size = new System.Drawing.Size(942, 440); + tabPageSessions.TabIndex = 6; + tabPageSessions.Text = "Persistence"; + tabPageSessions.UseVisualStyleBackColor = true; + // + // checkBoxPortableMode + // + checkBoxPortableMode.AutoSize = true; + checkBoxPortableMode.Location = new System.Drawing.Point(35, 110); + checkBoxPortableMode.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxPortableMode.Name = "checkBoxPortableMode"; + checkBoxPortableMode.Size = new System.Drawing.Size(150, 19); + checkBoxPortableMode.TabIndex = 3; + checkBoxPortableMode.Text = "Activate Portable Mode"; + toolTip.SetToolTip(checkBoxPortableMode, "If this mode is activated, the save file will be loaded from the Executable Location"); + checkBoxPortableMode.UseVisualStyleBackColor = true; + checkBoxPortableMode.CheckedChanged += OnPortableModeCheckedChanged; + // + // checkBoxSaveFilter + // + checkBoxSaveFilter.AutoSize = true; + checkBoxSaveFilter.Location = new System.Drawing.Point(35, 75); + checkBoxSaveFilter.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxSaveFilter.Name = "checkBoxSaveFilter"; + checkBoxSaveFilter.Size = new System.Drawing.Size(217, 19); + checkBoxSaveFilter.TabIndex = 2; + checkBoxSaveFilter.Text = " Save and restore filter and filter tabs"; + checkBoxSaveFilter.UseVisualStyleBackColor = true; + // + // groupBoxPersistantFileLocation + // + groupBoxPersistantFileLocation.Controls.Add(labelSessionSaveOwnDir); + groupBoxPersistantFileLocation.Controls.Add(buttonSessionSaveDir); + groupBoxPersistantFileLocation.Controls.Add(radioButtonSessionSaveOwn); + groupBoxPersistantFileLocation.Controls.Add(radioButtonsessionSaveDocuments); + groupBoxPersistantFileLocation.Controls.Add(radioButtonSessionSameDir); + groupBoxPersistantFileLocation.Controls.Add(radioButtonSessionApplicationStartupDir); + groupBoxPersistantFileLocation.Location = new System.Drawing.Point(34, 145); + groupBoxPersistantFileLocation.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxPersistantFileLocation.Name = "groupBoxPersistantFileLocation"; + groupBoxPersistantFileLocation.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxPersistantFileLocation.Size = new System.Drawing.Size(411, 190); + groupBoxPersistantFileLocation.TabIndex = 1; + groupBoxPersistantFileLocation.TabStop = false; + groupBoxPersistantFileLocation.Text = "Persistence file location"; + // + // labelSessionSaveOwnDir + // + labelSessionSaveOwnDir.Location = new System.Drawing.Point(27, 160); + labelSessionSaveOwnDir.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelSessionSaveOwnDir.Name = "labelSessionSaveOwnDir"; + labelSessionSaveOwnDir.Size = new System.Drawing.Size(252, 31); + labelSessionSaveOwnDir.TabIndex = 4; + labelSessionSaveOwnDir.Text = "sessionSaveOwnDirLabel"; + // + // buttonSessionSaveDir + // + buttonSessionSaveDir.Location = new System.Drawing.Point(358, 135); + buttonSessionSaveDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonSessionSaveDir.Name = "buttonSessionSaveDir"; + buttonSessionSaveDir.Size = new System.Drawing.Size(45, 19); + buttonSessionSaveDir.TabIndex = 3; + buttonSessionSaveDir.Text = "..."; + buttonSessionSaveDir.UseVisualStyleBackColor = true; + buttonSessionSaveDir.Click += OnBtnSessionSaveDirClick; + // + // radioButtonSessionSaveOwn + // + radioButtonSessionSaveOwn.AutoSize = true; + radioButtonSessionSaveOwn.Location = new System.Drawing.Point(10, 135); + radioButtonSessionSaveOwn.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonSessionSaveOwn.Name = "radioButtonSessionSaveOwn"; + radioButtonSessionSaveOwn.Size = new System.Drawing.Size(100, 19); + radioButtonSessionSaveOwn.TabIndex = 2; + radioButtonSessionSaveOwn.TabStop = true; + radioButtonSessionSaveOwn.Text = "Own directory"; + radioButtonSessionSaveOwn.UseVisualStyleBackColor = true; + // + // radioButtonsessionSaveDocuments + // + radioButtonsessionSaveDocuments.AutoSize = true; + radioButtonsessionSaveDocuments.Location = new System.Drawing.Point(10, 65); + radioButtonsessionSaveDocuments.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonsessionSaveDocuments.Name = "radioButtonsessionSaveDocuments"; + radioButtonsessionSaveDocuments.Size = new System.Drawing.Size(160, 19); + radioButtonsessionSaveDocuments.TabIndex = 1; + radioButtonsessionSaveDocuments.TabStop = true; + radioButtonsessionSaveDocuments.Text = "MyDocuments/LogExpert"; + radioButtonsessionSaveDocuments.UseVisualStyleBackColor = true; + // + // radioButtonSessionSameDir + // + radioButtonSessionSameDir.AutoSize = true; + radioButtonSessionSameDir.Location = new System.Drawing.Point(10, 30); + radioButtonSessionSameDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonSessionSameDir.Name = "radioButtonSessionSameDir"; + radioButtonSessionSameDir.Size = new System.Drawing.Size(157, 19); + radioButtonSessionSameDir.TabIndex = 0; + radioButtonSessionSameDir.TabStop = true; + radioButtonSessionSameDir.Text = "Same directory as log file"; + radioButtonSessionSameDir.UseVisualStyleBackColor = true; + // + // radioButtonSessionApplicationStartupDir + // + radioButtonSessionApplicationStartupDir.AutoSize = true; + radioButtonSessionApplicationStartupDir.Location = new System.Drawing.Point(10, 100); + radioButtonSessionApplicationStartupDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + radioButtonSessionApplicationStartupDir.Name = "radioButtonSessionApplicationStartupDir"; + radioButtonSessionApplicationStartupDir.Size = new System.Drawing.Size(176, 19); + radioButtonSessionApplicationStartupDir.TabIndex = 5; + radioButtonSessionApplicationStartupDir.TabStop = true; + radioButtonSessionApplicationStartupDir.Text = "Application startup directory"; + toolTip.SetToolTip(radioButtonSessionApplicationStartupDir, "This path is based on the executable and where it has been started from."); + radioButtonSessionApplicationStartupDir.UseVisualStyleBackColor = true; + // + // checkBoxSaveSessions + // + checkBoxSaveSessions.AutoSize = true; + checkBoxSaveSessions.Location = new System.Drawing.Point(35, 40); + checkBoxSaveSessions.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxSaveSessions.Name = "checkBoxSaveSessions"; + checkBoxSaveSessions.Size = new System.Drawing.Size(241, 19); + checkBoxSaveSessions.TabIndex = 0; + checkBoxSaveSessions.Text = "Automatically save persistence files (.lxp)"; + checkBoxSaveSessions.UseVisualStyleBackColor = true; + // + // tabPageMemory + // + tabPageMemory.Controls.Add(groupBoxCPUAndStuff); + tabPageMemory.Controls.Add(groupBoxLineBufferUsage); + tabPageMemory.Location = new System.Drawing.Point(4, 24); + tabPageMemory.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageMemory.Name = "tabPageMemory"; + tabPageMemory.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + tabPageMemory.Size = new System.Drawing.Size(942, 440); + tabPageMemory.TabIndex = 7; + tabPageMemory.Text = "Memory/CPU"; + tabPageMemory.UseVisualStyleBackColor = true; + // + // groupBoxCPUAndStuff + // + groupBoxCPUAndStuff.Controls.Add(checkBoxLegacyReader); + groupBoxCPUAndStuff.Controls.Add(checkBoxMultiThread); + groupBoxCPUAndStuff.Controls.Add(labelFilePollingInterval); + groupBoxCPUAndStuff.Controls.Add(upDownPollingInterval); + groupBoxCPUAndStuff.Location = new System.Drawing.Point(408, 29); + groupBoxCPUAndStuff.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxCPUAndStuff.Name = "groupBoxCPUAndStuff"; + groupBoxCPUAndStuff.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxCPUAndStuff.Size = new System.Drawing.Size(300, 197); + groupBoxCPUAndStuff.TabIndex = 8; + groupBoxCPUAndStuff.TabStop = false; + groupBoxCPUAndStuff.Text = "CPU and stuff"; + // + // checkBoxLegacyReader + // + checkBoxLegacyReader.AutoSize = true; + checkBoxLegacyReader.Location = new System.Drawing.Point(14, 138); + checkBoxLegacyReader.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxLegacyReader.Name = "checkBoxLegacyReader"; + checkBoxLegacyReader.Size = new System.Drawing.Size(182, 19); + checkBoxLegacyReader.TabIndex = 9; + checkBoxLegacyReader.Text = "Use legacy file reader (slower)"; + toolTip.SetToolTip(checkBoxLegacyReader, "Slower but more compatible with strange linefeeds and encodings"); + checkBoxLegacyReader.UseVisualStyleBackColor = true; + // + // checkBoxMultiThread + // + checkBoxMultiThread.AutoSize = true; + checkBoxMultiThread.Location = new System.Drawing.Point(14, 103); + checkBoxMultiThread.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + checkBoxMultiThread.Name = "checkBoxMultiThread"; + checkBoxMultiThread.Size = new System.Drawing.Size(131, 19); + checkBoxMultiThread.TabIndex = 5; + checkBoxMultiThread.Text = "Multi threaded filter"; + checkBoxMultiThread.UseVisualStyleBackColor = true; + // + // labelFilePollingInterval + // + labelFilePollingInterval.AutoSize = true; + labelFilePollingInterval.Location = new System.Drawing.Point(9, 52); + labelFilePollingInterval.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelFilePollingInterval.Name = "labelFilePollingInterval"; + labelFilePollingInterval.Size = new System.Drawing.Size(137, 15); + labelFilePollingInterval.TabIndex = 7; + labelFilePollingInterval.Text = "File polling interval (ms):"; + // + // upDownPollingInterval + // + upDownPollingInterval.Location = new System.Drawing.Point(190, 49); + upDownPollingInterval.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + upDownPollingInterval.Maximum = new decimal(new int[] { 5000, 0, 0, 0 }); + upDownPollingInterval.Minimum = new decimal(new int[] { 20, 0, 0, 0 }); + upDownPollingInterval.Name = "upDownPollingInterval"; + upDownPollingInterval.Size = new System.Drawing.Size(86, 23); + upDownPollingInterval.TabIndex = 6; + upDownPollingInterval.Value = new decimal(new int[] { 20, 0, 0, 0 }); + // + // groupBoxLineBufferUsage + // + groupBoxLineBufferUsage.Controls.Add(labelInfo); + groupBoxLineBufferUsage.Controls.Add(labelNumberOfBlocks); + groupBoxLineBufferUsage.Controls.Add(upDownLinesPerBlock); + groupBoxLineBufferUsage.Controls.Add(upDownBlockCount); + groupBoxLineBufferUsage.Controls.Add(labelLinesPerBlock); + groupBoxLineBufferUsage.Location = new System.Drawing.Point(10, 29); + groupBoxLineBufferUsage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxLineBufferUsage.Name = "groupBoxLineBufferUsage"; + groupBoxLineBufferUsage.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); + groupBoxLineBufferUsage.Size = new System.Drawing.Size(326, 197); + groupBoxLineBufferUsage.TabIndex = 4; + groupBoxLineBufferUsage.TabStop = false; + groupBoxLineBufferUsage.Text = "Line buffer usage"; + // + // labelInfo + // + labelInfo.AutoSize = true; + labelInfo.Location = new System.Drawing.Point(9, 145); + labelInfo.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelInfo.Name = "labelInfo"; + labelInfo.Size = new System.Drawing.Size(219, 15); + labelInfo.TabIndex = 4; + labelInfo.Text = "Changes will take effect on next file load"; + // + // labelNumberOfBlocks + // + labelNumberOfBlocks.AutoSize = true; + labelNumberOfBlocks.Location = new System.Drawing.Point(9, 52); + labelNumberOfBlocks.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelNumberOfBlocks.Name = "labelNumberOfBlocks"; + labelNumberOfBlocks.Size = new System.Drawing.Size(102, 15); + labelNumberOfBlocks.TabIndex = 1; + labelNumberOfBlocks.Text = "Number of blocks"; + // + // upDownLinesPerBlock + // + upDownLinesPerBlock.Location = new System.Drawing.Point(210, 102); + upDownLinesPerBlock.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + upDownLinesPerBlock.Maximum = new decimal(new int[] { 5000000, 0, 0, 0 }); + upDownLinesPerBlock.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); + upDownLinesPerBlock.Name = "upDownLinesPerBlock"; + upDownLinesPerBlock.Size = new System.Drawing.Size(94, 23); + upDownLinesPerBlock.TabIndex = 3; + upDownLinesPerBlock.Value = new decimal(new int[] { 50000, 0, 0, 0 }); + upDownLinesPerBlock.ValueChanged += OnNumericUpDown1ValueChanged; + // + // upDownBlockCount + // + upDownBlockCount.Location = new System.Drawing.Point(210, 49); + upDownBlockCount.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + upDownBlockCount.Maximum = new decimal(new int[] { 5000, 0, 0, 0 }); + upDownBlockCount.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); + upDownBlockCount.Name = "upDownBlockCount"; + upDownBlockCount.Size = new System.Drawing.Size(94, 23); + upDownBlockCount.TabIndex = 0; + upDownBlockCount.Value = new decimal(new int[] { 100, 0, 0, 0 }); + // + // labelLinesPerBlock + // + labelLinesPerBlock.AutoSize = true; + labelLinesPerBlock.Location = new System.Drawing.Point(9, 105); + labelLinesPerBlock.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); + labelLinesPerBlock.Name = "labelLinesPerBlock"; + labelLinesPerBlock.Size = new System.Drawing.Size(68, 15); + labelLinesPerBlock.TabIndex = 2; + labelLinesPerBlock.Text = "Lines/block"; + // + // buttonCancel + // + buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + buttonCancel.Location = new System.Drawing.Point(818, 509); + buttonCancel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonCancel.Name = "buttonCancel"; + buttonCancel.Size = new System.Drawing.Size(112, 35); + buttonCancel.TabIndex = 1; + buttonCancel.Text = "Cancel"; + buttonCancel.UseVisualStyleBackColor = true; + buttonCancel.Click += OnBtnCancelClick; + // + // buttonOk + // + buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + buttonOk.Location = new System.Drawing.Point(696, 509); + buttonOk.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonOk.Name = "buttonOk"; + buttonOk.Size = new System.Drawing.Size(112, 35); + buttonOk.TabIndex = 0; + buttonOk.Text = "OK"; + buttonOk.UseVisualStyleBackColor = true; + buttonOk.Click += OnBtnOkClick; + // + // helpProvider + // + helpProvider.HelpNamespace = "LogExpert.chm"; + // + // buttonExport + // + buttonExport.Location = new System.Drawing.Point(20, 509); + buttonExport.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonExport.Name = "buttonExport"; + buttonExport.Size = new System.Drawing.Size(112, 35); + buttonExport.TabIndex = 2; + buttonExport.Text = "Export..."; + buttonExport.UseVisualStyleBackColor = true; + buttonExport.Click += OnBtnExportClick; + // + // buttonImport + // + buttonImport.Location = new System.Drawing.Point(142, 509); + buttonImport.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + buttonImport.Name = "buttonImport"; + buttonImport.Size = new System.Drawing.Size(112, 35); + buttonImport.TabIndex = 3; + buttonImport.Text = "Import..."; + buttonImport.UseVisualStyleBackColor = true; + buttonImport.Click += OnBtnImportClick; + // + // dataGridViewTextBoxColumn1 + // + dataGridViewTextBoxColumn1.HeaderText = "File name mask (RegEx)"; + dataGridViewTextBoxColumn1.MinimumWidth = 40; + dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; + dataGridViewTextBoxColumn1.Width = 99; + // + // dataGridViewTextBoxColumn2 + // + dataGridViewTextBoxColumn2.HeaderText = "File name mask (RegEx)"; + dataGridViewTextBoxColumn2.MinimumWidth = 40; + dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; + dataGridViewTextBoxColumn2.Width = 259; + // + // SettingsDialog + // + AcceptButton = buttonOk; + CancelButton = buttonCancel; + ClientSize = new System.Drawing.Size(956, 563); + Controls.Add(buttonImport); + Controls.Add(buttonExport); + Controls.Add(buttonOk); + Controls.Add(buttonCancel); + Controls.Add(tabControlSettings); + FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + helpProvider.SetHelpKeyword(this, "Settings.htm"); + helpProvider.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); + Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); + Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); + MaximizeBox = false; + MinimizeBox = false; + Name = "SettingsDialog"; + helpProvider.SetShowHelp(this, true); + StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + Text = "Settings"; + Load += OnSettingsDialogLoad; + tabControlSettings.ResumeLayout(false); + tabPageViewSettings.ResumeLayout(false); + tabPageViewSettings.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)upDownMaximumLineLength).EndInit(); + ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntriesDisplayed).EndInit(); + ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntries).EndInit(); + groupBoxMisc.ResumeLayout(false); + groupBoxMisc.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)cpDownColumnWidth).EndInit(); + groupBoxDefaults.ResumeLayout(false); + groupBoxDefaults.PerformLayout(); + groupBoxFont.ResumeLayout(false); + tabPageTimeStampFeatures.ResumeLayout(false); + groupBoxTimeSpreadDisplay.ResumeLayout(false); + groupBoxTimeSpreadDisplay.PerformLayout(); + groupBoxDisplayMode.ResumeLayout(false); + groupBoxDisplayMode.PerformLayout(); + groupBoxTimeStampNavigationControl.ResumeLayout(false); + groupBoxTimeStampNavigationControl.PerformLayout(); + groupBoxMouseDragDefaults.ResumeLayout(false); + groupBoxMouseDragDefaults.PerformLayout(); + tabPageExternalTools.ResumeLayout(false); + groupBoxToolSettings.ResumeLayout(false); + groupBoxToolSettings.PerformLayout(); + tabPageColumnizers.ResumeLayout(false); + tabPageColumnizers.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)dataGridViewColumnizer).EndInit(); + tabPageHighlightMask.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)dataGridViewHighlightMask).EndInit(); + tabPageMultiFile.ResumeLayout(false); + groupBoxDefaultFileNamePattern.ResumeLayout(false); + groupBoxDefaultFileNamePattern.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)upDownMultifileDays).EndInit(); + groupBoxWhenOpeningMultiFile.ResumeLayout(false); + groupBoxWhenOpeningMultiFile.PerformLayout(); + tabPagePlugins.ResumeLayout(false); + groupBoxPlugins.ResumeLayout(false); + groupBoxSettings.ResumeLayout(false); + panelPlugin.ResumeLayout(false); + tabPageSessions.ResumeLayout(false); + tabPageSessions.PerformLayout(); + groupBoxPersistantFileLocation.ResumeLayout(false); + groupBoxPersistantFileLocation.PerformLayout(); + tabPageMemory.ResumeLayout(false); + groupBoxCPUAndStuff.ResumeLayout(false); + groupBoxCPUAndStuff.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)upDownPollingInterval).EndInit(); + groupBoxLineBufferUsage.ResumeLayout(false); + groupBoxLineBufferUsage.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)upDownLinesPerBlock).EndInit(); + ((System.ComponentModel.ISupportInitialize)upDownBlockCount).EndInit(); + ResumeLayout(false); + } + + #endregion + + private System.Windows.Forms.TabControl tabControlSettings; + private System.Windows.Forms.TabPage tabPageViewSettings; + private System.Windows.Forms.Label labelFont; + private System.Windows.Forms.TabPage tabPageTimeStampFeatures; + private System.Windows.Forms.GroupBox groupBoxFont; + private System.Windows.Forms.Button buttonChangeFont; + private System.Windows.Forms.Button buttonCancel; + private System.Windows.Forms.Button buttonOk; + private System.Windows.Forms.CheckBox checkBoxFilterTail; + private System.Windows.Forms.CheckBox checkBoxFollowTail; + private System.Windows.Forms.CheckBox checkBoxSyncFilter; + private System.Windows.Forms.GroupBox groupBoxDefaults; + private System.Windows.Forms.CheckBox checkBoxTimestamp; + private System.Windows.Forms.GroupBox groupBoxMouseDragDefaults; + private System.Windows.Forms.RadioButton radioButtonHorizMouseDrag; + private System.Windows.Forms.RadioButton radioButtonVerticalMouseDrag; + private System.Windows.Forms.RadioButton radioButtonVerticalMouseDragInverted; + private System.Windows.Forms.TabPage tabPageExternalTools; + private System.Windows.Forms.GroupBox groupBoxToolSettings; + private System.Windows.Forms.TextBox textBoxArguments; + private System.Windows.Forms.Button buttonTool; + private System.Windows.Forms.TextBox textBoxTool; + private System.Windows.Forms.Label labelArguments; + private System.Windows.Forms.Label labelTool; + private System.Windows.Forms.Button buttonArguments; + private System.Windows.Forms.TabPage tabPageColumnizers; + private System.Windows.Forms.DataGridView dataGridViewColumnizer; + private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; + private System.Windows.Forms.Button buttonDelete; + private System.Windows.Forms.DataGridViewTextBoxColumn columnFileMask; + private System.Windows.Forms.DataGridViewComboBoxColumn columnColumnizer; + private System.Windows.Forms.CheckBox checkBoxSysout; + private System.Windows.Forms.CheckBox checkBoxMaskPrio; + private System.Windows.Forms.GroupBox groupBoxMisc; + private System.Windows.Forms.CheckBox checkBoxAskCloseTabs; + private System.Windows.Forms.TabPage tabPageMultiFile; + private System.Windows.Forms.GroupBox groupBoxWhenOpeningMultiFile; + private System.Windows.Forms.RadioButton radioButtonAskWhatToDo; + private System.Windows.Forms.RadioButton radioButtonTreatAllFilesAsOneMultifile; + private System.Windows.Forms.RadioButton radioButtonLoadEveryFileIntoSeperatedTab; + private System.Windows.Forms.Label labelNoteMultiFile; + private System.Windows.Forms.Label labelHintMultiFile; + private System.Windows.Forms.HelpProvider helpProvider; + private System.Windows.Forms.CheckBox checkBoxSingleInstance; + private System.Windows.Forms.ComboBox comboBoxColumnizer; + private System.Windows.Forms.CheckBox checkBoxOpenLastFiles; + private System.Windows.Forms.CheckBox checkBoxTailState; + private System.Windows.Forms.Button buttonTailColor; + private System.Windows.Forms.NumericUpDown cpDownColumnWidth; + private System.Windows.Forms.CheckBox checkBoxColumnSize; + private System.Windows.Forms.CheckBox checkBoxTimeSpread; + private System.Windows.Forms.GroupBox groupBoxTimeSpreadDisplay; + private System.Windows.Forms.GroupBox groupBoxTimeStampNavigationControl; + private System.Windows.Forms.Button buttonTimespreadColor; + private System.Windows.Forms.CheckBox checkBoxReverseAlpha; + private System.Windows.Forms.GroupBox groupBoxDisplayMode; + private System.Windows.Forms.RadioButton radioButtonLineView; + private System.Windows.Forms.RadioButton radioButtonTimeView; + private System.Windows.Forms.TabPage tabPagePlugins; + private System.Windows.Forms.ListBox listBoxPlugin; + private System.Windows.Forms.Panel panelPlugin; + private System.Windows.Forms.GroupBox groupBoxPlugins; + private System.Windows.Forms.GroupBox groupBoxSettings; + private System.Windows.Forms.Button buttonConfigPlugin; + private System.Windows.Forms.TabPage tabPageSessions; + private System.Windows.Forms.GroupBox groupBoxPersistantFileLocation; + private System.Windows.Forms.RadioButton radioButtonsessionSaveDocuments; + private System.Windows.Forms.RadioButton radioButtonSessionSameDir; + private System.Windows.Forms.CheckBox checkBoxSaveSessions; + private System.Windows.Forms.RadioButton radioButtonSessionSaveOwn; + private System.Windows.Forms.Label labelSessionSaveOwnDir; + private System.Windows.Forms.Button buttonSessionSaveDir; + private System.Windows.Forms.CheckBox checkBoxSaveFilter; + private System.Windows.Forms.TabPage tabPageMemory; + private System.Windows.Forms.Label labelNumberOfBlocks; + private System.Windows.Forms.NumericUpDown upDownBlockCount; + private System.Windows.Forms.NumericUpDown upDownLinesPerBlock; + private System.Windows.Forms.Label labelLinesPerBlock; + private System.Windows.Forms.GroupBox groupBoxLineBufferUsage; + private System.Windows.Forms.Label labelInfo; + private System.Windows.Forms.TabPage tabPageHighlightMask; + private System.Windows.Forms.DataGridView dataGridViewHighlightMask; + private System.Windows.Forms.DataGridViewTextBoxColumn columnFileName; + private System.Windows.Forms.DataGridViewComboBoxColumn columnHighlightGroup; + private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; + private System.Windows.Forms.CheckBox checkBoxMultiThread; + private System.Windows.Forms.Label labelFilePollingInterval; + private System.Windows.Forms.NumericUpDown upDownPollingInterval; + private System.Windows.Forms.GroupBox groupBoxCPUAndStuff; + private System.Windows.Forms.Label labelToolColumnizerForOutput; + private System.Windows.Forms.Label labelToolName; + private System.Windows.Forms.CheckedListBox listBoxTools; + private System.Windows.Forms.TextBox textBoxToolName; + private System.Windows.Forms.Button buttonToolDelete; + private System.Windows.Forms.Button buttonToolAdd; + private System.Windows.Forms.Button buttonToolDown; + private System.Windows.Forms.Button buttonToolUp; + private System.Windows.Forms.Label labelToolsDescription; + private System.Windows.Forms.Button buttonIcon; + private System.Windows.Forms.Label labelWorkingDir; + private System.Windows.Forms.Button buttonWorkingDir; + private System.Windows.Forms.TextBox textBoxWorkingDir; + private System.Windows.Forms.GroupBox groupBoxDefaultFileNamePattern; + private System.Windows.Forms.Label labelMaxDays; + private System.Windows.Forms.Label labelPattern; + private System.Windows.Forms.NumericUpDown upDownMultifileDays; + private System.Windows.Forms.TextBox textBoxMultifilePattern; + private System.Windows.Forms.Label labelDefaultEncoding; + private System.Windows.Forms.ComboBox comboBoxEncoding; + private System.Windows.Forms.ToolTip toolTip; + private System.Windows.Forms.CheckBox checkBoxColumnFinder; + private System.Windows.Forms.Button buttonExport; + private System.Windows.Forms.Button buttonImport; + private System.Windows.Forms.CheckBox checkBoxLegacyReader; + private System.Windows.Forms.Label labelMaximumFilterEntries; + private System.Windows.Forms.NumericUpDown upDownMaximumFilterEntries; + private System.Windows.Forms.NumericUpDown upDownMaximumFilterEntriesDisplayed; + private System.Windows.Forms.Label labelMaximumFilterEntriesDisplayed; + private System.Windows.Forms.CheckBox checkBoxAutoPick; + private System.Windows.Forms.CheckBox checkBoxPortableMode; + private System.Windows.Forms.RadioButton radioButtonSessionApplicationStartupDir; + private System.Windows.Forms.CheckBox checkBoxShowErrorMessageOnlyOneInstance; + private System.Windows.Forms.CheckBox checkBoxDarkMode; + private System.Windows.Forms.NumericUpDown upDownMaximumLineLength; + private System.Windows.Forms.Label labelMaximumLineLength; + private System.Windows.Forms.Label labelWarningMaximumLineLenght; +} diff --git a/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.cs b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.cs new file mode 100644 index 00000000..bdf5df26 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.cs @@ -0,0 +1,1042 @@ +using System.Runtime.Versioning; +using System.Text; + +using LogExpert.Core.Classes; +using LogExpert.Core.Classes.Columnizer; +using LogExpert.Core.Config; +using LogExpert.Core.Entities; +using LogExpert.Core.Enums; +using LogExpert.Core.Interface; +using LogExpert.UI.Controls.LogTabWindow; +using LogExpert.UI.Dialogs; +using LogExpert.UI.Extensions; + +namespace LogExpert.Dialogs; + +//TODO: This class should not knoow ConfigManager? +[SupportedOSPlatform("windows")] +internal partial class SettingsDialog : Form +{ + #region Fields + + private readonly Image _emptyImage = new Bitmap(16, 16); + private readonly LogTabWindow _logTabWin; + + private ILogExpertPluginConfigurator _selectedPlugin; + private ToolEntry _selectedTool; + + #endregion + + #region cTor + + private SettingsDialog (Preferences prefs, LogTabWindow logTabWin) + { + Preferences = prefs; + _logTabWin = logTabWin; //TODO: uses only HighlightGroupList. Can we pass IList instead? + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + + public SettingsDialog (Preferences prefs, LogTabWindow logTabWin, int tabToOpen, IConfigManager configManager) : this(prefs, logTabWin) + { + tabControlSettings.SelectedIndex = tabToOpen; + ConfigManager = configManager; + + } + + #endregion + + #region Properties + + public Preferences Preferences { get; private set; } + private IConfigManager ConfigManager { get; } + + #endregion + + #region Private Methods + + private void FillDialog () + { + Preferences ??= new Preferences(); + + if (Preferences.FontName == null) + { + Preferences.FontName = "Courier New"; + } + + if (Math.Abs(Preferences.FontSize) < 0.1) + { + Preferences.FontSize = 9.0f; + } + + FillPortableMode(); + + checkBoxDarkMode.Checked = Preferences.DarkMode; + checkBoxTimestamp.Checked = Preferences.TimestampControl; + checkBoxSyncFilter.Checked = Preferences.FilterSync; + checkBoxFilterTail.Checked = Preferences.FilterTail; + checkBoxFollowTail.Checked = Preferences.FollowTail; + + radioButtonHorizMouseDrag.Checked = Preferences.TimestampControlDragOrientation == DragOrientationsEnum.Horizontal; + radioButtonVerticalMouseDrag.Checked = Preferences.TimestampControlDragOrientation == DragOrientationsEnum.Vertical; + radioButtonVerticalMouseDragInverted.Checked = Preferences.TimestampControlDragOrientation == DragOrientationsEnum.InvertedVertical; + + checkBoxSingleInstance.Checked = Preferences.AllowOnlyOneInstance; + checkBoxOpenLastFiles.Checked = Preferences.OpenLastFiles; + checkBoxTailState.Checked = Preferences.ShowTailState; + checkBoxColumnSize.Checked = Preferences.SetLastColumnWidth; + cpDownColumnWidth.Enabled = Preferences.SetLastColumnWidth; + + if (Preferences.LastColumnWidth != 0) + { + if (Preferences.LastColumnWidth < cpDownColumnWidth.Minimum) + { + Preferences.LastColumnWidth = (int)cpDownColumnWidth.Minimum; + } + + if (Preferences.LastColumnWidth > cpDownColumnWidth.Maximum) + { + Preferences.LastColumnWidth = (int)cpDownColumnWidth.Maximum; + } + + cpDownColumnWidth.Value = Preferences.LastColumnWidth; + } + + checkBoxTimeSpread.Checked = Preferences.ShowTimeSpread; + checkBoxReverseAlpha.Checked = Preferences.ReverseAlpha; + + radioButtonTimeView.Checked = Preferences.TimeSpreadTimeMode; + radioButtonLineView.Checked = !Preferences.TimeSpreadTimeMode; + + checkBoxSaveSessions.Checked = Preferences.SaveSessions; + + switch (Preferences.SaveLocation) + { + case SessionSaveLocation.OwnDir: + { + radioButtonSessionSaveOwn.Checked = true; + } + break; + case SessionSaveLocation.SameDir: + { + radioButtonSessionSameDir.Checked = true; + } + break; + case SessionSaveLocation.DocumentsDir: + { + radioButtonsessionSaveDocuments.Checked = true; + break; + } + case SessionSaveLocation.ApplicationStartupDir: + { + radioButtonSessionApplicationStartupDir.Checked = true; + break; + } + } + + //overwrite preferences save location in portable mode to always be application startup directory + if (checkBoxPortableMode.Checked) + { + radioButtonSessionApplicationStartupDir.Checked = true; + } + + upDownMaximumLineLength.Value = Preferences.MaxLineLength; + + upDownMaximumFilterEntriesDisplayed.Value = Preferences.MaximumFilterEntriesDisplayed; + upDownMaximumFilterEntries.Value = Preferences.MaximumFilterEntries; + + labelSessionSaveOwnDir.Text = Preferences.SessionSaveDirectory ?? string.Empty; + checkBoxSaveFilter.Checked = Preferences.SaveFilters; + upDownBlockCount.Value = Preferences.BufferCount; + upDownLinesPerBlock.Value = Preferences.LinesPerBuffer; + upDownPollingInterval.Value = Preferences.PollingInterval; + checkBoxMultiThread.Checked = Preferences.MultiThreadFilter; + + dataGridViewColumnizer.DataError += OnDataGridViewColumnizerDataError; + + FillColumnizerList(); + FillPluginList(); + DisplayFontName(); + FillHighlightMaskList(); + FillToolListbox(); + FillMultifileSettings(); + FillEncodingList(); + + var temp = Encoding.GetEncoding(Preferences.DefaultEncoding); + + comboBoxEncoding.SelectedItem = Encoding.GetEncoding(Preferences.DefaultEncoding); + checkBoxMaskPrio.Checked = Preferences.MaskPrio; + checkBoxAutoPick.Checked = Preferences.AutoPick; + checkBoxAskCloseTabs.Checked = Preferences.AskForClose; + checkBoxColumnFinder.Checked = Preferences.ShowColumnFinder; + checkBoxLegacyReader.Checked = Preferences.UseLegacyReader; + checkBoxShowErrorMessageOnlyOneInstance.Checked = Preferences.ShowErrorMessageAllowOnlyOneInstances; + } + + private void FillPortableMode () + { + checkBoxPortableMode.CheckState = Preferences.PortableMode ? CheckState.Checked : CheckState.Unchecked; + } + + private void DisplayFontName () + { + labelFont.Text = Preferences.FontName + @" " + (int)Preferences.FontSize; + labelFont.Font = new Font(new FontFamily(Preferences.FontName), Preferences.FontSize); + } + + private void SaveMultifileData () + { + if (radioButtonLoadEveryFileIntoSeperatedTab.Checked) + { + Preferences.MultiFileOption = MultiFileOption.SingleFiles; + } + + if (radioButtonTreatAllFilesAsOneMultifile.Checked) + { + Preferences.MultiFileOption = MultiFileOption.MultiFile; + } + + if (radioButtonAskWhatToDo.Checked) + { + Preferences.MultiFileOption = MultiFileOption.Ask; + } + + Preferences.MultiFileOptions.FormatPattern = textBoxMultifilePattern.Text; + Preferences.MultiFileOptions.MaxDayTry = (int)upDownMultifileDays.Value; + } + + private void OnBtnToolClickInternal (TextBox textBox) + { + OpenFileDialog dlg = new(); + dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + + if (string.IsNullOrEmpty(textBox.Text) == false) + { + FileInfo info = new(textBox.Text); + if (info.Directory != null && info.Directory.Exists) + { + dlg.InitialDirectory = info.DirectoryName; + } + } + + if (dlg.ShowDialog() == DialogResult.OK) + { + textBox.Text = dlg.FileName; + } + } + + //TODO: what is the purpose of this method? + private void OnBtnArgsClickInternal (TextBox textBox) + { + ToolArgsDialog dlg = new(_logTabWin, this) + { + Arg = textBox.Text + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + textBox.Text = dlg.Arg; + } + } + + private void OnBtnWorkingDirClick (TextBox textBox) + { + FolderBrowserDialog dlg = new() + { + RootFolder = Environment.SpecialFolder.MyComputer, + Description = @"Select a working directory" + }; + + if (!string.IsNullOrEmpty(textBox.Text)) + { + DirectoryInfo info = new(textBox.Text); + if (info.Exists) + { + dlg.SelectedPath = info.FullName; + } + } + + if (dlg.ShowDialog() == DialogResult.OK) + { + textBox.Text = dlg.SelectedPath; + } + } + + private void FillColumnizerForToolsList () + { + if (_selectedTool != null) + { + FillColumnizerForToolsList(comboBoxColumnizer, _selectedTool.ColumnizerName); + } + } + + private void FillColumnizerForToolsList (ComboBox comboBox, string columnizerName) + { + var selIndex = 0; + comboBox.Items.Clear(); + IList columnizers = PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers; + + foreach (ILogLineColumnizer columnizer in columnizers) + { + var index = comboBox.Items.Add(columnizer.GetName()); + if (columnizer.GetName().Equals(columnizerName, StringComparison.Ordinal)) + { + selIndex = index; + } + } + + //ILogLineColumnizer columnizer = Util.FindColumnizerByName(columnizerName, this.logTabWin.RegisteredColumnizers); + //if (columnizer == null) + // columnizer = this.logTabWin.RegisteredColumnizers[0]; + comboBox.SelectedIndex = selIndex; + } + + private void FillColumnizerList () + { + dataGridViewColumnizer.Rows.Clear(); + + var comboColumn = (DataGridViewComboBoxColumn)dataGridViewColumnizer.Columns[1]; + comboColumn.Items.Clear(); + + var textColumn = (DataGridViewTextBoxColumn)dataGridViewColumnizer.Columns[0]; + + IList columnizers = PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers; + + foreach (ILogLineColumnizer columnizer in columnizers) + { + comboColumn.Items.Add(columnizer.GetName()); + } + //comboColumn.DisplayMember = "Name"; + //comboColumn.ValueMember = "Columnizer"; + + foreach (ColumnizerMaskEntry maskEntry in Preferences.ColumnizerMaskList) + { + DataGridViewRow row = new(); + row.Cells.Add(new DataGridViewTextBoxCell()); + DataGridViewComboBoxCell cell = new(); + + foreach (ILogLineColumnizer logColumnizer in columnizers) + { + cell.Items.Add(logColumnizer.GetName()); + } + + row.Cells.Add(cell); + row.Cells[0].Value = maskEntry.Mask; + ILogLineColumnizer columnizer = ColumnizerPicker.DecideColumnizerByName(maskEntry.ColumnizerName, + PluginRegistry.PluginRegistry.Instance.RegisteredColumnizers); + + row.Cells[1].Value = columnizer.GetName(); + dataGridViewColumnizer.Rows.Add(row); + } + + var count = dataGridViewColumnizer.RowCount; + + if (count > 0 && !dataGridViewColumnizer.Rows[count - 1].IsNewRow) + { + var comboCell = (DataGridViewComboBoxCell)dataGridViewColumnizer.Rows[count - 1].Cells[1]; + comboCell.Value = comboCell.Items[0]; + } + } + + private void FillHighlightMaskList () + { + dataGridViewHighlightMask.Rows.Clear(); + + var comboColumn = (DataGridViewComboBoxColumn)dataGridViewHighlightMask.Columns[1]; + comboColumn.Items.Clear(); + + //TODO Remove if not necessary + var textColumn = (DataGridViewTextBoxColumn)dataGridViewHighlightMask.Columns[0]; + + foreach (HighlightGroup group in (IList)_logTabWin.HighlightGroupList) + { + comboColumn.Items.Add(group.GroupName); + } + + foreach (HighlightMaskEntry maskEntry in Preferences.HighlightMaskList) + { + DataGridViewRow row = new(); + row.Cells.Add(new DataGridViewTextBoxCell()); + DataGridViewComboBoxCell cell = new(); + + foreach (HighlightGroup group in (IList)_logTabWin.HighlightGroupList) + { + cell.Items.Add(group.GroupName); + } + + row.Cells.Add(cell); + row.Cells[0].Value = maskEntry.Mask; + + HighlightGroup currentGroup = _logTabWin.FindHighlightGroup(maskEntry.HighlightGroupName); + var highlightGroupList = _logTabWin.HighlightGroupList; + currentGroup ??= highlightGroupList.Count > 0 ? highlightGroupList[0] : new HighlightGroup(); + + row.Cells[1].Value = currentGroup.GroupName; + dataGridViewHighlightMask.Rows.Add(row); + } + + var count = dataGridViewHighlightMask.RowCount; + + if (count > 0 && !dataGridViewHighlightMask.Rows[count - 1].IsNewRow) + { + var comboCell = + (DataGridViewComboBoxCell)dataGridViewHighlightMask.Rows[count - 1].Cells[1]; + comboCell.Value = comboCell.Items[0]; + } + } + + private void SaveColumnizerList () + { + Preferences.ColumnizerMaskList.Clear(); + + foreach (DataGridViewRow row in dataGridViewColumnizer.Rows) + { + if (!row.IsNewRow) + { + ColumnizerMaskEntry entry = new(); + entry.Mask = (string)row.Cells[0].Value; + entry.ColumnizerName = (string)row.Cells[1].Value; + Preferences.ColumnizerMaskList.Add(entry); + } + } + } + + private void SaveHighlightMaskList () + { + Preferences.HighlightMaskList.Clear(); + + foreach (DataGridViewRow row in dataGridViewHighlightMask.Rows) + { + if (!row.IsNewRow) + { + HighlightMaskEntry entry = new(); + entry.Mask = (string)row.Cells[0].Value; + entry.HighlightGroupName = (string)row.Cells[1].Value; + Preferences.HighlightMaskList.Add(entry); + } + } + } + + private void FillPluginList () + { + listBoxPlugin.Items.Clear(); + + foreach (IContextMenuEntry entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) + { + listBoxPlugin.Items.Add(entry); + if (entry is ILogExpertPluginConfigurator configurator) + { + configurator.StartConfig(); + } + } + + foreach (IKeywordAction entry in PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions) + { + listBoxPlugin.Items.Add(entry); + if (entry is ILogExpertPluginConfigurator configurator) + { + configurator.StartConfig(); + } + } + + foreach (IFileSystemPlugin entry in PluginRegistry.PluginRegistry.Instance.RegisteredFileSystemPlugins) + { + listBoxPlugin.Items.Add(entry); + if (entry is ILogExpertPluginConfigurator configurator) + { + configurator.StartConfig(); + } + } + + buttonConfigPlugin.Enabled = false; + } + + private void SavePluginSettings () + { + _selectedPlugin?.HideConfigForm(); + + foreach (IContextMenuEntry entry in PluginRegistry.PluginRegistry.Instance.RegisteredContextMenuPlugins) + { + if (entry is ILogExpertPluginConfigurator configurator) + { + configurator.SaveConfig(checkBoxPortableMode.Checked ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir); + } + } + + foreach (IKeywordAction entry in PluginRegistry.PluginRegistry.Instance.RegisteredKeywordActions) + { + if (entry is ILogExpertPluginConfigurator configurator) + { + configurator.SaveConfig(checkBoxPortableMode.Checked ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir); + } + } + } + + private void FillToolListbox () + { + listBoxTools.Items.Clear(); + + foreach (ToolEntry tool in Preferences.ToolEntries) + { + listBoxTools.Items.Add(tool.Clone(), tool.IsFavourite); + } + + if (listBoxTools.Items.Count > 0) + { + listBoxTools.SelectedIndex = 0; + } + } + + private void FillMultifileSettings () + { + switch (Preferences.MultiFileOption) + { + case MultiFileOption.SingleFiles: + { + radioButtonLoadEveryFileIntoSeperatedTab.Checked = true; + break; + } + case MultiFileOption.MultiFile: + { + radioButtonTreatAllFilesAsOneMultifile.Checked = true; + break; + } + case MultiFileOption.Ask: + { + radioButtonAskWhatToDo.Checked = true; + break; + } + } + + textBoxMultifilePattern.Text = Preferences.MultiFileOptions.FormatPattern; //TODO: Impport settings file throws an exception. Fix or I caused it? + upDownMultifileDays.Value = Preferences.MultiFileOptions.MaxDayTry; + } + + private void GetToolListBoxData () + { + GetCurrentToolValues(); + Preferences.ToolEntries.Clear(); + + for (var i = 0; i < listBoxTools.Items.Count; ++i) + { + Preferences.ToolEntries.Add(listBoxTools.Items[i] as ToolEntry); + (listBoxTools.Items[i] as ToolEntry).IsFavourite = listBoxTools.GetItemChecked(i); + } + } + + private void GetCurrentToolValues () + { + if (_selectedTool != null) + { + _selectedTool.Name = Util.IsNullOrSpaces(textBoxToolName.Text) ? textBoxTool.Text : textBoxToolName.Text; + _selectedTool.Cmd = textBoxTool.Text; + _selectedTool.Args = textBoxArguments.Text; + _selectedTool.ColumnizerName = comboBoxColumnizer.Text; + _selectedTool.Sysout = checkBoxSysout.Checked; + _selectedTool.WorkingDir = textBoxWorkingDir.Text; + } + } + + private void ShowCurrentToolValues () + { + if (_selectedTool != null) + { + textBoxToolName.Text = _selectedTool.Name; + textBoxTool.Text = _selectedTool.Cmd; + textBoxArguments.Text = _selectedTool.Args; + comboBoxColumnizer.Text = _selectedTool.ColumnizerName; + checkBoxSysout.Checked = _selectedTool.Sysout; + comboBoxColumnizer.Enabled = _selectedTool.Sysout; + textBoxWorkingDir.Text = _selectedTool.WorkingDir; + } + } + + private void DisplayCurrentIcon () + { + if (_selectedTool != null) + { + Icon icon = NativeMethods.LoadIconFromExe(_selectedTool.IconFile, _selectedTool.IconIndex); + if (icon != null) + { + Image image = icon.ToBitmap(); + buttonIcon.Image = image; + NativeMethods.DestroyIcon(icon.Handle); + icon.Dispose(); + } + else + { + buttonIcon.Image = _emptyImage; + } + } + } + + private void FillEncodingList () + { + comboBoxEncoding.Items.Clear(); + + comboBoxEncoding.Items.Add(Encoding.ASCII); + comboBoxEncoding.Items.Add(Encoding.Default); + comboBoxEncoding.Items.Add(Encoding.GetEncoding("iso-8859-1")); + comboBoxEncoding.Items.Add(Encoding.UTF8); + comboBoxEncoding.Items.Add(Encoding.Unicode); + comboBoxEncoding.Items.Add(CodePagesEncodingProvider.Instance.GetEncoding(1252)); + + comboBoxEncoding.ValueMember = "HeaderName"; + } + + #endregion + + #region Events handler + + private void OnSettingsDialogLoad (object sender, EventArgs e) + { + FillDialog(); + } + + private void OnBtnChangeFontClick (object sender, EventArgs e) + { + FontDialog dlg = new() + { + ShowEffects = false, + AllowVerticalFonts = false, + AllowScriptChange = false, + Font = new Font(new FontFamily(Preferences.FontName), Preferences.FontSize) + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + Preferences.FontSize = dlg.Font.Size; + Preferences.FontName = dlg.Font.FontFamily.Name; + } + + DisplayFontName(); + } + + private void OnBtnOkClick (object sender, EventArgs e) + { + Preferences.TimestampControl = checkBoxTimestamp.Checked; + Preferences.FilterSync = checkBoxSyncFilter.Checked; + Preferences.FilterTail = checkBoxFilterTail.Checked; + Preferences.FollowTail = checkBoxFollowTail.Checked; + + if (radioButtonVerticalMouseDrag.Checked) + { + Preferences.TimestampControlDragOrientation = DragOrientationsEnum.Vertical; + } + else if (radioButtonVerticalMouseDragInverted.Checked) + { + Preferences.TimestampControlDragOrientation = DragOrientationsEnum.InvertedVertical; + } + else + { + Preferences.TimestampControlDragOrientation = DragOrientationsEnum.Horizontal; + } + + SaveColumnizerList(); + + Preferences.MaskPrio = checkBoxMaskPrio.Checked; + Preferences.AutoPick = checkBoxAutoPick.Checked; + Preferences.AskForClose = checkBoxAskCloseTabs.Checked; + Preferences.AllowOnlyOneInstance = checkBoxSingleInstance.Checked; + Preferences.OpenLastFiles = checkBoxOpenLastFiles.Checked; + Preferences.ShowTailState = checkBoxTailState.Checked; + Preferences.SetLastColumnWidth = checkBoxColumnSize.Checked; + Preferences.LastColumnWidth = (int)cpDownColumnWidth.Value; + Preferences.ShowTimeSpread = checkBoxTimeSpread.Checked; + Preferences.ReverseAlpha = checkBoxReverseAlpha.Checked; + Preferences.TimeSpreadTimeMode = radioButtonTimeView.Checked; + + Preferences.SaveSessions = checkBoxSaveSessions.Checked; + Preferences.SessionSaveDirectory = labelSessionSaveOwnDir.Text; + + if (radioButtonsessionSaveDocuments.Checked) + { + Preferences.SaveLocation = SessionSaveLocation.DocumentsDir; + } + else if (radioButtonSessionSaveOwn.Checked) + { + Preferences.SaveLocation = SessionSaveLocation.OwnDir; + } + else if (radioButtonSessionApplicationStartupDir.Checked) + { + Preferences.SaveLocation = SessionSaveLocation.ApplicationStartupDir; + } + else + { + Preferences.SaveLocation = SessionSaveLocation.SameDir; + } + + Preferences.SaveFilters = checkBoxSaveFilter.Checked; + Preferences.BufferCount = (int)upDownBlockCount.Value; + Preferences.LinesPerBuffer = (int)upDownLinesPerBlock.Value; + Preferences.PollingInterval = (int)upDownPollingInterval.Value; + Preferences.MultiThreadFilter = checkBoxMultiThread.Checked; + Preferences.DefaultEncoding = comboBoxEncoding.SelectedItem != null ? (comboBoxEncoding.SelectedItem as Encoding).HeaderName : Encoding.Default.HeaderName; + Preferences.ShowColumnFinder = checkBoxColumnFinder.Checked; + Preferences.UseLegacyReader = checkBoxLegacyReader.Checked; + + Preferences.MaximumFilterEntries = (int)upDownMaximumFilterEntries.Value; + Preferences.MaximumFilterEntriesDisplayed = (int)upDownMaximumFilterEntriesDisplayed.Value; + Preferences.ShowErrorMessageAllowOnlyOneInstances = checkBoxShowErrorMessageOnlyOneInstance.Checked; + Preferences.DarkMode = checkBoxDarkMode.Checked; + + SavePluginSettings(); + SaveHighlightMaskList(); + GetToolListBoxData(); + SaveMultifileData(); + } + + private void OnBtnToolClick (object sender, EventArgs e) + { + OnBtnToolClickInternal(textBoxTool); + } + + //TODO: what is the purpose of this click? + private void OnBtnArgClick (object sender, EventArgs e) + { + OnBtnArgsClickInternal(textBoxArguments); + } + + //TODO Remove or refactor this function + private void OnDataGridViewColumnizerRowsAdded (object sender, DataGridViewRowsAddedEventArgs e) + { + var comboCell = (DataGridViewComboBoxCell)dataGridViewColumnizer.Rows[e.RowIndex].Cells[1]; + if (comboCell.Items.Count > 0) + { + // comboCell.Value = comboCell.Items[0]; + } + } + + private void OnBtnDeleteClick (object sender, EventArgs e) + { + if (dataGridViewColumnizer.CurrentRow != null && !dataGridViewColumnizer.CurrentRow.IsNewRow) + { + var index = dataGridViewColumnizer.CurrentRow.Index; + dataGridViewColumnizer.EndEdit(); + dataGridViewColumnizer.Rows.RemoveAt(index); + } + } + + private void OnDataGridViewColumnizerDataError (object sender, DataGridViewDataErrorEventArgs e) + { + e.Cancel = true; + } + + private void OnChkBoxSysoutCheckedChanged (object sender, EventArgs e) + { + comboBoxColumnizer.Enabled = checkBoxSysout.Checked; + } + + private void OnBtnTailColorClick (object sender, EventArgs e) + { + ColorDialog dlg = new() + { + Color = Preferences.ShowTailColor + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + Preferences.ShowTailColor = dlg.Color; + } + } + + private void OnChkBoxColumnSizeCheckedChanged (object sender, EventArgs e) + { + cpDownColumnWidth.Enabled = checkBoxColumnSize.Checked; + } + + private void OnBtnTimespreadColorClick (object sender, EventArgs e) + { + ColorDialog dlg = new() + { + Color = Preferences.TimeSpreadColor + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + Preferences.TimeSpreadColor = dlg.Color; + } + } + + private void OnListBoxPluginSelectedIndexChanged (object sender, EventArgs e) + { + _selectedPlugin?.HideConfigForm(); + + var o = listBoxPlugin.SelectedItem; + + if (o != null) + { + _selectedPlugin = o as ILogExpertPluginConfigurator; + + if (o is ILogExpertPluginConfigurator) + { + if (_selectedPlugin.HasEmbeddedForm()) + { + buttonConfigPlugin.Enabled = false; + buttonConfigPlugin.Visible = false; + _selectedPlugin.ShowConfigForm(panelPlugin); + } + else + { + buttonConfigPlugin.Enabled = true; + buttonConfigPlugin.Visible = true; + } + } + } + else + { + buttonConfigPlugin.Enabled = false; + buttonConfigPlugin.Visible = true; + } + } + + private void OnBtnSessionSaveDirClick (object sender, EventArgs e) + { + FolderBrowserDialog dlg = new(); + + if (Preferences.SessionSaveDirectory != null) + { + dlg.SelectedPath = Preferences.SessionSaveDirectory; + } + + dlg.ShowNewFolderButton = true; + dlg.Description = @"Choose folder for LogExpert's session files"; + + if (dlg.ShowDialog() == DialogResult.OK) + { + labelSessionSaveOwnDir.Text = dlg.SelectedPath; + } + } + + private void OnPortableModeCheckedChanged (object sender, EventArgs e) + { + try + { + switch (checkBoxPortableMode.CheckState) + { + case CheckState.Checked when !File.Exists(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName): + { + if (Directory.Exists(ConfigManager.PortableModeDir) == false) + { + Directory.CreateDirectory(ConfigManager.PortableModeDir); + } + + using (File.Create(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName)) + { + break; + } + } + case CheckState.Unchecked when File.Exists(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName): + { + File.Delete(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName); + break; + } + } + + switch (checkBoxPortableMode.CheckState) + { + case CheckState.Unchecked: + { + checkBoxPortableMode.Text = @"Activate Portable Mode"; + Preferences.PortableMode = false; + break; + } + + case CheckState.Checked: + { + Preferences.PortableMode = true; + checkBoxPortableMode.Text = @"Deactivate Portable Mode"; + break; + } + } + } + catch (Exception exception) + { + MessageBox.Show($@"Could not create / delete marker for Portable Mode: {exception}", @"Error", MessageBoxButtons.OK); + } + + } + + private void OnBtnConfigPluginClick (object sender, EventArgs e) + { + if (!_selectedPlugin.HasEmbeddedForm()) + { + _selectedPlugin.ShowConfigDialog(this); + } + } + + private void OnNumericUpDown1ValueChanged (object sender, EventArgs e) + { + //TODO implement + } + + private void OnListBoxToolSelectedIndexChanged (object sender, EventArgs e) + { + GetCurrentToolValues(); + _selectedTool = listBoxTools.SelectedItem as ToolEntry; + ShowCurrentToolValues(); + listBoxTools.Refresh(); + FillColumnizerForToolsList(); + DisplayCurrentIcon(); + } + + private void OnBtnToolUpClick (object sender, EventArgs e) + { + var i = listBoxTools.SelectedIndex; + + if (i > 0) + { + var isChecked = listBoxTools.GetItemChecked(i); + var item = listBoxTools.Items[i]; + listBoxTools.Items.RemoveAt(i); + i--; + listBoxTools.Items.Insert(i, item); + listBoxTools.SelectedIndex = i; + listBoxTools.SetItemChecked(i, isChecked); + } + } + + private void OnBtnToolDownClick (object sender, EventArgs e) + { + var i = listBoxTools.SelectedIndex; + + if (i < listBoxTools.Items.Count - 1) + { + var isChecked = listBoxTools.GetItemChecked(i); + var item = listBoxTools.Items[i]; + listBoxTools.Items.RemoveAt(i); + i++; + listBoxTools.Items.Insert(i, item); + listBoxTools.SelectedIndex = i; + listBoxTools.SetItemChecked(i, isChecked); + } + } + + [SupportedOSPlatform("windows")] + private void OnBtnToolAddClick (object sender, EventArgs e) + { + listBoxTools.Items.Add(new ToolEntry()); + listBoxTools.SelectedIndex = listBoxTools.Items.Count - 1; + } + + [SupportedOSPlatform("windows")] + private void OnToolDeleteButtonClick (object sender, EventArgs e) + { + var i = listBoxTools.SelectedIndex; + + if (i < listBoxTools.Items.Count && i >= 0) + { + listBoxTools.Items.RemoveAt(i); + if (i < listBoxTools.Items.Count) + { + listBoxTools.SelectedIndex = i; + } + else + { + if (listBoxTools.Items.Count > 0) + { + listBoxTools.SelectedIndex = listBoxTools.Items.Count - 1; + } + } + } + } + + [SupportedOSPlatform("windows")] + private void OnBtnIconClick (object sender, EventArgs e) + { + if (_selectedTool != null) + { + var iconFile = _selectedTool.IconFile; + + if (Util.IsNullOrSpaces(iconFile)) + { + iconFile = textBoxTool.Text; + } + + ChooseIconDlg dlg = new(iconFile); + + if (dlg.ShowDialog() == DialogResult.OK) + { + _selectedTool.IconFile = dlg.FileName; + _selectedTool.IconIndex = dlg.IconIndex; + DisplayCurrentIcon(); + } + } + } + + private void OnBtnCancelClick (object sender, EventArgs e) + { + _selectedPlugin?.HideConfigForm(); + } + + private void OnBtnWorkingDirClick (object sender, EventArgs e) + { + OnBtnWorkingDirClick(textBoxWorkingDir); + } + + [SupportedOSPlatform("windows")] + private void OnMultiFilePatternTextChanged (object sender, EventArgs e) + { + var pattern = textBoxMultifilePattern.Text; + upDownMultifileDays.Enabled = pattern.Contains("$D", System.StringComparison.Ordinal); + } + + [SupportedOSPlatform("windows")] + private void OnBtnExportClick (object sender, EventArgs e) + { + SaveFileDialog dlg = new() + { + Title = @"Export Settings to file", + DefaultExt = "json", + AddExtension = true, + Filter = @"Settings (*.json)|*.json|All files (*.*)|*.*" + }; + + DialogResult result = dlg.ShowDialog(); + + if (result == DialogResult.OK) + { + FileInfo fileInfo = new(dlg.FileName); + ConfigManager.Export(fileInfo); + } + } + + /// + /// + /// + /// + /// + private void OnBtnImportClick (object sender, EventArgs e) + { + ImportSettingsDialog dlg = new(ExportImportFlags.All); + + if (dlg.ShowDialog() == DialogResult.OK) + { + if (string.IsNullOrWhiteSpace(dlg.FileName)) + { + return; + } + + FileInfo fileInfo; + try + { + fileInfo = new FileInfo(dlg.FileName); + } + catch (Exception ex) + { + MessageBox.Show(this, $@"Settings could not be imported: {ex}", @"LogExpert"); + return; + } + + ConfigManager.Import(fileInfo, dlg.ImportFlags); + Preferences = ConfigManager.Settings.Preferences; + FillDialog(); + MessageBox.Show(this, @"Settings imported", @"LogExpert"); + } + } + + #endregion +} diff --git a/src/LogExpert/Dialogs/SettingsDialog.resx b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.resx similarity index 85% rename from src/LogExpert/Dialogs/SettingsDialog.resx rename to src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.resx index 2c2d8d82..7f3f0ea5 100644 --- a/src/LogExpert/Dialogs/SettingsDialog.resx +++ b/src/LogExpert.UI/Dialogs/LogTabWindow/SettingsDialog.resx @@ -1,152 +1,173 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - 144, 17 - - - True - - - True - - - True - - - True - - - 17, 17 - - - Note: You can always load your logfiles as MultiFile automatically if the files names follow the MultiFile naming rule (<filename>, <filename>.1, <filename>.2, ...). Simply choose 'MultiFile' from the File menu after loading the first file. - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 144, 17 + + + 144, 17 + + + 144, 17 + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + True + + + 17, 17 + + + Note: You can always load your logfiles as MultiFile automatically if the files names follow the MultiFile naming rule (<filename>, <filename>.1, <filename>.2, ...). Simply choose 'MultiFile' from the File menu after loading the first file. + + + 17, 17 + + + + + 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/Dialogs/MultiFileMaskDialog.Designer.cs b/src/LogExpert.UI/Dialogs/MultiFileMaskDialog.Designer.cs new file mode 100644 index 00000000..d57d7e64 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/MultiFileMaskDialog.Designer.cs @@ -0,0 +1,191 @@ +namespace LogExpert.UI.Dialogs; + + partial class MultiFileMaskDialog + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MultiFileMaskDialog)); + this.labelMultiSettingsFor = new System.Windows.Forms.Label(); + this.labelFileName = new System.Windows.Forms.Label(); + this.labelFileNamePattern = new System.Windows.Forms.Label(); + this.upDownMaxDays = new System.Windows.Forms.NumericUpDown(); + this.fileNamePatternTextBox = new System.Windows.Forms.TextBox(); + this.labelMaxDays = new System.Windows.Forms.Label(); + this.Settings = new System.Windows.Forms.GroupBox(); + this.syntaxHelpLabel = new System.Windows.Forms.Label(); + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + ((System.ComponentModel.ISupportInitialize)(this.upDownMaxDays)).BeginInit(); + this.Settings.SuspendLayout(); + this.SuspendLayout(); + // + // labelMultiSettingsFor + // + this.labelMultiSettingsFor.AutoSize = true; + this.labelMultiSettingsFor.Location = new System.Drawing.Point(12, 13); + this.labelMultiSettingsFor.Name = "labelMultiSettingsFor"; + this.labelMultiSettingsFor.Size = new System.Drawing.Size(154, 20); + this.labelMultiSettingsFor.TabIndex = 0; + this.labelMultiSettingsFor.Text = "MultiFile settings for:"; + // + // labelFileName + // + this.labelFileName.AutoSize = true; + this.labelFileName.Location = new System.Drawing.Point(172, 13); + this.labelFileName.Name = "labelFileName"; + this.labelFileName.Size = new System.Drawing.Size(91, 20); + this.labelFileName.TabIndex = 1; + this.labelFileName.Text = ""; + // + // labelFileNamePattern + // + this.labelFileNamePattern.AutoSize = true; + this.labelFileNamePattern.Location = new System.Drawing.Point(6, 28); + this.labelFileNamePattern.Name = "labelFileNamePattern"; + this.labelFileNamePattern.Size = new System.Drawing.Size(137, 20); + this.labelFileNamePattern.TabIndex = 2; + this.labelFileNamePattern.Text = "File name pattern:"; + // + // upDownMaxDays + // + this.upDownMaxDays.Location = new System.Drawing.Point(91, 55); + this.upDownMaxDays.Maximum = new decimal(new int[] { + 40, + 0, + 0, + 0}); + this.upDownMaxDays.Name = "upDownMaxDays"; + this.upDownMaxDays.Size = new System.Drawing.Size(49, 26); + this.upDownMaxDays.TabIndex = 3; + this.upDownMaxDays.Value = new decimal(new int[] { + 1, + 0, + 0, + 0}); + // + // fileNamePatternTextBox + // + this.fileNamePatternTextBox.Location = new System.Drawing.Point(149, 25); + this.fileNamePatternTextBox.Name = "fileNamePatternTextBox"; + this.fileNamePatternTextBox.Size = new System.Drawing.Size(247, 26); + this.fileNamePatternTextBox.TabIndex = 4; + // + // labelMaxDays + // + this.labelMaxDays.AutoSize = true; + this.labelMaxDays.Location = new System.Drawing.Point(6, 57); + this.labelMaxDays.Name = "labelMaxDays"; + this.labelMaxDays.Size = new System.Drawing.Size(79, 20); + this.labelMaxDays.TabIndex = 5; + this.labelMaxDays.Text = "Max days:"; + // + // Settings + // + this.Settings.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.Settings.Controls.Add(this.labelFileNamePattern); + this.Settings.Controls.Add(this.labelMaxDays); + this.Settings.Controls.Add(this.upDownMaxDays); + this.Settings.Controls.Add(this.fileNamePatternTextBox); + this.Settings.Location = new System.Drawing.Point(15, 39); + this.Settings.Name = "Settings"; + this.Settings.Size = new System.Drawing.Size(402, 98); + this.Settings.TabIndex = 6; + this.Settings.TabStop = false; + // + // syntaxHelpLabel + // + this.syntaxHelpLabel.Location = new System.Drawing.Point(15, 140); + this.syntaxHelpLabel.Name = "syntaxHelpLabel"; + this.syntaxHelpLabel.Size = new System.Drawing.Size(402, 194); + this.syntaxHelpLabel.TabIndex = 7; + this.syntaxHelpLabel.Text = "Syntax Help Label"; + // + // buttonOk + // + this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(261, 347); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 8; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnButtonOKClick); + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(342, 347); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 9; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // MultiFileMaskDialog + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(434, 386); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.syntaxHelpLabel); + this.Controls.Add(this.Settings); + this.Controls.Add(this.labelFileName); + this.Controls.Add(this.labelMultiSettingsFor); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.MinimumSize = new System.Drawing.Size(329, 420); + this.Name = "MultiFileMaskDialog"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "MultiFile settings"; + this.TopMost = true; + this.Load += new System.EventHandler(this.OnMultiFileMaskDialogLoad); + ((System.ComponentModel.ISupportInitialize)(this.upDownMaxDays)).EndInit(); + this.Settings.ResumeLayout(false); + this.Settings.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Label labelMultiSettingsFor; + private System.Windows.Forms.Label labelFileName; + private System.Windows.Forms.Label labelFileNamePattern; + private System.Windows.Forms.NumericUpDown upDownMaxDays; + private System.Windows.Forms.TextBox fileNamePatternTextBox; + private System.Windows.Forms.Label labelMaxDays; + private System.Windows.Forms.GroupBox Settings; + private System.Windows.Forms.Label syntaxHelpLabel; + private System.Windows.Forms.Button buttonOk; + private System.Windows.Forms.Button buttonCancel; + } \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/MultiFileMaskDialog.cs b/src/LogExpert.UI/Dialogs/MultiFileMaskDialog.cs new file mode 100644 index 00000000..6bbf4b12 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/MultiFileMaskDialog.cs @@ -0,0 +1,62 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class MultiFileMaskDialog : Form +{ + #region Fields + + #endregion + + #region cTor + + public MultiFileMaskDialog(Form parent, string fileName) + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + syntaxHelpLabel.Text = "" + + "Pattern syntax:\n\n" + + "* = any characters (wildcard)\n" + + "$D() = Date pattern\n" + + "$I = File index number\n" + + "$J = File index number, hidden when zero\n" + + "$J() = Like $J, but adding when non-zero\n" + + "\n" + + ":\n" + + "DD = day\n" + + "MM = month\n" + + "YY[YY] = year\n" + + "all other chars will be used as given"; + labelFileName.Text = fileName; + } + + #endregion + + #region Properties + + public string FileNamePattern { get; set; } + + public int MaxDays { get; set; } + + #endregion + + #region Events handler + + private void OnButtonOKClick(object sender, EventArgs e) + { + FileNamePattern = fileNamePatternTextBox.Text; + MaxDays = (int)upDownMaxDays.Value; + } + + private void OnMultiFileMaskDialogLoad(object sender, EventArgs e) + { + fileNamePatternTextBox.Text = FileNamePattern; + upDownMaxDays.Value = MaxDays; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/MultiFileMaskDialog.resx b/src/LogExpert.UI/Dialogs/MultiFileMaskDialog.resx similarity index 98% rename from src/LogExpert/Dialogs/MultiFileMaskDialog.resx rename to src/LogExpert.UI/Dialogs/MultiFileMaskDialog.resx index 2de0ae4d..a43dafee 100644 --- a/src/LogExpert/Dialogs/MultiFileMaskDialog.resx +++ b/src/LogExpert.UI/Dialogs/MultiFileMaskDialog.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + 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/Dialogs/MultiLoadRequestDialog.Designer.cs b/src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.Designer.cs new file mode 100644 index 00000000..ecc9ddf4 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.Designer.cs @@ -0,0 +1,88 @@ +namespace LogExpert.UI.Dialogs; + +partial class MultiLoadRequestDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.buttonSingleMode = new System.Windows.Forms.Button(); + this.buttonMultiMode = new System.Windows.Forms.Button(); + this.labelChooseLoadingMode = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // buttonSingleMode + // + this.buttonSingleMode.DialogResult = System.Windows.Forms.DialogResult.Yes; + this.buttonSingleMode.Location = new System.Drawing.Point(12, 59); + this.buttonSingleMode.Name = "buttonSingleMode"; + this.buttonSingleMode.Size = new System.Drawing.Size(75, 23); + this.buttonSingleMode.TabIndex = 1; + this.buttonSingleMode.Text = "Single files"; + this.buttonSingleMode.UseVisualStyleBackColor = true; + // + // buttonMultiMode + // + this.buttonMultiMode.DialogResult = System.Windows.Forms.DialogResult.No; + this.buttonMultiMode.Location = new System.Drawing.Point(114, 59); + this.buttonMultiMode.Name = "buttonMultiMode"; + this.buttonMultiMode.Size = new System.Drawing.Size(75, 23); + this.buttonMultiMode.TabIndex = 2; + this.buttonMultiMode.Text = "Multi file"; + this.buttonMultiMode.UseVisualStyleBackColor = true; + // + // labelChooseLoadingMode + // + this.labelChooseLoadingMode.AutoSize = true; + this.labelChooseLoadingMode.Location = new System.Drawing.Point(48, 18); + this.labelChooseLoadingMode.Name = "labelChooseLoadingMode"; + this.labelChooseLoadingMode.Size = new System.Drawing.Size(167, 20); + this.labelChooseLoadingMode.TabIndex = 4; + this.labelChooseLoadingMode.Text = "Choose loading mode:"; + // + // MultiLoadRequestDialog + // + this.ClientSize = new System.Drawing.Size(237, 103); + this.Controls.Add(this.labelChooseLoadingMode); + this.Controls.Add(this.buttonMultiMode); + this.Controls.Add(this.buttonSingleMode); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "MultiLoadRequestDialog"; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Loading multiple files"; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Button buttonSingleMode; +private System.Windows.Forms.Button buttonMultiMode; +private System.Windows.Forms.Label labelChooseLoadingMode; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.cs b/src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.cs new file mode 100644 index 00000000..0e311a0e --- /dev/null +++ b/src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.cs @@ -0,0 +1,19 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class MultiLoadRequestDialog : Form +{ + #region cTor + + public MultiLoadRequestDialog() + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/MultiLoadRequestDialog.resx b/src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/MultiLoadRequestDialog.resx rename to src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.resx index c7e0d4bd..d58980a3 100644 --- a/src/LogExpert/Dialogs/MultiLoadRequestDialog.resx +++ b/src/LogExpert.UI/Dialogs/MultiLoadRequestDialog.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Dialogs/OpenUriDialog.Designer.cs b/src/LogExpert.UI/Dialogs/OpenUriDialog.Designer.cs new file mode 100644 index 00000000..0f54eb31 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/OpenUriDialog.Designer.cs @@ -0,0 +1,121 @@ +namespace LogExpert.UI.Dialogs; + +partial class OpenUriDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OpenUriDialog)); + this.cmbUri = new System.Windows.Forms.ComboBox(); + this.label1 = new System.Windows.Forms.Label(); + this.okButton = new System.Windows.Forms.Button(); + this.cancelButton = new System.Windows.Forms.Button(); + this.label2 = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // uriComboBox + // + this.cmbUri.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.cmbUri.FormattingEnabled = true; + this.cmbUri.Location = new System.Drawing.Point(12, 37); + this.cmbUri.Name = "cmbUri"; + this.cmbUri.Size = new System.Drawing.Size(449, 21); + this.cmbUri.TabIndex = 0; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(12, 21); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(32, 13); + this.label1.TabIndex = 1; + this.label1.Text = "URL:"; + // + // okButton + // + this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; + this.okButton.Location = new System.Drawing.Point(305, 127); + this.okButton.Name = "okButton"; + this.okButton.Size = new System.Drawing.Size(75, 23); + this.okButton.TabIndex = 2; + this.okButton.Text = "OK"; + this.okButton.UseVisualStyleBackColor = true; + this.okButton.Click += new System.EventHandler(this.OnBtnOkClick); + // + // cancelButton + // + this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.cancelButton.Location = new System.Drawing.Point(386, 127); + this.cancelButton.Name = "cancelButton"; + this.cancelButton.Size = new System.Drawing.Size(75, 23); + this.cancelButton.TabIndex = 3; + this.cancelButton.Text = "Cancel"; + this.cancelButton.UseVisualStyleBackColor = true; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(12, 84); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(410, 13); + this.label2.TabIndex = 4; + this.label2.Text = "Enter a URL which is supported by an installed file system plugin (e.g. file:// o" + + "r sftp://)"; + // + // OpenUriDialog + // + this.AcceptButton = this.okButton; + this.CancelButton = this.cancelButton; + this.ClientSize = new System.Drawing.Size(475, 162); + this.Controls.Add(this.label2); + this.Controls.Add(this.cancelButton); + this.Controls.Add(this.okButton); + this.Controls.Add(this.label1); + this.Controls.Add(this.cmbUri); + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MaximumSize = new System.Drawing.Size(800, 260); + this.MinimizeBox = false; + this.MinimumSize = new System.Drawing.Size(491, 200); + this.Name = "OpenUriDialog"; + this.Text = "Open URL"; + this.Load += new System.EventHandler(this.OnOpenUriDialogLoad); + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.ComboBox cmbUri; +private System.Windows.Forms.Label label1; +private System.Windows.Forms.Button okButton; +private System.Windows.Forms.Button cancelButton; +private System.Windows.Forms.Label label2; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/OpenUriDialog.cs b/src/LogExpert.UI/Dialogs/OpenUriDialog.cs new file mode 100644 index 00000000..0b9f8cd7 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/OpenUriDialog.cs @@ -0,0 +1,71 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class OpenUriDialog : Form +{ + #region Fields + + #endregion + + #region cTor + + public OpenUriDialog() + { + SuspendLayout(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + InitializeComponent(); + + ResumeLayout(); + } + + #endregion + + #region Properties + + public string Uri => cmbUri.Text; + + public IList UriHistory { get; set; } + + #endregion + + #region Events handler + + private void OnOpenUriDialogLoad(object sender, EventArgs e) + { + if (UriHistory != null) + { + cmbUri.Items.Clear(); + foreach (var uri in UriHistory) + { + cmbUri.Items.Add(uri); + } + } + } + + private void OnBtnOkClick(object sender, EventArgs e) + { + UriHistory = []; + + foreach (var item in cmbUri.Items) + { + UriHistory.Add(item.ToString()); + } + + if (UriHistory.Contains(cmbUri.Text)) + { + UriHistory.Remove(cmbUri.Text); + } + UriHistory.Insert(0, cmbUri.Text); + + while (UriHistory.Count > 20) + { + UriHistory.RemoveAt(UriHistory.Count - 1); + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/OpenUriDialog.resx b/src/LogExpert.UI/Dialogs/OpenUriDialog.resx similarity index 98% rename from src/LogExpert/Dialogs/OpenUriDialog.resx rename to src/LogExpert.UI/Dialogs/OpenUriDialog.resx index 2de0ae4d..a43dafee 100644 --- a/src/LogExpert/Dialogs/OpenUriDialog.resx +++ b/src/LogExpert.UI/Dialogs/OpenUriDialog.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + 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/Dialogs/ParamRequesterDialog.Designer.cs b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.Designer.cs new file mode 100644 index 00000000..a42f5b83 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.Designer.cs @@ -0,0 +1,104 @@ +namespace LogExpert.Dialogs; + +partial class ParamRequesterDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.labelValueForParameter = new System.Windows.Forms.Label(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonOk = new System.Windows.Forms.Button(); + this.comboBoxValue = new System.Windows.Forms.ComboBox(); + this.SuspendLayout(); + // + // labelValueForParameter + // + this.labelValueForParameter.AutoSize = true; + this.labelValueForParameter.Location = new System.Drawing.Point(13, 25); + this.labelValueForParameter.Name = "labelValueForParameter"; + this.labelValueForParameter.Size = new System.Drawing.Size(154, 20); + this.labelValueForParameter.TabIndex = 0; + this.labelValueForParameter.Text = "&Value for parameter:"; + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(238, 88); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 3; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // buttonOk + // + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(148, 88); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 2; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); + // + // comboBoxValue + // + this.comboBoxValue.FormattingEnabled = true; + this.comboBoxValue.Location = new System.Drawing.Point(16, 48); + this.comboBoxValue.Name = "comboBoxValue"; + this.comboBoxValue.Size = new System.Drawing.Size(297, 28); + this.comboBoxValue.TabIndex = 1; + // + // ParamRequesterDialog + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(332, 130); + this.Controls.Add(this.comboBoxValue); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.labelValueForParameter); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ParamRequesterDialog"; + this.ShowIcon = false; + this.ShowInTaskbar = false; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Tool parameter"; + this.Shown += new System.EventHandler(this.ParamRequesterDialog_Shown); + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Label labelValueForParameter; +private System.Windows.Forms.Button buttonCancel; +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.ComboBox comboBoxValue; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/ParamRequesterDialog.cs b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.cs new file mode 100644 index 00000000..263a8a71 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.cs @@ -0,0 +1,57 @@ +using System.Runtime.Versioning; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class ParamRequesterDialog : Form +{ + #region Fields + + #endregion + + #region cTor + + public ParamRequesterDialog () + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + } + + #endregion + + #region Properties + + public string ParamName { get; set; } + + public string ParamValue { get; set; } + + public string[] Values { get; set; } + + #endregion + + #region Events handler + + private void ParamRequesterDialog_Shown (object sender, EventArgs e) + { + labelValueForParameter.Text = ParamName; + + if (Values != null) + { + foreach (var value in Values) + { + comboBoxValue.Items.Add(value); + } + + comboBoxValue.SelectedIndex = 0; + } + } + + private void OnButtonOkClick (object sender, EventArgs e) + { + ParamValue = comboBoxValue.Text; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ParamRequesterDialog.resx b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/ParamRequesterDialog.resx rename to src/LogExpert.UI/Dialogs/ParamRequesterDialog.resx index c7e0d4bd..d58980a3 100644 --- a/src/LogExpert/Dialogs/ParamRequesterDialog.resx +++ b/src/LogExpert.UI/Dialogs/ParamRequesterDialog.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Dialogs/ProjectLoadDlg.Designer.cs b/src/LogExpert.UI/Dialogs/ProjectLoadDlg.Designer.cs new file mode 100644 index 00000000..3e5677c3 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ProjectLoadDlg.Designer.cs @@ -0,0 +1,119 @@ +namespace LogExpert.Dialogs; + +partial class ProjectLoadDlg +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProjectLoadDlg)); + this.labelInformational = new System.Windows.Forms.Label(); + this.buttonCloseTabs = new System.Windows.Forms.Button(); + this.buttonNewWindow = new System.Windows.Forms.Button(); + this.buttonIgnore = new System.Windows.Forms.Button(); + this.labelChooseHowToProceed = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // labelInformational + // + this.labelInformational.Location = new System.Drawing.Point(12, 9); + this.labelInformational.Name = "labelInformational"; + this.labelInformational.Size = new System.Drawing.Size(178, 41); + this.labelInformational.TabIndex = 0; + this.labelInformational.Text = "Restoring layout requires an empty workbench. \r\n\r\n"; + // + // buttonCloseTabs + // + this.buttonCloseTabs.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonCloseTabs.Location = new System.Drawing.Point(43, 94); + this.buttonCloseTabs.Name = "buttonCloseTabs"; + this.buttonCloseTabs.Size = new System.Drawing.Size(113, 23); + this.buttonCloseTabs.TabIndex = 1; + this.buttonCloseTabs.Text = "Close existing tabs"; + this.buttonCloseTabs.UseVisualStyleBackColor = true; + this.buttonCloseTabs.Click += new System.EventHandler(this.OnButtonCloseTabsClick); + // + // buttonNewWindow + // + this.buttonNewWindow.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonNewWindow.Location = new System.Drawing.Point(43, 124); + this.buttonNewWindow.Name = "buttonNewWindow"; + this.buttonNewWindow.Size = new System.Drawing.Size(113, 23); + this.buttonNewWindow.TabIndex = 2; + this.buttonNewWindow.Text = "Open new window"; + this.buttonNewWindow.UseVisualStyleBackColor = true; + this.buttonNewWindow.Click += new System.EventHandler(this.OnButtonNewWindowClick); + // + // buttonIgnore + // + this.buttonIgnore.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonIgnore.Location = new System.Drawing.Point(43, 154); + this.buttonIgnore.Name = "buttonIgnore"; + this.buttonIgnore.Size = new System.Drawing.Size(113, 23); + this.buttonIgnore.TabIndex = 3; + this.buttonIgnore.Text = "Ignore layout data"; + this.buttonIgnore.UseVisualStyleBackColor = true; + this.buttonIgnore.Click += new System.EventHandler(this.OnButtonIgnoreClick); + // + // labelChooseHowToProceed + // + this.labelChooseHowToProceed.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) + | System.Windows.Forms.AnchorStyles.Right))); + this.labelChooseHowToProceed.AutoSize = true; + this.labelChooseHowToProceed.Location = new System.Drawing.Point(21, 66); + this.labelChooseHowToProceed.Name = "labelChooseHowToProceed"; + this.labelChooseHowToProceed.Size = new System.Drawing.Size(230, 20); + this.labelChooseHowToProceed.TabIndex = 4; + this.labelChooseHowToProceed.Text = "Please choose how to proceed:"; + // + // ProjectLoadDlg + // + this.ClientSize = new System.Drawing.Size(258, 196); + this.Controls.Add(this.labelChooseHowToProceed); + this.Controls.Add(this.buttonIgnore); + this.Controls.Add(this.buttonNewWindow); + this.Controls.Add(this.buttonCloseTabs); + this.Controls.Add(this.labelInformational); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ProjectLoadDlg"; + this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Loading Session"; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Label labelInformational; +private System.Windows.Forms.Button buttonCloseTabs; +private System.Windows.Forms.Button buttonNewWindow; +private System.Windows.Forms.Button buttonIgnore; +private System.Windows.Forms.Label labelChooseHowToProceed; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/ProjectLoadDlg.cs b/src/LogExpert.UI/Dialogs/ProjectLoadDlg.cs new file mode 100644 index 00000000..5d268884 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ProjectLoadDlg.cs @@ -0,0 +1,53 @@ +using LogExpert.Core.Enums; + +using System.Runtime.Versioning; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class ProjectLoadDlg : Form +{ + #region Fields + + #endregion + + #region cTor + + public ProjectLoadDlg() + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + } + + #endregion + + #region Properties + + public ProjectLoadDlgResult ProjectLoadResult { get; set; } = ProjectLoadDlgResult.Cancel; + + #endregion + + #region Events handler + + private void OnButtonCloseTabsClick(object sender, EventArgs e) + { + ProjectLoadResult = ProjectLoadDlgResult.CloseTabs; + Close(); + } + + private void OnButtonNewWindowClick(object sender, EventArgs e) + { + ProjectLoadResult = ProjectLoadDlgResult.NewWindow; + Close(); + } + + private void OnButtonIgnoreClick(object sender, EventArgs e) + { + ProjectLoadResult = ProjectLoadDlgResult.IgnoreLayout; + Close(); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ProjectLoadDlg.resx b/src/LogExpert.UI/Dialogs/ProjectLoadDlg.resx similarity index 98% rename from src/LogExpert/Dialogs/ProjectLoadDlg.resx rename to src/LogExpert.UI/Dialogs/ProjectLoadDlg.resx index 2de0ae4d..a43dafee 100644 --- a/src/LogExpert/Dialogs/ProjectLoadDlg.resx +++ b/src/LogExpert.UI/Dialogs/ProjectLoadDlg.resx @@ -1,131 +1,131 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - - - 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 - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + + + 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/Dialogs/RegexHelperDialog.Designer.cs b/src/LogExpert.UI/Dialogs/RegexHelperDialog.Designer.cs new file mode 100644 index 00000000..03e622b5 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/RegexHelperDialog.Designer.cs @@ -0,0 +1,194 @@ +namespace LogExpert.UI.Dialogs; + +partial class RegexHelperDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.buttonCancel = new System.Windows.Forms.Button(); + this.buttonOk = new System.Windows.Forms.Button(); + this.labelRegex = new System.Windows.Forms.Label(); + this.labelTestText = new System.Windows.Forms.Label(); + this.labelMatches = new System.Windows.Forms.Label(); + this.textBoxMatches = new System.Windows.Forms.TextBox(); + this.checkBoxCaseSensitive = new System.Windows.Forms.CheckBox(); + this.comboBoxRegex = new System.Windows.Forms.ComboBox(); + this.comboBoxTestText = new System.Windows.Forms.ComboBox(); + this.helpProvider1 = new System.Windows.Forms.HelpProvider(); + this.buttonHelp = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(365, 371); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 0; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // buttonOk + // + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(284, 371); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 1; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); + // + // labelRegex + // + this.labelRegex.AutoSize = true; + this.labelRegex.Location = new System.Drawing.Point(14, 14); + this.labelRegex.Name = "labelRegex"; + this.labelRegex.Size = new System.Drawing.Size(151, 20); + this.labelRegex.TabIndex = 3; + this.labelRegex.Text = "Regular Expression:"; + // + // labelTestText + // + this.labelTestText.AutoSize = true; + this.labelTestText.Location = new System.Drawing.Point(14, 98); + this.labelTestText.Name = "labelTestText"; + this.labelTestText.Size = new System.Drawing.Size(74, 20); + this.labelTestText.TabIndex = 5; + this.labelTestText.Text = "Test text:"; + // + // labelMatches + // + this.labelMatches.AutoSize = true; + this.labelMatches.Location = new System.Drawing.Point(14, 152); + this.labelMatches.Name = "labelMatches"; + this.labelMatches.Size = new System.Drawing.Size(74, 20); + this.labelMatches.TabIndex = 6; + this.labelMatches.Text = "Matches:"; + // + // textBoxMatches + // + this.textBoxMatches.Location = new System.Drawing.Point(12, 175); + this.textBoxMatches.Multiline = true; + this.textBoxMatches.Name = "textBoxMatches"; + this.textBoxMatches.ReadOnly = true; + this.textBoxMatches.ScrollBars = System.Windows.Forms.ScrollBars.Both; + this.textBoxMatches.Size = new System.Drawing.Size(428, 190); + this.textBoxMatches.TabIndex = 7; + // + // checkBoxCaseSensitive + // + this.checkBoxCaseSensitive.AutoSize = true; + this.checkBoxCaseSensitive.Location = new System.Drawing.Point(12, 71); + this.checkBoxCaseSensitive.Name = "checkBoxCaseSensitive"; + this.checkBoxCaseSensitive.Size = new System.Drawing.Size(137, 24); + this.checkBoxCaseSensitive.TabIndex = 8; + this.checkBoxCaseSensitive.Text = "Case sensitive"; + this.checkBoxCaseSensitive.UseVisualStyleBackColor = true; + this.checkBoxCaseSensitive.CheckedChanged += new System.EventHandler(this.OnCaseSensitiveCheckBoxCheckedChanged); + // + // comboBoxRegex + // + this.comboBoxRegex.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; + this.comboBoxRegex.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; + this.comboBoxRegex.FormattingEnabled = true; + this.comboBoxRegex.Location = new System.Drawing.Point(12, 37); + this.comboBoxRegex.Name = "comboBoxRegex"; + this.comboBoxRegex.Size = new System.Drawing.Size(428, 28); + this.comboBoxRegex.TabIndex = 10; + this.comboBoxRegex.TextChanged += new System.EventHandler(this.OnComboBoxRegexTextChanged); + // + // comboBoxTestText + // + this.comboBoxTestText.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; + this.comboBoxTestText.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; + this.comboBoxTestText.FormattingEnabled = true; + this.comboBoxTestText.Location = new System.Drawing.Point(12, 121); + this.comboBoxTestText.Name = "comboBoxTestText"; + this.comboBoxTestText.Size = new System.Drawing.Size(428, 28); + this.comboBoxTestText.TabIndex = 11; + this.comboBoxTestText.TextChanged += new System.EventHandler(this.OnComboBoxTestTextTextChanged); + // + // helpProvider1 + // + this.helpProvider1.HelpNamespace = "LogExpert.chm"; + // + // buttonHelp + // + this.helpProvider1.SetHelpKeyword(this.buttonHelp, "RegEx.htm"); + this.helpProvider1.SetHelpNavigator(this.buttonHelp, System.Windows.Forms.HelpNavigator.Topic); + this.buttonHelp.Location = new System.Drawing.Point(13, 371); + this.buttonHelp.Name = "buttonHelp"; + this.helpProvider1.SetShowHelp(this.buttonHelp, true); + this.buttonHelp.Size = new System.Drawing.Size(75, 23); + this.buttonHelp.TabIndex = 12; + this.buttonHelp.Text = "Help"; + this.buttonHelp.UseVisualStyleBackColor = true; + this.buttonHelp.Click += new System.EventHandler(this.OnButtonHelpClick); + // + // RegexHelperDialog + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(452, 403); + this.Controls.Add(this.buttonHelp); + this.Controls.Add(this.comboBoxTestText); + this.Controls.Add(this.comboBoxRegex); + this.Controls.Add(this.checkBoxCaseSensitive); + this.Controls.Add(this.textBoxMatches); + this.Controls.Add(this.labelMatches); + this.Controls.Add(this.labelTestText); + this.Controls.Add(this.labelRegex); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.buttonCancel); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.helpProvider1.SetHelpKeyword(this, "RegEx.htm"); + this.helpProvider1.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "RegexHelperDialog"; + this.helpProvider1.SetShowHelp(this, true); + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Regex-Helper"; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Button buttonCancel; +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.Label labelRegex; +private System.Windows.Forms.Label labelTestText; +private System.Windows.Forms.Label labelMatches; +private System.Windows.Forms.TextBox textBoxMatches; +private System.Windows.Forms.CheckBox checkBoxCaseSensitive; +private System.Windows.Forms.ComboBox comboBoxRegex; +private System.Windows.Forms.ComboBox comboBoxTestText; +private System.Windows.Forms.HelpProvider helpProvider1; +private System.Windows.Forms.Button buttonHelp; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs b/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs new file mode 100644 index 00000000..ac7df7c5 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/RegexHelperDialog.cs @@ -0,0 +1,146 @@ +using System.Runtime.Versioning; +using System.Text.RegularExpressions; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class RegexHelperDialog : Form +{ + #region Fields + + private const int MAX_HISTORY = 30; + private bool _caseSensitive; + private List _expressionHistoryList = []; + private List _testtextHistoryList = []; + + #endregion + + #region cTor + + public RegexHelperDialog () + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + Load += OnRegexHelperDialogLoad; + } + + #endregion + + #region Properties + + public bool CaseSensitive + { + get => _caseSensitive; + set + { + _caseSensitive = value; + checkBoxCaseSensitive.Checked = value; + } + } + + public string Pattern + { + get => comboBoxRegex.Text; + set => comboBoxRegex.Text = value; + } + + public List ExpressionHistoryList + { + get => _expressionHistoryList; + set => _expressionHistoryList = value; + } + + public List TesttextHistoryList + { + get => _testtextHistoryList; + set => _testtextHistoryList = value; + } + + #endregion + + #region Private Methods + + private void UpdateMatches () + { + textBoxMatches.Text = ""; + try + { + Regex rex = new(comboBoxRegex.Text, _caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); + MatchCollection matches = rex.Matches(comboBoxTestText.Text); + + foreach (Match match in matches) + { + textBoxMatches.Text += $"{match.Value}\r\n"; + } + } + catch (ArgumentException) + { + textBoxMatches.Text = "No valid regex pattern"; + } + } + + private void LoadHistory () + { + comboBoxRegex.Items.Clear(); + comboBoxRegex.DataSource = _expressionHistoryList; + + comboBoxTestText.Items.Clear(); + comboBoxTestText.DataSource = _testtextHistoryList; + } + + #endregion + + #region Events handler + + private void OnRegexHelperDialogLoad (object? sender, EventArgs e) + { + LoadHistory(); + } + + private void OnCaseSensitiveCheckBoxCheckedChanged (object sender, EventArgs e) + { + _caseSensitive = checkBoxCaseSensitive.Checked; + UpdateMatches(); + } + + private void OnButtonOkClick (object sender, EventArgs e) + { + var text = comboBoxRegex.Text; + comboBoxRegex.Items.Remove(text); + comboBoxRegex.Items.Insert(0, text); + + text = comboBoxTestText.Text; + comboBoxTestText.Items.Remove(text); + comboBoxTestText.Items.Insert(0, text); + + if (comboBoxRegex.Items.Count > MAX_HISTORY) + { + comboBoxRegex.Items.Remove(comboBoxRegex.Items.Count - 1); + } + + if (comboBoxTestText.Items.Count > MAX_HISTORY) + { + comboBoxTestText.Items.Remove(comboBoxTestText.Items.Count - 1); + } + } + + private void OnComboBoxRegexTextChanged (object sender, EventArgs e) + { + UpdateMatches(); + } + + private void OnComboBoxTestTextTextChanged (object sender, EventArgs e) + { + UpdateMatches(); + } + + private void OnButtonHelpClick (object sender, EventArgs e) + { + Help.ShowHelp(this, "LogExpert.chm", HelpNavigator.Topic, "RegEx.htm"); + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/RegexHelperDialog.resx b/src/LogExpert.UI/Dialogs/RegexHelperDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/RegexHelperDialog.resx rename to src/LogExpert.UI/Dialogs/RegexHelperDialog.resx index 59775d45..9cf9a31f 100644 --- a/src/LogExpert/Dialogs/RegexHelperDialog.resx +++ b/src/LogExpert.UI/Dialogs/RegexHelperDialog.resx @@ -1,123 +1,123 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - 17, 17 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 17, 17 + \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/SearchDialog.Designer.cs b/src/LogExpert.UI/Dialogs/SearchDialog.Designer.cs new file mode 100644 index 00000000..8a0e20dc --- /dev/null +++ b/src/LogExpert.UI/Dialogs/SearchDialog.Designer.cs @@ -0,0 +1,253 @@ +namespace LogExpert.Dialogs; + +partial class SearchDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.labelSearchFor = new System.Windows.Forms.Label(); + this.checkBoxCaseSensitive = new System.Windows.Forms.CheckBox(); + this.checkBoxRegex = new System.Windows.Forms.CheckBox(); + this.buttonRegexHelper = new System.Windows.Forms.Button(); + this.radioButtonFromTop = new System.Windows.Forms.RadioButton(); + this.radioButtonFromSelected = new System.Windows.Forms.RadioButton(); + this.groupBoxSearchStart = new System.Windows.Forms.GroupBox(); + this.groupBoxOptions = new System.Windows.Forms.GroupBox(); + this.groupBoxDirection = new System.Windows.Forms.GroupBox(); + this.radioButtonBackward = new System.Windows.Forms.RadioButton(); + this.radioButtonForward = new System.Windows.Forms.RadioButton(); + this.comboBoxSearchFor = new System.Windows.Forms.ComboBox(); + this.helpProvider1 = new System.Windows.Forms.HelpProvider(); + this.groupBoxSearchStart.SuspendLayout(); + this.groupBoxOptions.SuspendLayout(); + this.groupBoxDirection.SuspendLayout(); + this.SuspendLayout(); + // + // buttonOk + // + this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(317, 215); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 5; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); + // + // buttonCancel + // + this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(398, 215); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 6; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.OnButtonCancelClick); + // + // labelSearchFor + // + this.labelSearchFor.AutoSize = true; + this.labelSearchFor.Location = new System.Drawing.Point(10, 9); + this.labelSearchFor.Name = "labelSearchFor"; + this.labelSearchFor.Size = new System.Drawing.Size(87, 20); + this.labelSearchFor.TabIndex = 0; + this.labelSearchFor.Text = "&Search for:"; + // + // checkBoxCaseSensitive + // + this.checkBoxCaseSensitive.AutoSize = true; + this.checkBoxCaseSensitive.Location = new System.Drawing.Point(6, 19); + this.checkBoxCaseSensitive.Name = "checkBoxCaseSensitive"; + this.checkBoxCaseSensitive.Size = new System.Drawing.Size(137, 24); + this.checkBoxCaseSensitive.TabIndex = 4; + this.checkBoxCaseSensitive.Text = "&Case sensitive"; + this.checkBoxCaseSensitive.UseVisualStyleBackColor = true; + // + // checkBoxRegex + // + this.checkBoxRegex.AutoSize = true; + this.checkBoxRegex.Location = new System.Drawing.Point(6, 43); + this.checkBoxRegex.Name = "checkBoxRegex"; + this.checkBoxRegex.Size = new System.Drawing.Size(171, 24); + this.checkBoxRegex.TabIndex = 5; + this.checkBoxRegex.Text = "&Regular expression"; + this.checkBoxRegex.UseVisualStyleBackColor = true; + // + // buttonRegexHelper + // + this.buttonRegexHelper.Location = new System.Drawing.Point(6, 72); + this.buttonRegexHelper.Name = "buttonRegexHelper"; + this.buttonRegexHelper.Size = new System.Drawing.Size(84, 26); + this.buttonRegexHelper.TabIndex = 3; + this.buttonRegexHelper.Text = "Regex-&Helper"; + this.buttonRegexHelper.UseVisualStyleBackColor = true; + this.buttonRegexHelper.Click += new System.EventHandler(this.OnButtonRegexClick); + // + // radioButtonFromTop + // + this.radioButtonFromTop.AutoSize = true; + this.radioButtonFromTop.Location = new System.Drawing.Point(6, 19); + this.radioButtonFromTop.Name = "radioButtonFromTop"; + this.radioButtonFromTop.Size = new System.Drawing.Size(98, 24); + this.radioButtonFromTop.TabIndex = 7; + this.radioButtonFromTop.TabStop = true; + this.radioButtonFromTop.Text = "From top"; + this.radioButtonFromTop.UseVisualStyleBackColor = true; + // + // radioButtonFromSelected + // + this.radioButtonFromSelected.AutoSize = true; + this.radioButtonFromSelected.Location = new System.Drawing.Point(6, 42); + this.radioButtonFromSelected.Name = "radioButtonFromSelected"; + this.radioButtonFromSelected.Size = new System.Drawing.Size(163, 24); + this.radioButtonFromSelected.TabIndex = 8; + this.radioButtonFromSelected.TabStop = true; + this.radioButtonFromSelected.Text = "From selected line"; + this.radioButtonFromSelected.UseVisualStyleBackColor = true; + // + // groupBoxSearchStart + // + this.groupBoxSearchStart.Controls.Add(this.radioButtonFromTop); + this.groupBoxSearchStart.Controls.Add(this.radioButtonFromSelected); + this.groupBoxSearchStart.Location = new System.Drawing.Point(12, 74); + this.groupBoxSearchStart.Name = "groupBoxSearchStart"; + this.groupBoxSearchStart.Size = new System.Drawing.Size(179, 79); + this.groupBoxSearchStart.TabIndex = 1; + this.groupBoxSearchStart.TabStop = false; + this.groupBoxSearchStart.Text = "Search start"; + // + // groupBoxOptions + // + this.groupBoxOptions.Controls.Add(this.checkBoxCaseSensitive); + this.groupBoxOptions.Controls.Add(this.checkBoxRegex); + this.groupBoxOptions.Controls.Add(this.buttonRegexHelper); + this.groupBoxOptions.Location = new System.Drawing.Point(198, 74); + this.groupBoxOptions.Name = "groupBoxOptions"; + this.groupBoxOptions.Size = new System.Drawing.Size(275, 104); + this.groupBoxOptions.TabIndex = 2; + this.groupBoxOptions.TabStop = false; + this.groupBoxOptions.Text = "Options"; + // + // groupBoxDirection + // + this.groupBoxDirection.Controls.Add(this.radioButtonBackward); + this.groupBoxDirection.Controls.Add(this.radioButtonForward); + this.groupBoxDirection.Location = new System.Drawing.Point(13, 159); + this.groupBoxDirection.Name = "groupBoxDirection"; + this.groupBoxDirection.Size = new System.Drawing.Size(122, 79); + this.groupBoxDirection.TabIndex = 4; + this.groupBoxDirection.TabStop = false; + this.groupBoxDirection.Text = "Direction"; + // + // radioButtonBackward + // + this.radioButtonBackward.AutoSize = true; + this.radioButtonBackward.Location = new System.Drawing.Point(7, 44); + this.radioButtonBackward.Name = "radioButtonBackward"; + this.radioButtonBackward.Size = new System.Drawing.Size(104, 24); + this.radioButtonBackward.TabIndex = 1; + this.radioButtonBackward.TabStop = true; + this.radioButtonBackward.Text = "Backward"; + this.radioButtonBackward.UseVisualStyleBackColor = true; + // + // radioButtonForward + // + this.radioButtonForward.AutoSize = true; + this.radioButtonForward.Location = new System.Drawing.Point(7, 20); + this.radioButtonForward.Name = "radioButtonForward"; + this.radioButtonForward.Size = new System.Drawing.Size(92, 24); + this.radioButtonForward.TabIndex = 0; + this.radioButtonForward.TabStop = true; + this.radioButtonForward.Text = "Forward"; + this.radioButtonForward.UseVisualStyleBackColor = true; + // + // comboBoxSearchFor + // + this.comboBoxSearchFor.FormattingEnabled = true; + this.comboBoxSearchFor.Location = new System.Drawing.Point(13, 34); + this.comboBoxSearchFor.Name = "comboBoxSearchFor"; + this.comboBoxSearchFor.Size = new System.Drawing.Size(460, 28); + this.comboBoxSearchFor.TabIndex = 0; + // + // helpProvider1 + // + this.helpProvider1.HelpNamespace = "LogExpert.chm"; + // + // SearchDialog + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(488, 250); + this.Controls.Add(this.comboBoxSearchFor); + this.Controls.Add(this.groupBoxDirection); + this.Controls.Add(this.groupBoxOptions); + this.Controls.Add(this.groupBoxSearchStart); + this.Controls.Add(this.labelSearchFor); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOk); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.helpProvider1.SetHelpKeyword(this, "Search and Navigation.htm"); + this.helpProvider1.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "SearchDialog"; + this.helpProvider1.SetShowHelp(this, true); + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Search"; + this.groupBoxSearchStart.ResumeLayout(false); + this.groupBoxSearchStart.PerformLayout(); + this.groupBoxOptions.ResumeLayout(false); + this.groupBoxOptions.PerformLayout(); + this.groupBoxDirection.ResumeLayout(false); + this.groupBoxDirection.PerformLayout(); + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.Button buttonCancel; +private System.Windows.Forms.Label labelSearchFor; +private System.Windows.Forms.CheckBox checkBoxCaseSensitive; +private System.Windows.Forms.CheckBox checkBoxRegex; +private System.Windows.Forms.Button buttonRegexHelper; +private System.Windows.Forms.RadioButton radioButtonFromTop; +private System.Windows.Forms.RadioButton radioButtonFromSelected; +private System.Windows.Forms.GroupBox groupBoxSearchStart; +private System.Windows.Forms.GroupBox groupBoxOptions; +private System.Windows.Forms.GroupBox groupBoxDirection; +private System.Windows.Forms.RadioButton radioButtonBackward; +private System.Windows.Forms.RadioButton radioButtonForward; +private System.Windows.Forms.ComboBox comboBoxSearchFor; +private System.Windows.Forms.HelpProvider helpProvider1; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/SearchDialog.cs b/src/LogExpert.UI/Dialogs/SearchDialog.cs new file mode 100644 index 00000000..a12294ed --- /dev/null +++ b/src/LogExpert.UI/Dialogs/SearchDialog.cs @@ -0,0 +1,137 @@ +using System.Runtime.Versioning; +using System.Text.RegularExpressions; + +using LogExpert.Entities; +using LogExpert.UI.Dialogs; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class SearchDialog : Form +{ + #region Fields + + private const int MAX_HISTORY = 30; + + #endregion + + #region cTor + + public SearchDialog () + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + Load += OnSearchDialogLoad; + } + + #endregion + + #region Properties + + public SearchParams SearchParams { get; set; } = new(); + + #endregion + + #region Events handler + + private void OnSearchDialogLoad (object? sender, EventArgs e) + { + if (SearchParams != null) + { + if (SearchParams.IsFromTop) + { + radioButtonFromTop.Checked = true; + } + else + { + radioButtonFromSelected.Checked = true; + } + + if (SearchParams.IsForward) + { + radioButtonForward.Checked = true; + } + else + { + radioButtonBackward.Checked = true; + } + + checkBoxRegex.Checked = SearchParams.IsRegex; + checkBoxCaseSensitive.Checked = SearchParams.IsCaseSensitive; + foreach (var item in SearchParams.HistoryList) + { + comboBoxSearchFor.Items.Add(item); + } + + if (comboBoxSearchFor.Items.Count > 0) + { + comboBoxSearchFor.SelectedIndex = 0; + } + } + else + { + radioButtonFromSelected.Checked = true; + radioButtonForward.Checked = true; + SearchParams = new SearchParams(); + } + } + + private void OnButtonRegexClick (object sender, EventArgs e) + { + RegexHelperDialog dlg = new() + { + Owner = this, + CaseSensitive = checkBoxCaseSensitive.Checked, + Pattern = comboBoxSearchFor.Text + }; + + if (dlg.ShowDialog() == DialogResult.OK) + { + checkBoxCaseSensitive.Checked = dlg.CaseSensitive; + comboBoxSearchFor.Text = dlg.Pattern; + } + } + + private void OnButtonOkClick (object sender, EventArgs e) + { + try + { + if (checkBoxRegex.Checked) + { + if (string.IsNullOrWhiteSpace(comboBoxSearchFor.Text)) + { + throw new ArgumentException("Search text is empty"); + } + + Regex.IsMatch("", comboBoxSearchFor.Text); + } + + SearchParams.SearchText = comboBoxSearchFor.Text; + SearchParams.IsCaseSensitive = checkBoxCaseSensitive.Checked; + SearchParams.IsForward = radioButtonForward.Checked; + SearchParams.IsFromTop = radioButtonFromTop.Checked; + SearchParams.IsRegex = checkBoxRegex.Checked; + SearchParams.HistoryList.Remove(comboBoxSearchFor.Text); + SearchParams.HistoryList.Insert(0, comboBoxSearchFor.Text); + + if (SearchParams.HistoryList.Count > MAX_HISTORY) + { + SearchParams.HistoryList.RemoveAt(SearchParams.HistoryList.Count - 1); + } + } + catch (Exception ex) + { + MessageBox.Show($"Error during creation of search parameter\r\n{ex.Message}"); + } + } + + #endregion + + private void OnButtonCancelClick (object sender, EventArgs e) + { + Close(); + } +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SearchDialog.resx b/src/LogExpert.UI/Dialogs/SearchDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/SearchDialog.resx rename to src/LogExpert.UI/Dialogs/SearchDialog.resx index 59775d45..9cf9a31f 100644 --- a/src/LogExpert/Dialogs/SearchDialog.resx +++ b/src/LogExpert.UI/Dialogs/SearchDialog.resx @@ -1,123 +1,123 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - 17, 17 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 17, 17 + \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/SearchProgressDialog.Designer.cs b/src/LogExpert.UI/Dialogs/SearchProgressDialog.Designer.cs new file mode 100644 index 00000000..756c707b --- /dev/null +++ b/src/LogExpert.UI/Dialogs/SearchProgressDialog.Designer.cs @@ -0,0 +1,74 @@ +namespace LogExpert.UI.Dialogs; + +partial class SearchProgressDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.buttonCancel = new System.Windows.Forms.Button(); + this.labelSearchProgress = new System.Windows.Forms.Label(); + this.SuspendLayout(); + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(159, 40); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(90, 23); + this.buttonCancel.TabIndex = 0; + this.buttonCancel.Text = "Cancel search"; + this.buttonCancel.UseVisualStyleBackColor = true; + this.buttonCancel.Click += new System.EventHandler(this.OnButtonCancelClick); + // + // labelSearchProgress + // + this.labelSearchProgress.AutoSize = true; + this.labelSearchProgress.Location = new System.Drawing.Point(13, 13); + this.labelSearchProgress.Name = "labelSearchProgress"; + this.labelSearchProgress.Size = new System.Drawing.Size(175, 20); + this.labelSearchProgress.TabIndex = 1; + this.labelSearchProgress.Text = "Searching in progress..."; + // + // SearchProgressDialog + // + this.ClientSize = new System.Drawing.Size(261, 80); + this.ControlBox = false; + this.Controls.Add(this.labelSearchProgress); + this.Controls.Add(this.buttonCancel); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.Name = "SearchProgressDialog"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Searching..."; + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Button buttonCancel; +private System.Windows.Forms.Label labelSearchProgress; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/SearchProgressDialog.cs b/src/LogExpert.UI/Dialogs/SearchProgressDialog.cs new file mode 100644 index 00000000..5d1f8deb --- /dev/null +++ b/src/LogExpert.UI/Dialogs/SearchProgressDialog.cs @@ -0,0 +1,40 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class SearchProgressDialog : Form +{ + #region Fields + + #endregion + + #region cTor + + public SearchProgressDialog() + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + + ShouldStop = false; + } + + #endregion + + #region Properties + + public bool ShouldStop { get; private set; } + + #endregion + + #region Events handler + + private void OnButtonCancelClick(object sender, EventArgs e) + { + ShouldStop = true; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SearchProgressDialog.resx b/src/LogExpert.UI/Dialogs/SearchProgressDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/SearchProgressDialog.resx rename to src/LogExpert.UI/Dialogs/SearchProgressDialog.resx index c7e0d4bd..d58980a3 100644 --- a/src/LogExpert/Dialogs/SearchProgressDialog.resx +++ b/src/LogExpert.UI/Dialogs/SearchProgressDialog.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Dialogs/TabRenameDialog.Designer.cs b/src/LogExpert.UI/Dialogs/TabRenameDialog.Designer.cs new file mode 100644 index 00000000..1911909c --- /dev/null +++ b/src/LogExpert.UI/Dialogs/TabRenameDialog.Designer.cs @@ -0,0 +1,101 @@ +namespace LogExpert.UI.Dialogs; + +partial class TabRenameDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.textBoxTabName = new System.Windows.Forms.TextBox(); + this.labelName = new System.Windows.Forms.Label(); + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.SuspendLayout(); + // + // textBoxTabName + // + this.textBoxTabName.Location = new System.Drawing.Point(12, 34); + this.textBoxTabName.Name = "textBoxTabName"; + this.textBoxTabName.Size = new System.Drawing.Size(193, 26); + this.textBoxTabName.TabIndex = 0; + // + // labelName + // + this.labelName.AutoSize = true; + this.labelName.Location = new System.Drawing.Point(13, 11); + this.labelName.Name = "labelName"; + this.labelName.Size = new System.Drawing.Size(55, 20); + this.labelName.TabIndex = 1; + this.labelName.Text = "Name:"; + // + // buttonOk + // + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(49, 73); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 2; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(130, 73); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 3; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // TabRenameDlg + // + this.AcceptButton = this.buttonOk; + this.ClientSize = new System.Drawing.Size(219, 108); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.buttonOk); + this.Controls.Add(this.labelName); + this.Controls.Add(this.textBoxTabName); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; + this.KeyPreview = true; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "TabRenameDlg"; + this.ShowIcon = false; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Rename Tab"; + this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnTabRenameDlgKeyDown); + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + + private System.Windows.Forms.TextBox textBoxTabName; + private System.Windows.Forms.Label labelName; + private System.Windows.Forms.Button buttonOk; + private System.Windows.Forms.Button buttonCancel; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/TabRenameDialog.cs b/src/LogExpert.UI/Dialogs/TabRenameDialog.cs new file mode 100644 index 00000000..2f2455db --- /dev/null +++ b/src/LogExpert.UI/Dialogs/TabRenameDialog.cs @@ -0,0 +1,42 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class TabRenameDialog : Form +{ + #region cTor + + public TabRenameDialog() + { + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + } + + #endregion + + #region Properties + + public string TabName + { + get => textBoxTabName.Text; + set => textBoxTabName.Text = value; + } + + #endregion + + #region Events handler + + private void OnTabRenameDlgKeyDown(object sender, KeyEventArgs e) + { + if (e.KeyCode == Keys.Escape) + { + DialogResult = DialogResult.Cancel; + Close(); + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/TabRenameDlg.resx b/src/LogExpert.UI/Dialogs/TabRenameDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/TabRenameDlg.resx rename to src/LogExpert.UI/Dialogs/TabRenameDialog.resx index c7e0d4bd..d58980a3 100644 --- a/src/LogExpert/Dialogs/TabRenameDlg.resx +++ b/src/LogExpert.UI/Dialogs/TabRenameDialog.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Dialogs/ToolArgsDialog.Designer.cs b/src/LogExpert.UI/Dialogs/ToolArgsDialog.Designer.cs new file mode 100644 index 00000000..71931e78 --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ToolArgsDialog.Designer.cs @@ -0,0 +1,150 @@ +namespace LogExpert.Dialogs; + +partial class ToolArgsDialog +{ +/// +/// Required designer variable. +/// +private System.ComponentModel.IContainer components = null; + +/// +/// Clean up any resources being used. +/// +/// true if managed resources should be disposed; otherwise, false. +protected override void Dispose(bool disposing) +{ + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); +} + +#region Windows Form Designer generated code + +/// +/// Required method for Designer support - do not modify +/// the contents of this method with the code editor. +/// +private void InitializeComponent() +{ + this.buttonOk = new System.Windows.Forms.Button(); + this.buttonRegexHelp = new System.Windows.Forms.Button(); + this.textBoxArguments = new System.Windows.Forms.TextBox(); + this.buttonTest = new System.Windows.Forms.Button(); + this.labelEnterArguments = new System.Windows.Forms.Label(); + this.labelHelp = new System.Windows.Forms.Label(); + this.buttonCancel = new System.Windows.Forms.Button(); + this.labelTestResult = new System.Windows.Forms.TextBox(); + this.SuspendLayout(); + // + // buttonOk + // + this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; + this.buttonOk.Location = new System.Drawing.Point(348, 292); + this.buttonOk.Name = "buttonOk"; + this.buttonOk.Size = new System.Drawing.Size(75, 23); + this.buttonOk.TabIndex = 1; + this.buttonOk.Text = "OK"; + this.buttonOk.UseVisualStyleBackColor = true; + this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); + // + // buttonRegexHelp + // + this.buttonRegexHelp.Location = new System.Drawing.Point(429, 59); + this.buttonRegexHelp.Name = "buttonRegexHelp"; + this.buttonRegexHelp.Size = new System.Drawing.Size(75, 21); + this.buttonRegexHelp.TabIndex = 2; + this.buttonRegexHelp.Text = "RegEx Help"; + this.buttonRegexHelp.UseVisualStyleBackColor = true; + this.buttonRegexHelp.Click += new System.EventHandler(this.OnButtonRegexHelpClick); + // + // textBoxArguments + // + this.textBoxArguments.Location = new System.Drawing.Point(12, 36); + this.textBoxArguments.Name = "textBoxArguments"; + this.textBoxArguments.Size = new System.Drawing.Size(395, 26); + this.textBoxArguments.TabIndex = 8; + // + // buttonTest + // + this.buttonTest.Location = new System.Drawing.Point(429, 30); + this.buttonTest.Name = "buttonTest"; + this.buttonTest.Size = new System.Drawing.Size(75, 23); + this.buttonTest.TabIndex = 9; + this.buttonTest.Text = "Test"; + this.buttonTest.UseVisualStyleBackColor = true; + this.buttonTest.Click += new System.EventHandler(this.OnButtonTestClick); + // + // labelEnterArguments + // + this.labelEnterArguments.AutoSize = true; + this.labelEnterArguments.Location = new System.Drawing.Point(12, 13); + this.labelEnterArguments.Name = "labelEnterArguments"; + this.labelEnterArguments.Size = new System.Drawing.Size(154, 20); + this.labelEnterArguments.TabIndex = 11; + this.labelEnterArguments.Text = "Enter command line:"; + // + // labelHelp + // + this.labelHelp.Location = new System.Drawing.Point(15, 124); + this.labelHelp.Name = "labelHelp"; + this.labelHelp.Size = new System.Drawing.Size(392, 157); + this.labelHelp.TabIndex = 12; + this.labelHelp.Text = "Help"; + // + // buttonCancel + // + this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; + this.buttonCancel.Location = new System.Drawing.Point(429, 292); + this.buttonCancel.Name = "buttonCancel"; + this.buttonCancel.Size = new System.Drawing.Size(75, 23); + this.buttonCancel.TabIndex = 13; + this.buttonCancel.Text = "Cancel"; + this.buttonCancel.UseVisualStyleBackColor = true; + // + // labelTestResult + // + this.labelTestResult.Location = new System.Drawing.Point(12, 68); + this.labelTestResult.Multiline = true; + this.labelTestResult.Name = "labelTestResult"; + this.labelTestResult.ReadOnly = true; + this.labelTestResult.Size = new System.Drawing.Size(395, 48); + this.labelTestResult.TabIndex = 14; + // + // ToolArgsDialog + // + this.AcceptButton = this.buttonOk; + this.CancelButton = this.buttonCancel; + this.ClientSize = new System.Drawing.Size(516, 327); + this.Controls.Add(this.labelTestResult); + this.Controls.Add(this.buttonCancel); + this.Controls.Add(this.labelHelp); + this.Controls.Add(this.labelEnterArguments); + this.Controls.Add(this.buttonTest); + this.Controls.Add(this.textBoxArguments); + this.Controls.Add(this.buttonRegexHelp); + this.Controls.Add(this.buttonOk); + this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; + this.MaximizeBox = false; + this.MinimizeBox = false; + this.Name = "ToolArgsDialog"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; + this.Text = "Tool Arguments Help"; + this.Load += new System.EventHandler(this.OnToolArgsDialogLoad); + this.ResumeLayout(false); + this.PerformLayout(); + +} + +#endregion + +private System.Windows.Forms.Button buttonOk; +private System.Windows.Forms.Button buttonRegexHelp; +private System.Windows.Forms.TextBox textBoxArguments; +private System.Windows.Forms.Button buttonTest; +private System.Windows.Forms.Label labelEnterArguments; +private System.Windows.Forms.Label labelHelp; +private System.Windows.Forms.Button buttonCancel; +private System.Windows.Forms.TextBox labelTestResult; +} \ No newline at end of file diff --git a/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs b/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs new file mode 100644 index 00000000..a1a68d1f --- /dev/null +++ b/src/LogExpert.UI/Dialogs/ToolArgsDialog.cs @@ -0,0 +1,94 @@ +using System.Runtime.Versioning; + +using LogExpert.UI.Controls.LogTabWindow; +using LogExpert.UI.Dialogs; +using LogExpert.UI.Entities; + +namespace LogExpert.Dialogs; + +[SupportedOSPlatform("windows")] +internal partial class ToolArgsDialog : Form +{ + #region Fields + + private readonly LogTabWindow logTabWin; + + #endregion + + #region cTor + + public ToolArgsDialog (LogTabWindow logTabWin, Form parent) + { + this.logTabWin = logTabWin; + parent.AddOwnedForm(this); + TopMost = parent.TopMost; + InitializeComponent(); + + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + } + + #endregion + + #region Properties + + public string Arg { get; set; } + + #endregion + + #region Events handler + + private void OnToolArgsDialogLoad (object sender, EventArgs e) + { + labelHelp.Text = "" + + "%L = Current line number\n" + + "%N = Current log file name without path\n" + + "%P = Path (directory) of current log file\n" + + "%F = Full name (incl. path) of log file\n" + + "%E = Extension of log file name (e.g. 'txt')\n" + + "%M = Name of log file without extension\n" + + "%S = User (from URI)\n" + + "%R = Path (from URI)\n" + + "%H = Host (from URI)\n" + + "%T = Port (from URI)\n" + + "?\"\" = variable parameter 'name'\n" + + "?\"\"(def1,def2,...) = variable parameter with predefined values\n" + + "\n" + + "{}{}:\n" + + "Regex search/replace on current selected line."; + + textBoxArguments.Text = Arg; + } + + private void OnButtonRegexHelpClick (object sender, EventArgs e) + { + RegexHelperDialog regexDlg = new(); + if (regexDlg.ShowDialog() == DialogResult.OK) + { + textBoxArguments.SelectedText = regexDlg.Pattern; + } + } + + //TODO: what is the purpose of this in the settings? Can we just send the line and info instead of the object? + private void OnButtonTestClick (object sender, EventArgs e) + { + if (logTabWin.CurrentLogWindow != null) + { + ILogLine line = logTabWin.CurrentLogWindow.GetCurrentLine(); + ILogFileInfo info = logTabWin.CurrentLogWindow.GetCurrentFileInfo(); + if (line != null && info != null) + { + ArgParser parser = new(textBoxArguments.Text); + var args = parser.BuildArgs(line, logTabWin.CurrentLogWindow.GetRealLineNum() + 1, info, this); + labelTestResult.Text = args; + } + } + } + + private void OnButtonOkClick (object sender, EventArgs e) + { + Arg = textBoxArguments.Text; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ToolArgsDialog.resx b/src/LogExpert.UI/Dialogs/ToolArgsDialog.resx similarity index 97% rename from src/LogExpert/Dialogs/ToolArgsDialog.resx rename to src/LogExpert.UI/Dialogs/ToolArgsDialog.resx index c7e0d4bd..d58980a3 100644 --- a/src/LogExpert/Dialogs/ToolArgsDialog.resx +++ b/src/LogExpert.UI/Dialogs/ToolArgsDialog.resx @@ -1,120 +1,120 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/Entities/ArgParser.cs b/src/LogExpert.UI/Entities/ArgParser.cs new file mode 100644 index 00000000..8aa65cfd --- /dev/null +++ b/src/LogExpert.UI/Entities/ArgParser.cs @@ -0,0 +1,155 @@ +using System.Runtime.Versioning; +using System.Text; +using System.Text.RegularExpressions; + +using LogExpert.Core.Classes; +using LogExpert.Dialogs; + +namespace LogExpert.UI.Entities; + +internal class ArgParser (string argTemplate) +{ + #region Public methods + + [SupportedOSPlatform("windows")] + public string BuildArgs (ILogLine logLine, int lineNum, ILogFileInfo logFileInfo, Form parent) + { + StringBuilder builder = new(argTemplate); + + _ = builder.Replace("%L", "" + lineNum); + _ = builder.Replace("%P", logFileInfo.DirectoryName); + _ = builder.Replace("%N", logFileInfo.FileName); + _ = builder.Replace("%F", logFileInfo.FullName); + _ = builder.Replace("%E", Util.GetExtension(logFileInfo.FileName)); + var stripped = Util.StripExtension(logFileInfo.FileName); + _ = builder.Replace("%M", stripped); + _ = builder.Replace("%URI", logFileInfo.Uri.AbsoluteUri); + var user = logFileInfo.Uri.UserInfo; + + if (user.Contains(':', StringComparison.Ordinal)) + { + user = user[..user.IndexOf(':', StringComparison.Ordinal)]; + } + + _ = builder.Replace("%S", user); + _ = builder.Replace("%R", logFileInfo.Uri.PathAndQuery); + _ = builder.Replace("%H", logFileInfo.Uri.Host); + _ = builder.Replace("%T", logFileInfo.Uri.Port.ToString()); + + var sPos = 0; + string reg; + string replace; + do + { + reg = GetNextGroup(builder, ref sPos); + replace = GetNextGroup(builder, ref sPos); + if (reg != null && replace != null) + { + var result = Regex.Replace(logLine.FullLine, reg, replace); + _ = builder.Insert(sPos, result); + } + } while (replace != null); + + var i = 0; + while (i < builder.Length) + { + // ?"Pinpad-type?"(thales,dione) + if (builder[i] == '?') + { + var end = i; + var ask = "Parameter"; + if (builder[i + 1] == '"') + { + end = builder.ToString().IndexOf('"', i + 2); + if (end == -1) + { + end = builder.Length - 1; + } + + ask = builder.ToString().Substring(i + 2, end - i - 2); + } + + string[] values = null; + + if (builder[end + 1] == '(') + { + var end2 = builder.ToString().IndexOf(')', StringComparison.Ordinal); + if (end2 == -1) + { + end2 = builder.Length - 1; + } + var valueStr = builder.ToString().Substring(end + 2, end2 - end - 2); + values = valueStr.Split([','], StringSplitOptions.None); + end = end2; + } + + ParamRequesterDialog dlg = new() + { + ParamName = ask, + Values = values + }; + + DialogResult res = dlg.ShowDialog(parent); + + if (res is DialogResult.OK) + { + _ = builder.Remove(i, end - i + 1); + _ = builder.Insert(i, dlg.ParamValue); + } + else if (res is DialogResult.Cancel or DialogResult.Abort) + { + return null; + } + } + + ++i; + } + + return builder.ToString(); + } + + #endregion + + #region Private Methods + + private string GetNextGroup (StringBuilder builder, ref int sPos) + { + int ePos; + while (sPos < builder.Length) + { + if (builder[sPos] == '{') + { + ePos = sPos + 1; + var count = 1; + + while (ePos < builder.Length) + { + if (builder[ePos] == '{') + { + count++; + } + + if (builder[ePos] == '}') + { + count--; + } + + if (count == 0) + { + var reg = builder.ToString(sPos + 1, ePos - sPos - 1); + _ = builder.Remove(sPos, ePos - sPos + 1); + return reg; + } + + ePos++; + } + } + + sPos++; + } + + return null; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Entities/PaintHelper.cs b/src/LogExpert.UI/Entities/PaintHelper.cs new file mode 100644 index 00000000..b58b26a4 --- /dev/null +++ b/src/LogExpert.UI/Entities/PaintHelper.cs @@ -0,0 +1,518 @@ +using System.Runtime.Versioning; + +using LogExpert.Core.Classes.Highlight; +using LogExpert.Core.Entities; +using LogExpert.Dialogs; +using LogExpert.UI.Controls; +using LogExpert.UI.Interface; + +using NLog; + +namespace LogExpert.UI.Entities; + +//TOOD: This whole class should be refactored and rethought +internal static class PaintHelper +{ + #region Fields + + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); + + #endregion + + #region Public methods + + [SupportedOSPlatform("windows")] + public static void CellPainting (ILogPaintContextUI logPaintCtx, bool focused, int rowIndex, int columnIndex, DataGridViewCellPaintingEventArgs e) + { + if (rowIndex < 0 || columnIndex < 0) + { + e.Handled = false; + return; + } + + var line = logPaintCtx.GetLogLine(rowIndex); + + if (line != null) + { + var entry = logPaintCtx.FindHighlightEntry(line, true); + e.Graphics.SetClip(e.CellBounds); + + if (e.State.HasFlag(DataGridViewElementStates.Selected)) + { + using var brush = GetBrushForFocusedControl(focused, e.CellStyle.SelectionBackColor); + e.Graphics.FillRectangle(brush, e.CellBounds); + } + else + { + e.CellStyle.BackColor = GetBackColorFromHighlightEntry(entry); + e.PaintBackground(e.ClipBounds, false); + } + + if (DebugOptions.DisableWordHighlight) + { + e.PaintContent(e.CellBounds); + } + else + { + PaintCell(logPaintCtx, e, entry); + } + + if (e.ColumnIndex == 0) + { + var bookmark = logPaintCtx.GetBookmarkForLine(rowIndex); + if (bookmark != null) + { + //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); + using var brush = new SolidBrush(logPaintCtx.BookmarkColor); + e.Graphics.FillRectangle(brush, r); + + 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 = logPaintCtx.MonospacedFont; + 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 static Color GetBackColorFromHighlightEntry (HighlightEntry? entry) + { + return entry?.BackgroundColor ?? Color.White; + } + + [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 () + { + DataGridViewTextBoxColumn markerColumn = new() + { + HeaderText = string.Empty, + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.False, + DividerWidth = 1, + ReadOnly = true, + SortMode = DataGridViewColumnSortMode.NotSortable + }; + + return markerColumn; + } + + [SupportedOSPlatform("windows")] + public static DataGridViewTextBoxColumn CreateLineNumberColumn () + { + DataGridViewTextBoxColumn lineNumberColumn = new() + { + HeaderText = "Line", + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.NotSet, + DividerWidth = 1, + ReadOnly = true, + SortMode = DataGridViewColumnSortMode.NotSortable + }; + + return lineNumberColumn; + } + + [SupportedOSPlatform("windows")] + public static DataGridViewColumn CreateTitleColumn (string colName) + { + DataGridViewColumn titleColumn = new LogTextColumn + { + HeaderText = colName, + AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet, + Resizable = DataGridViewTriState.NotSet, + DividerWidth = 1, + SortMode = DataGridViewColumnSortMode.NotSortable + }; + + return titleColumn; + } + + [SupportedOSPlatform("windows")] + public static void SetColumnizer (ILogLineColumnizer columnizer, BufferedDataGridView gridView) + { + var rowCount = gridView.RowCount; + var currLine = gridView.CurrentCellAddress.Y; + var currFirstLine = gridView.FirstDisplayedScrollingRowIndex; + + try + { + gridView.Columns.Clear(); + } + catch (ArgumentOutOfRangeException ae) + { + // Occures sometimes on empty gridViews (no lines) if bookmark window was closed and re-opened in floating mode. + // Don't know why. + _logger.Error(ae); + } + + _ = gridView.Columns.Add(CreateMarkerColumn()); + + _ = gridView.Columns.Add(CreateLineNumberColumn()); + + foreach (var colName in columnizer.GetColumnNames()) + { + _ = gridView.Columns.Add(CreateTitleColumn(colName)); + } + + gridView.RowCount = rowCount; + + if (currLine != -1) + { + gridView.CurrentCell = gridView.Rows[currLine].Cells[0]; + } + + if (currFirstLine != -1) + { + gridView.FirstDisplayedScrollingRowIndex = currFirstLine; + } + + //gridView.Refresh(); + //AutoResizeColumns(gridView); + } + + [SupportedOSPlatform("windows")] + private static void AutoResizeColumns (BufferedDataGridView gridView, bool setLastColumnWidth, int lastColumnWidth) + { + try + { + gridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); + if (gridView.Columns.Count > 1 && setLastColumnWidth && gridView.Columns[gridView.Columns.Count - 1].Width < 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 = 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: "); + } + } + + /// + /// 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; + } + + //TODO Make this configurable => this should close https://github.com/LogExperts/LogExpert/issues/85 + [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 + }; + } + + //TODO Make this configurable => this should close https://github.com/LogExperts/LogExpert/issues/85 + [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) + { + if (dataGridView.Columns.Count > 1) + { + if (setLastColumnWidht) + { + dataGridView.Columns[dataGridView.Columns.Count - 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.Count - 1].MinimumWidth = 5; // default + } + } + + if (dataGridView.RowCount > 0) + { + dataGridView.UpdateRowHeightInfo(0, true); + } + + dataGridView.Invalidate(); + dataGridView.Refresh(); + AutoResizeColumns(dataGridView, setLastColumnWidht, lastColumnWidth); + } + + [SupportedOSPlatform("windows")] + public static Rectangle BorderWidths (DataGridViewAdvancedBorderStyle style) + { + return new Rectangle( + GetBorderSize(style.Left), + GetBorderSize(style.Top), + GetBorderSize(style.Right), + GetBorderSize(style.Bottom)); + } + + [SupportedOSPlatform("windows")] + private static int GetBorderSize (DataGridViewAdvancedCellBorderStyle borderStyle) + { + return borderStyle switch + { + DataGridViewAdvancedCellBorderStyle.None => 0, + DataGridViewAdvancedCellBorderStyle.InsetDouble or DataGridViewAdvancedCellBorderStyle.OutsetDouble => 2, + _ => 1 + }; + } + + #endregion + + #region Private Methods + + [SupportedOSPlatform("windows")] + private static void PaintCell (ILogPaintContextUI logPaintCtx, DataGridViewCellPaintingEventArgs e, HighlightEntry groundEntry) + { + PaintHighlightedCell(logPaintCtx, e, groundEntry); + } + + [SupportedOSPlatform("windows")] + private static void PaintHighlightedCell (ILogPaintContextUI logPaintCtx, DataGridViewCellPaintingEventArgs e, HighlightEntry groundEntry) + { + //TODO Refactor if possible since Column is ITextValue + var value = e.Value ?? string.Empty; + + var matchList = logPaintCtx.FindHighlightMatches(value as ITextValue); + // too many entries per line seem to cause problems with the GDI + while (matchList.Count > 50) + { + matchList.RemoveAt(50); + } + + if (value is Column column) + { + if (!string.IsNullOrEmpty(column.FullValue)) + { + HighlightMatchEntry hme = new() + { + StartPos = 0, + Length = column.FullValue.Length + }; + + var he = new HighlightEntry + { + SearchText = column.FullValue, + //TODO change to white if the background color is darker + BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, + ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), + IsRegEx = false, + IsCaseSensitive = false, + IsLedSwitch = false, + IsStopTail = false, + IsSetBookmark = false, + IsActionEntry = false, + IsWordMatch = false + }; + + hme.HighlightEntry = he; + + matchList = MergeHighlightMatchEntries(matchList, hme); + } + } + + 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); + 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); + + e.Graphics.SetClip(e.CellBounds); + + foreach (var matchEntry in matchList) + { + using var font = matchEntry != null && matchEntry.HighlightEntry.IsBold + ? logPaintCtx.BoldFont + : logPaintCtx.NormalFont; + + using var bgBrush = matchEntry.HighlightEntry.BackgroundColor != Color.Empty + ? new SolidBrush(matchEntry.HighlightEntry.BackgroundColor) + : null; + + var matchWord = string.Empty; + if (value is Column again) + { + if (!string.IsNullOrEmpty(again.FullValue)) + { + matchWord = again.FullValue.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.HasFlag(DataGridViewElementStates.Selected)) + { + if (foreColor.Equals(Color.Black)) + { + foreColor = Color.White; + } + } + else + { + 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); + } + } + + /// + /// 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 HilightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. + private static 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 mergeEntry = new() + { + StartPos = lastStartPos, + Length = pos - lastStartPos, + HighlightEntry = currentEntry + }; + + mergedList.Add(mergeEntry); + currentEntry = entryArray[pos]; + lastStartPos = pos; + } + } + + HighlightMatchEntry secondMergeEntry = new() + { + StartPos = lastStartPos, + Length = pos - lastStartPos, + HighlightEntry = currentEntry + }; + mergedList.Add(secondMergeEntry); + } + + return mergedList; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Entities/WindowFileEntry.cs b/src/LogExpert.UI/Entities/WindowFileEntry.cs new file mode 100644 index 00000000..842dfd41 --- /dev/null +++ b/src/LogExpert.UI/Entities/WindowFileEntry.cs @@ -0,0 +1,42 @@ +using System.Runtime.Versioning; + +using LogExpert.UI.Controls.LogWindow; + +namespace LogExpert.UI.Entities; + +/// +/// Represents a log file and its window. Used as a kind of handle for menus or list of open files. +/// +internal class WindowFileEntry (LogWindow logWindow) +{ + #region Fields + + private const int MAX_LEN = 40; + + #endregion + + #region Properties + + [SupportedOSPlatform("windows")] + public string Title + { + get + { + var title = LogWindow.Text; + + if (title.Length > MAX_LEN) + { + title = string.Concat("...", title.AsSpan(title.Length - MAX_LEN)); + } + + return title; + } + } + + [SupportedOSPlatform("windows")] + public string FileName => LogWindow.FileName; + + public LogWindow LogWindow { get; } = logWindow; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Extensions/BookmarkExporter.cs b/src/LogExpert.UI/Extensions/BookmarkExporter.cs new file mode 100644 index 00000000..70381f9a --- /dev/null +++ b/src/LogExpert.UI/Extensions/BookmarkExporter.cs @@ -0,0 +1,73 @@ +using LogExpert.Core.Entities; + +namespace LogExpert.UI.Extensions; + +internal static class BookmarkExporter +{ + #region Fields + + private const string replacementForNewLine = @"\n"; + + #endregion + + #region Public methods + + //TOOD: check if the callers are checking for null before calling + public static void ExportBookmarkList (SortedList bookmarkList, string logfileName, string fileName) + { + ArgumentNullException.ThrowIfNull(bookmarkList, nameof(bookmarkList)); + FileStream fs = new(fileName, FileMode.Create, FileAccess.Write); + StreamWriter writer = new(fs); + writer.WriteLine("Log file name;Line number;Comment"); + foreach (var bookmark in bookmarkList.Values) + { + var line = $"{logfileName};{bookmark.LineNum};{bookmark.Text.Replace(replacementForNewLine, @"\" + replacementForNewLine, StringComparison.OrdinalIgnoreCase).Replace("\r\n", replacementForNewLine, StringComparison.OrdinalIgnoreCase)}"; + writer.WriteLine(line); + } + writer.Close(); + fs.Close(); + } + + public static void ImportBookmarkList (string logfileName, string fileName, SortedList bookmarkList) + { + using FileStream fs = new(fileName, FileMode.Open, FileAccess.Read); + using StreamReader reader = new(fs); + if (!reader.EndOfStream) + { + _ = reader.ReadLine(); // skip "Log file name;Line number;Comment" + } + + while (!reader.EndOfStream) + { + try + { + var line = reader.ReadLine(); + line = line.Replace(replacementForNewLine, "\r\n", StringComparison.OrdinalIgnoreCase).Replace("\\\r\n", replacementForNewLine, StringComparison.OrdinalIgnoreCase); + + // Line is formatted: logfileName ";" bookmark.LineNum ";" bookmark.Text; + var firstSeparator = line.IndexOf(';', StringComparison.OrdinalIgnoreCase); + var secondSeparator = line.IndexOf(';', firstSeparator + 1); + + var fileStr = line[..firstSeparator]; + var lineStr = line.Substring(firstSeparator + 1, secondSeparator - firstSeparator - 1); + var comment = line[(secondSeparator + 1)..]; + + if (int.TryParse(lineStr, out var lineNum)) + { + Bookmark bookmark = new(lineNum, comment); + bookmarkList.Add(lineNum, bookmark); + } + else + { + //!!!log error: skipping a line entry + } + } + catch + { + //!!! + } + } + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Extensions/ComboBoxExtensions.cs b/src/LogExpert.UI/Extensions/ComboBoxExtensions.cs new file mode 100644 index 00000000..9cd24a7a --- /dev/null +++ b/src/LogExpert.UI/Extensions/ComboBoxExtensions.cs @@ -0,0 +1,25 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Extensions; + +[SupportedOSPlatform("windows")] +internal static class ComboBoxExtensions +{ + /// + public static int GetMaxTextWidth(this ComboBox comboBox) + { + var maxTextWidth = comboBox.Width; + + foreach (var item in comboBox.Items) + { + var textWidthInPixels = TextRenderer.MeasureText(item.ToString(), comboBox.Font).Width; + + if (textWidthInPixels > maxTextWidth) + { + maxTextWidth = textWidthInPixels; + } + } + + return maxTextWidth; + } +} diff --git a/src/LogExpert.UI/Extensions/LockFinder.cs b/src/LogExpert.UI/Extensions/LockFinder.cs new file mode 100644 index 00000000..ad4c74c7 --- /dev/null +++ b/src/LogExpert.UI/Extensions/LockFinder.cs @@ -0,0 +1,129 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.InteropServices; + +// Expanded with some helpers from: https://code.msdn.microsoft.com/windowsapps/How-to-know-the-process-704839f4/ +// Uses Windows Restart Manager. +// A more involved and cross platform solution to this problem is here: https://github.com/cklutz/LockCheck + + +namespace LogExpert.UI.Extensions; + +internal class LockFinder +{ + + /// + /// Method FindLockedProcessName Retrieve the first process name + /// that is locking the file at the specified path + /// + /// The path of a file with a write lock held by a + /// process + /// The name of the first process found with a lock + /// + /// Thrown when the file path is not locked + /// + static public string FindLockedProcessName (string path) + { + var list = FindLockProcesses(path); + if (list.Count == 0) + { + throw new Exception( + "No processes are locking the path specified"); + } + return list[0].ProcessName; + } + + /// + /// Method CheckIfFileIsLocked Check if the file specified has a + /// write lock held by a process + /// + /// The path of a file being checked if a write lock + /// held by a process + /// true when one or more processes with lock + static public bool CheckIfFileIsLocked (string path) + { + var list = FindLockProcesses(path); + if (list.Count > 0) + { return true; } + return false; + } + + /// + /// Used to find processes holding a lock on the file. This would cause + /// other usage, such as file truncation or write opretions to throw + /// IOException if an exclusive lock is attempted. + /// + /// Path being checked + /// List of processes holding file lock to path + /// + static public List FindLockProcesses (string path) + { + var key = Guid.NewGuid().ToString(); + var processes = new List(); + + var res = NativeMethods.RmStartSession(out var handle, 0, key); + if (res != 0) + { + throw new Exception("Could not begin restart session. " + + "Unable to determine file locker."); + } + + try + { + uint pnProcInfo = 0; + uint lpdwRebootReasons = NativeMethods.RmRebootReasonNone; + string[] resources = [path]; + + res = NativeMethods.RmRegisterResources(handle, (uint)resources.Length, + resources, 0, null, 0, null); + if (res != 0) + { + throw new Exception("Could not register resource."); + } + res = NativeMethods.RmGetList(handle, out var pnProcInfoNeeded, ref pnProcInfo, null, + ref lpdwRebootReasons); + const int ERROR_MORE_DATA = 234; + if (res == ERROR_MORE_DATA) + { + var processInfo = + new NativeMethods.RM_PROCESS_INFO[pnProcInfoNeeded]; + pnProcInfo = pnProcInfoNeeded; + // Get the list. + res = NativeMethods.RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons); + if (res == 0) + { + processes = new List((int)pnProcInfo); + for (var i = 0; i < pnProcInfo; i++) + { + try + { + processes.Add(Process.GetProcessById(processInfo[i]. + Process.dwProcessId)); + } + catch (ArgumentException) { } + } + } + else + { + throw new Exception("Could not list processes locking resource"); + } + } + else if (res != 0) + { + throw new Exception("Could not list processes locking resource." + + "Failed to get size of result."); + } + } + catch (Exception exception) + { + Trace.WriteLine(exception.Message); + } + finally + { + Trace.WriteLine($"RmEndSession: {NativeMethods.RmEndSession(handle)}"); + } + + return processes; + } +} diff --git a/src/LogExpert.UI/Extensions/LogWindow/AbstractLogTabWindow.cs b/src/LogExpert.UI/Extensions/LogWindow/AbstractLogTabWindow.cs new file mode 100644 index 00000000..664f4279 --- /dev/null +++ b/src/LogExpert.UI/Extensions/LogWindow/AbstractLogTabWindow.cs @@ -0,0 +1,17 @@ +using System.Runtime.Versioning; + +using LogExpert.Core.Interface; +using LogExpert.UI.Controls.LogTabWindow; + +namespace LogExpert.UI.Extensions.LogWindow; + +public abstract class AbstractLogTabWindow () +{ + public static StaticLogTabWindowData StaticData { get; set; } = new StaticLogTabWindowData(); + + [SupportedOSPlatform("windows")] + public static ILogTabWindow Create (string[] fileNames, int instanceNumber, bool showInstanceNumbers, IConfigManager configManager) + { + return new LogTabWindow(fileNames, instanceNumber, showInstanceNumbers, configManager); + } +} \ No newline at end of file diff --git a/src/LogExpert.UI/Extensions/LogWindow/StaticLogTabWindowData.cs b/src/LogExpert.UI/Extensions/LogWindow/StaticLogTabWindowData.cs new file mode 100644 index 00000000..cc356eb6 --- /dev/null +++ b/src/LogExpert.UI/Extensions/LogWindow/StaticLogTabWindowData.cs @@ -0,0 +1,12 @@ +using LogExpert.Core.Interface; + +namespace LogExpert.UI.Extensions.LogWindow; + +public class StaticLogTabWindowData +{ + #region Properties + + public ILogTabWindow CurrentLockedMainWindow { get; set; } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/Extensions/NativeMethods.cs b/src/LogExpert.UI/Extensions/NativeMethods.cs new file mode 100644 index 00000000..41d97fa1 --- /dev/null +++ b/src/LogExpert.UI/Extensions/NativeMethods.cs @@ -0,0 +1,228 @@ +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace LogExpert.UI.Extensions; + +[SupportedOSPlatform("windows")] +internal static partial class NativeMethods +{ + #region Fields + + public const long SM_CYVSCROLL = 20; + public const long SM_CXHSCROLL = 21; + public const long SM_CXVSCROLL = 2; + public const long SM_CYHSCROLL = 3; + private const int DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19; + private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20; + public const int RmRebootReasonNone = 0; + private const int CCH_RM_MAX_APP_NAME = 255; + private const int CCH_RM_MAX_SVC_NAME = 63; + + #endregion + + #region Structs + + [StructLayout(LayoutKind.Sequential)] + public struct RM_UNIQUE_PROCESS + { + public int dwProcessId; + public System.Runtime.InteropServices. + ComTypes.FILETIME ProcessStartTime; + } + + [StructLayout(LayoutKind.Sequential, + CharSet = CharSet.Auto)] + public struct RM_PROCESS_INFO + { + public RM_UNIQUE_PROCESS Process; + [MarshalAs(UnmanagedType.ByValTStr, + SizeConst = CCH_RM_MAX_APP_NAME + 1)] + public string strAppName; + [MarshalAs(UnmanagedType.ByValTStr, + SizeConst = CCH_RM_MAX_SVC_NAME + 1)] + public string strServiceShortName; + public RM_APP_TYPE ApplicationType; + public uint AppStatus; + public uint TSSessionId; + [MarshalAs(UnmanagedType.Bool)] + public bool bRestartable; + } + #endregion Structs + + #region Enums + public enum RM_APP_TYPE + { + RmUnknownApp = 0, + RmMainWindow = 1, + RmOtherWindow = 2, + RmService = 3, + RmExplorer = 4, + RmConsole = 5, + RmCritical = 1000 + } + + #endregion Enums + + #region Library Imports + + #region user32.dll Imports + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + public static partial bool DestroyIcon (nint hIcon); + + [LibraryImport("User32.dll")] + public static partial int SetForegroundWindow (nint hWnd); + + [LibraryImport("user32.dll")] + public static partial long GetSystemMetricsForDpi (long index); + + [LibraryImport("user32.dll")] + public static partial long GetSystemMetrics (long index); + + [LibraryImport("user32.dll")] + public static partial short GetKeyState (int vKey); + + #endregion user32.dll Imports + + #region shell32.dll Imports + /* + UINT ExtractIconEx( + LPCTSTR lpszFile, + int nIconIndex, + HICON *phiconLarge, + HICON *phiconSmall, + UINT nIcons + ); + * */ + [LibraryImport("shell32.dll", StringMarshalling = StringMarshalling.Utf16)] + public static partial uint ExtractIconEx ( + string fileName, + int iconIndex, + out nint iconsLarge, + out nint iconsSmall, + uint numIcons + ); + + #endregion shell32.dll Imports + + #region dwmapi.dll Imports + + #region TitleBarDarkMode + [LibraryImport("dwmapi.dll")] + public static partial int DwmSetWindowAttribute (nint hwnd, int attr, ref int attrValue, int attrSize); + #endregion TitleBarDarkMode + + #endregion shell32.dll Imports + + #region rstrtmgr.dll Imports + + [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern int RmGetList ( + uint dwSessionHandle, + out uint pnProcInfoNeeded, + ref uint pnProcInfo, + [In, Out] RM_PROCESS_INFO[] rgAffectedApps, + ref uint lpdwRebootReasons); + + [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto, SetLastError = true)] + public static extern int RmRegisterResources ( + uint pSessionHandle, + uint nFiles, + string[] rgsFilenames, + uint nApplications, + [In] RM_UNIQUE_PROCESS[] rgApplications, + uint nServices, + string[] rgsServiceNames); + + [LibraryImport("rstrtmgr.dll", StringMarshalling = StringMarshalling.Utf16)] + public static partial int RmStartSession ( + out uint pSessionHandle, + int dwSessionFlags, + string strSessionKey); + + [LibraryImport("rstrtmgr.dll", StringMarshalling = StringMarshalling.Utf16)] + public static partial int RmEndSession (uint pSessionHandle); + + #endregion rstrtmgr.dll Imports + + #endregion Library Imports + + #region Helper methods + + public static Icon LoadIconFromExe (string fileName, int index) + { + nint smallIcons = new(); + nint largeIcons = new(); + int num = (int)ExtractIconEx(fileName, index, out largeIcons, out smallIcons, 1); + if (num > 0 && smallIcons != nint.Zero) + { + var icon = (Icon)Icon.FromHandle(smallIcons).Clone(); + DestroyIcon(smallIcons); + return icon; + } + if (num > 0 && largeIcons != nint.Zero) + { + var icon = (Icon)Icon.FromHandle(largeIcons).Clone(); + DestroyIcon(largeIcons); + return icon; + } + return null; + } + + public static Icon[,] ExtractIcons (string fileName) + { + var iconCount = ExtractIconEx(fileName, -1, out var largeIcon, out var smallIcon, 0); + if (iconCount <= 0) + { + return null; + } + + var result = new Icon[2, iconCount]; + + for (var i = 0; i < iconCount; ++i) + { + var num = ExtractIconEx(fileName, i, out var largeIcons, out var smallIcons, 1); + if (smallIcons != nint.Zero) + { + result[0, i] = (Icon)Icon.FromHandle(smallIcons).Clone(); + DestroyIcon(smallIcons); + } + else + { + result[0, i] = null; + } + + if (num > 0 && largeIcons != nint.Zero) + { + result[1, i] = (Icon)Icon.FromHandle(largeIcons).Clone(); + DestroyIcon(largeIcons); + } + else + { + result[1, i] = null; + } + } + + return result; + } + + public static bool UseImmersiveDarkMode (nint handle, bool enabled) + { + var attribute = DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1; + if (IsWindows10OrGreater(18985)) + { + attribute = DWMWA_USE_IMMERSIVE_DARK_MODE; + } + + var useImmersiveDarkMode = enabled ? 1 : 0; + return DwmSetWindowAttribute(handle, attribute, ref useImmersiveDarkMode, sizeof(int)) == 0; + + } + + private static bool IsWindows10OrGreater (int build = -1) + { + return Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= build; + } + + #endregion Helper methods +} \ No newline at end of file diff --git a/src/LogExpert.UI/Extensions/Utils.cs b/src/LogExpert.UI/Extensions/Utils.cs new file mode 100644 index 00000000..27d000b0 --- /dev/null +++ b/src/LogExpert.UI/Extensions/Utils.cs @@ -0,0 +1,55 @@ +using System.Runtime.Versioning; + +namespace LogExpert.UI.Extensions; + + +internal static class Utils +{ + [SupportedOSPlatform("windows")] + public static string GetWordFromPos (int xPos, string text, Graphics g, Font font) + { + var words = text.Split([' ', '.', ':', ';']); + + var index = 0; + + List crList = []; + + for (var i = 0; i < words.Length; ++i) + { + crList.Add(new CharacterRange(index, words[i].Length)); + index += words[i].Length; + } + + CharacterRange[] crArray = [.. crList]; + + StringFormat stringFormat = new(StringFormat.GenericTypographic) + { + Trimming = StringTrimming.None, + FormatFlags = StringFormatFlags.NoClip + }; + + stringFormat.SetMeasurableCharacterRanges(crArray); + + RectangleF rect = new(0, 0, 3000, 20); + Region[] stringRegions = g.MeasureCharacterRanges(text, font, rect, stringFormat); + + var found = false; + + var y = 0; + + foreach (Region regio in stringRegions) + { + if (regio.IsVisible(xPos, 3, g)) + { + found = true; + break; + } + + y++; + } + + return found + ? words[y] + : null; + } +} diff --git a/src/LogExpert.UI/Interface/ILogPaintContextUI.cs b/src/LogExpert.UI/Interface/ILogPaintContextUI.cs new file mode 100644 index 00000000..45caee8b --- /dev/null +++ b/src/LogExpert.UI/Interface/ILogPaintContextUI.cs @@ -0,0 +1,34 @@ +using LogExpert.Core.Classes.Highlight; +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; + +namespace LogExpert.UI.Interface; + +/// +/// Declares methods that are needed for drawing log lines. Used by PaintHelper. +/// +internal interface ILogPaintContextUI : ILogPaintContext +{ + #region Properties + + Font MonospacedFont { get; } // Font font = new Font("Courier New", this.Preferences.fontSize, FontStyle.Bold); + Font NormalFont { get; } + Font BoldFont { get; } + Color BookmarkColor { get; } + + #endregion + + #region Public methods + + ILogLine GetLogLine(int lineNum); + + IColumn GetCellValue(int rowIndex, int columnIndex); + + Bookmark GetBookmarkForLine(int lineNum); + + HighlightEntry FindHighlightEntry(ITextValue line, bool noWordMatches); + + IList FindHighlightMatches(ITextValue line); + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert.UI/LogExpert.UI.csproj b/src/LogExpert.UI/LogExpert.UI.csproj new file mode 100644 index 00000000..0959af4b --- /dev/null +++ b/src/LogExpert.UI/LogExpert.UI.csproj @@ -0,0 +1,27 @@ + + + + true + true + true + net8.0-windows + true + + + + + + + + Always + + + + + + + Form + + + + diff --git a/src/LogExpert.sln b/src/LogExpert.sln index c5d5aa5a..21ba9ceb 100644 --- a/src/LogExpert.sln +++ b/src/LogExpert.sln @@ -21,11 +21,14 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GlassfishColumnizer", "Glas EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FlashIconHighlighter", "FlashIconHighlighter\FlashIconHighlighter.csproj", "{F5E81EBE-3E6F-409F-B510-918E97F59072}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "WinFormsUI", "WinFormsUI\WinFormsUI.csproj", "{C75532C4-765B-418E-B09B-46D36B2ABDB1}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{DE6375A4-B4C4-4620-8FFB-B9D5A4E21144}" ProjectSection(SolutionItems) = preProject - Solution Items\AssemblyVersion.cs = Solution Items\AssemblyVersion.cs + .editorconfig = .editorconfig + Solution Items\AssemblyInfo.cs = Solution Items\AssemblyInfo.cs + Directory.Build.props = Directory.Build.props + Directory.Packages.props = Directory.Packages.props + ..\GitVersion.yml = ..\GitVersion.yml + Solution Items\usedComponents.json = Solution Items\usedComponents.json EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "JsonColumnizer", "JsonColumnizer\JsonColumnizer.csproj", "{4C899885-E361-410A-B6AC-C2F236C436FA}" @@ -57,7 +60,17 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "setup", "setup", "{C625E7C2 EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RegexColumnizer.UnitTests", "RegexColumnizer.UnitTests\RegexColumnizer.UnitTests.csproj", "{FBFB598D-B94A-4AD3-A355-0D5A618CEEE3}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogexpertgRPCService", "LogexpertgRPCService\LogexpertgRPCService.csproj", "{D31D1721-9DEA-45A4-B813-D5023B2EC2CC}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogExpert.Core", "LogExpert.Core\LogExpert.Core.csproj", "{F49C6738-3F62-4890-8FF2-1F53A0F0A2CD}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogExpert.Resources", "LogExpert.Resources\LogExpert.Resources.csproj", "{578CC5D5-1DCD-47C2-8BD3-B32C14635BEC}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogExpert.UI", "LogExpert.UI\LogExpert.UI.csproj", "{5DB0B0F8-3C3E-4805-93A3-7E69AC45CD40}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LogExpert.PluginRegistry", "PluginRegistry\LogExpert.PluginRegistry.csproj", "{E2D8E653-B7DF-4ACE-8314-8059B1E20751}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Columnizers", "Columnizers", "{02EA681E-C7D8-13C7-8484-4AC65E1B71E8}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{848C24BA-BEBA-48EC-90E6-526ECAB6BB4A}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -93,10 +106,6 @@ Global {F5E81EBE-3E6F-409F-B510-918E97F59072}.Debug|Any CPU.Build.0 = Debug|Any CPU {F5E81EBE-3E6F-409F-B510-918E97F59072}.Release|Any CPU.ActiveCfg = Release|Any CPU {F5E81EBE-3E6F-409F-B510-918E97F59072}.Release|Any CPU.Build.0 = Release|Any CPU - {C75532C4-765B-418E-B09B-46D36B2ABDB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {C75532C4-765B-418E-B09B-46D36B2ABDB1}.Debug|Any CPU.Build.0 = Debug|Any CPU - {C75532C4-765B-418E-B09B-46D36B2ABDB1}.Release|Any CPU.ActiveCfg = Release|Any CPU - {C75532C4-765B-418E-B09B-46D36B2ABDB1}.Release|Any CPU.Build.0 = Release|Any CPU {4C899885-E361-410A-B6AC-C2F236C436FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {4C899885-E361-410A-B6AC-C2F236C436FA}.Debug|Any CPU.Build.0 = Debug|Any CPU {4C899885-E361-410A-B6AC-C2F236C436FA}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -135,16 +144,38 @@ Global {FBFB598D-B94A-4AD3-A355-0D5A618CEEE3}.Debug|Any CPU.Build.0 = Debug|Any CPU {FBFB598D-B94A-4AD3-A355-0D5A618CEEE3}.Release|Any CPU.ActiveCfg = Release|Any CPU {FBFB598D-B94A-4AD3-A355-0D5A618CEEE3}.Release|Any CPU.Build.0 = Release|Any CPU - {D31D1721-9DEA-45A4-B813-D5023B2EC2CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D31D1721-9DEA-45A4-B813-D5023B2EC2CC}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D31D1721-9DEA-45A4-B813-D5023B2EC2CC}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D31D1721-9DEA-45A4-B813-D5023B2EC2CC}.Release|Any CPU.Build.0 = Release|Any CPU + {F49C6738-3F62-4890-8FF2-1F53A0F0A2CD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F49C6738-3F62-4890-8FF2-1F53A0F0A2CD}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F49C6738-3F62-4890-8FF2-1F53A0F0A2CD}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F49C6738-3F62-4890-8FF2-1F53A0F0A2CD}.Release|Any CPU.Build.0 = Release|Any CPU + {578CC5D5-1DCD-47C2-8BD3-B32C14635BEC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {578CC5D5-1DCD-47C2-8BD3-B32C14635BEC}.Debug|Any CPU.Build.0 = Debug|Any CPU + {578CC5D5-1DCD-47C2-8BD3-B32C14635BEC}.Release|Any CPU.ActiveCfg = Release|Any CPU + {578CC5D5-1DCD-47C2-8BD3-B32C14635BEC}.Release|Any CPU.Build.0 = Release|Any CPU + {5DB0B0F8-3C3E-4805-93A3-7E69AC45CD40}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {5DB0B0F8-3C3E-4805-93A3-7E69AC45CD40}.Debug|Any CPU.Build.0 = Debug|Any CPU + {5DB0B0F8-3C3E-4805-93A3-7E69AC45CD40}.Release|Any CPU.ActiveCfg = Release|Any CPU + {5DB0B0F8-3C3E-4805-93A3-7E69AC45CD40}.Release|Any CPU.Build.0 = Release|Any CPU + {E2D8E653-B7DF-4ACE-8314-8059B1E20751}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E2D8E653-B7DF-4ACE-8314-8059B1E20751}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E2D8E653-B7DF-4ACE-8314-8059B1E20751}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E2D8E653-B7DF-4ACE-8314-8059B1E20751}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution + {2563526E-4566-40CB-AA27-587B904FD25B} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {C41A517B-7502-4B17-9119-55D5716FAD65} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {43B3857D-4341-41A6-9E77-4F3BA4F2C7AB} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {4C899885-E361-410A-B6AC-C2F236C436FA} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {B5A7DFA4-48A8-4616-8008-7441699EC946} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {0DBBCBEF-4A91-4031-AEAB-B7EEE802F496} = {848C24BA-BEBA-48EC-90E6-526ECAB6BB4A} + {1FFB09A8-DAE4-4DEB-AFF6-8BAE6D01C7AC} = {848C24BA-BEBA-48EC-90E6-526ECAB6BB4A} + {003535EC-4186-4958-9DD9-C641F089AEED} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} + {B57259A3-4ED7-4F8B-A252-29E799A56B9E} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8} {C625E7C2-AF15-4C40-8C35-3E166D46F939} = {DE6375A4-B4C4-4620-8FFB-B9D5A4E21144} + {FBFB598D-B94A-4AD3-A355-0D5A618CEEE3} = {848C24BA-BEBA-48EC-90E6-526ECAB6BB4A} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {15924D5F-B90B-4BC7-9E7D-BCCB62EBABAD} diff --git a/src/LogExpert/Classes/ArgParser.cs b/src/LogExpert/Classes/ArgParser.cs deleted file mode 100644 index 3c94c115..00000000 --- a/src/LogExpert/Classes/ArgParser.cs +++ /dev/null @@ -1,154 +0,0 @@ -using System; -using System.Text; -using System.Text.RegularExpressions; -using System.Windows.Forms; -using LogExpert.Dialogs; - -namespace LogExpert.Classes -{ - internal class ArgParser - { - #region Fields - - private readonly string argLine; - - #endregion - - #region cTor - - public ArgParser(string argTemplate) - { - this.argLine = argTemplate; - } - - #endregion - - #region Public methods - - public string BuildArgs(ILogLine logLine, int lineNum, ILogFileInfo logFileInfo, Form parent) - { - StringBuilder builder = new(this.argLine); - builder.Replace("%L", "" + lineNum); - builder.Replace("%P", logFileInfo.DirectoryName); - builder.Replace("%N", logFileInfo.FileName); - builder.Replace("%F", logFileInfo.FullName); - builder.Replace("%E", Util.GetExtension(logFileInfo.FileName)); - string stripped = Util.StripExtension(logFileInfo.FileName); - builder.Replace("%M", stripped); - - builder.Replace("%URI", logFileInfo.Uri.AbsoluteUri); - string user = logFileInfo.Uri.UserInfo; - if (user.Contains(":")) - { - user = user.Substring(0, user.IndexOf(':')); - } - builder.Replace("%S", user); - builder.Replace("%R", logFileInfo.Uri.PathAndQuery); - builder.Replace("%H", logFileInfo.Uri.Host); - builder.Replace("%T", logFileInfo.Uri.Port.ToString()); - - int sPos = 0; - string reg; - string replace; - do - { - reg = GetNextGroup(builder, ref sPos); - replace = GetNextGroup(builder, ref sPos); - if (reg != null && replace != null) - { - string result = Regex.Replace(logLine.FullLine, reg, replace); - builder.Insert(sPos, result); - } - } while (replace != null); - - int i = 0; - while (i < builder.Length) - { - // ?"Pinpad-type?"(thales,dione) - if (builder[i] == '?') - { - int end = i; - string ask = "Parameter"; - if (builder[i + 1] == '"') - { - end = builder.ToString().IndexOf('"', i + 2); - if (end == -1) - { - end = builder.Length - 1; - } - ask = builder.ToString().Substring(i + 2, end - i - 2); - } - string[] values = null; - if (builder[end + 1] == '(') - { - int end2 = builder.ToString().IndexOf(')'); - if (end2 == -1) - { - end2 = builder.Length - 1; - } - string valueStr = builder.ToString().Substring(end + 2, end2 - end - 2); - values = valueStr.Split(new char[] {','}, StringSplitOptions.None); - end = end2; - } - - ParamRequesterDialog dlg = new(); - dlg.ParamName = ask; - dlg.Values = values; - DialogResult res = dlg.ShowDialog(parent); - if (res == DialogResult.OK) - { - builder.Remove(i, end - i + 1); - builder.Insert(i, dlg.ParamValue); - } - else if (res == DialogResult.Cancel || res == DialogResult.Abort) - { - return null; - } - } - ++i; - } - - return builder.ToString(); - } - - #endregion - - #region Private Methods - - private string GetNextGroup(StringBuilder builder, ref int sPos) - { - int count = 0; - int ePos; - while (sPos < builder.Length) - { - if (builder[sPos] == '{') - { - ePos = sPos + 1; - count = 1; - while (ePos < builder.Length) - { - if (builder[ePos] == '{') - { - count++; - } - if (builder[ePos] == '}') - { - count--; - } - if (count == 0) - { - string reg = builder.ToString(sPos + 1, ePos - sPos - 1); - builder.Remove(sPos, ePos - sPos + 1); - return reg; - } - ePos++; - } - } - sPos++; - } - return null; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Bookmark/BookmarkDataProvider.cs b/src/LogExpert/Classes/Bookmark/BookmarkDataProvider.cs deleted file mode 100644 index 8fb5cda4..00000000 --- a/src/LogExpert/Classes/Bookmark/BookmarkDataProvider.cs +++ /dev/null @@ -1,177 +0,0 @@ -using System; -using System.Collections.Generic; -using LogExpert.Entities; -using LogExpert.Interface; -using NLog; - -namespace LogExpert.Classes.Bookmark -{ - internal class BookmarkDataProvider : IBookmarkData - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - #endregion - - #region cTor - - internal BookmarkDataProvider() - { - BookmarkList = []; - } - - internal BookmarkDataProvider(SortedList bookmarkList) - { - BookmarkList = bookmarkList; - } - - #endregion - - #region Delegates - - public delegate void AllBookmarksRemovedEventHandler(object sender, EventArgs e); - - public delegate void BookmarkAddedEventHandler(object sender, EventArgs e); - - public delegate void BookmarkRemovedEventHandler(object sender, EventArgs e); - - #endregion - - #region Events - - public event BookmarkAddedEventHandler BookmarkAdded; - public event BookmarkRemovedEventHandler BookmarkRemoved; - public event AllBookmarksRemovedEventHandler AllBookmarksRemoved; - - #endregion - - #region Properties - - public BookmarkCollection Bookmarks => new(BookmarkList); - - internal SortedList BookmarkList { get; set; } - - #endregion - - #region Public methods - - public void ToggleBookmark(int lineNum) - { - if (IsBookmarkAtLine(lineNum)) - { - RemoveBookmarkForLine(lineNum); - } - else - { - AddBookmark(new Entities.Bookmark(lineNum)); - } - } - - public bool IsBookmarkAtLine(int lineNum) - { - return BookmarkList.ContainsKey(lineNum); - } - - public int GetBookmarkIndexForLine(int lineNum) - { - return BookmarkList.IndexOfKey(lineNum); - } - - public Entities.Bookmark GetBookmarkForLine(int lineNum) - { - return BookmarkList[lineNum]; - } - - #endregion - - #region Internals - - internal void ShiftBookmarks(int offset) - { - SortedList newBookmarkList = []; - foreach (Entities.Bookmark bookmark in BookmarkList.Values) - { - int line = bookmark.LineNum - offset; - if (line >= 0) - { - bookmark.LineNum = line; - newBookmarkList.Add(line, bookmark); - } - } - BookmarkList = newBookmarkList; - } - - internal int FindPrevBookmarkIndex(int lineNum) - { - IList values = BookmarkList.Values; - for (int i = BookmarkList.Count - 1; i >= 0; --i) - { - if (values[i].LineNum <= lineNum) - { - return i; - } - } - return BookmarkList.Count - 1; - } - - internal int FindNextBookmarkIndex(int lineNum) - { - IList values = BookmarkList.Values; - for (int i = 0; i < BookmarkList.Count; ++i) - { - if (values[i].LineNum >= lineNum) - { - return i; - } - } - return 0; - } - - internal void RemoveBookmarkForLine(int lineNum) - { - BookmarkList.Remove(lineNum); - OnBookmarkRemoved(); - } - - internal void RemoveBookmarksForLines(List lineNumList) - { - foreach (int lineNum in lineNumList) - { - BookmarkList.Remove(lineNum); - } - OnBookmarkRemoved(); - } - - - internal void AddBookmark(Entities.Bookmark bookmark) - { - BookmarkList.Add(bookmark.LineNum, bookmark); - OnBookmarkAdded(); - } - - internal void ClearAllBookmarks() - { - _logger.Debug("Removing all bookmarks"); - BookmarkList.Clear(); - OnAllBookmarksRemoved(); - } - - #endregion - - protected void OnBookmarkAdded() - { - BookmarkAdded?.Invoke(this, EventArgs.Empty); - } - - protected void OnBookmarkRemoved() - { - BookmarkRemoved?.Invoke(this, EventArgs.Empty); - } - - protected void OnAllBookmarksRemoved() - { - AllBookmarksRemoved?.Invoke(this, EventArgs.Empty); - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Bookmark/BookmarkExporter.cs b/src/LogExpert/Classes/Bookmark/BookmarkExporter.cs deleted file mode 100644 index 5ce6b0f6..00000000 --- a/src/LogExpert/Classes/Bookmark/BookmarkExporter.cs +++ /dev/null @@ -1,81 +0,0 @@ -using System.Collections.Generic; -using System.IO; - -namespace LogExpert.Classes.Bookmark -{ - internal static class BookmarkExporter - { - #region Fields - - private const string replacementForNewLine = @"\n"; - - #endregion - - #region Public methods - - public static void ExportBookmarkList(SortedList bookmarkList, string logfileName, - string fileName) - { - FileStream fs = new(fileName, FileMode.Create, FileAccess.Write); - StreamWriter writer = new(fs); - writer.WriteLine("Log file name;Line number;Comment"); - foreach (Entities.Bookmark bookmark in bookmarkList.Values) - { - string line = logfileName + ";" + bookmark.LineNum + ";" + - bookmark.Text.Replace(replacementForNewLine, @"\" + replacementForNewLine).Replace("\r\n", replacementForNewLine); - writer.WriteLine(line); - } - writer.Close(); - fs.Close(); - } - - public static void ImportBookmarkList(string logfileName, string fileName, - SortedList bookmarkList) - { - using (FileStream fs = new(fileName, FileMode.Open, FileAccess.Read)) - { - using (StreamReader reader = new(fs)) - { - if (!reader.EndOfStream) - { - reader.ReadLine(); // skip "Log file name;Line number;Comment" - } - - while (!reader.EndOfStream) - { - try - { - string line = reader.ReadLine(); - line = line.Replace(replacementForNewLine, "\r\n").Replace("\\\r\n", replacementForNewLine); - - // Line is formatted: logfileName ";" bookmark.LineNum ";" bookmark.Text; - int firstSeparator = line.IndexOf(';'); - int secondSeparator = line.IndexOf(';', firstSeparator + 1); - - string fileStr = line.Substring(0, firstSeparator); - string lineStr = line.Substring(firstSeparator + 1, secondSeparator - firstSeparator - 1); - string comment = line.Substring(secondSeparator + 1); - - int lineNum; - if (int.TryParse(lineStr, out lineNum)) - { - Entities.Bookmark bookmark = new(lineNum, comment); - bookmarkList.Add(lineNum, bookmark); - } - else - { - //!!!log error: skipping a line entry - } - } - catch - { - //!!! - } - } - } - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Bookmark/BookmarkView.cs b/src/LogExpert/Classes/Bookmark/BookmarkView.cs deleted file mode 100644 index f8d54825..00000000 --- a/src/LogExpert/Classes/Bookmark/BookmarkView.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System; -using LogExpert.Interface; - -namespace LogExpert.Classes.Bookmark -{ - internal class BookmarkView : IBookmarkView - { - #region Fields - - #endregion - - - #region IBookmarkView Member - - public void UpdateView() - { - throw new NotImplementedException(); - } - - public void BookmarkTextChanged(Entities.Bookmark bookmark) - { - throw new NotImplementedException(); - } - - public void SelectBookmark(int lineNum) - { - throw new NotImplementedException(); - } - - public bool LineColumnVisible - { - set { throw new NotImplementedException(); } - } - - public bool IsActive { get; set; } = false; - - public void SetBookmarkData(IBookmarkData bookmarkData) - { - throw new NotImplementedException(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/CmdLine.cs b/src/LogExpert/Classes/CmdLine.cs deleted file mode 100644 index f99bffb4..00000000 --- a/src/LogExpert/Classes/CmdLine.cs +++ /dev/null @@ -1,436 +0,0 @@ -using System; -using System.Collections.Generic; - -/* - * Taken from https://cmdline.codeplex.com/ - * - */ - -namespace LogExpert.Classes -{ - /// - /// Represents an error occuring during command line parsing. - /// - public class CmdLineException : Exception - { - #region cTor - - public CmdLineException(string parameter, string message) - : - base(string.Format("Syntax error of parameter -{0}: {1}", parameter, message)) - { - } - - public CmdLineException(string message) - : - base(message) - { - } - - #endregion - } - - /// - /// Represents a command line parameter. - /// Parameters are words in the command line beginning with a hyphen (-). - /// The value of the parameter is the next word in - /// - public class CmdLineParameter - { - #region Fields - - #endregion - - #region cTor - - /// - /// Creates a new instance of this class. - /// - /// Name of parameter. - /// Require that the parameter is present in the command line. - /// The explanation of the parameter to add to the help screen. - public CmdLineParameter(string name, bool required, string helpMessage) - { - Name = name; - Required = required; - Help = helpMessage; - } - - #endregion - - #region Properties - - /// - /// Returns the value of the parameter. - /// - public string Value { get; private set; } = ""; - - /// - /// Returns the help message associated with the parameter. - /// - public string Help { get; } = ""; - - /// - /// Returns true if the parameter was found in the command line. - /// - public bool Exists { get; private set; } = false; - - /// - /// Returns true if the parameter is required in the command line. - /// - public bool Required { get; } = false; - - /// - /// Returns the name of the parameter. - /// - public string Name { get; } - - #endregion - - #region Public methods - - /// - /// Sets the value of the parameter. - /// - /// A string containing a integer expression. - public virtual void SetValue(string value) - { - Value = value; - Exists = true; - } - - #endregion - } - - /// - /// Represents an integer command line parameter. - /// - public class CmdLineInt : CmdLineParameter - { - #region Fields - - private readonly int _max = int.MaxValue; - private readonly int _min = int.MinValue; - - #endregion - - #region cTor - - /// - /// Creates a new instance of this class. - /// - /// Name of parameter. - /// Require that the parameter is present in the command line. - /// The explanation of the parameter to add to the help screen. - public CmdLineInt(string name, bool required, string helpMessage) - : base(name, required, helpMessage) - { - } - - /// - /// Creates a new instance of this class. - /// - /// Name of parameter. - /// Require that the parameter is present in the command line. - /// The explanation of the parameter to add to the help screen. - /// The minimum value of the parameter. - /// The maximum valie of the parameter. - public CmdLineInt(string name, bool required, string helpMessage, int min, int max) - : base(name, required, helpMessage) - { - _min = min; - _max = max; - } - - #endregion - - #region Properties - - /// - /// Returns the current value of the parameter. - /// - new public int Value { get; private set; } - - #endregion - - #region Public methods - - /// - /// Sets the value of the parameter. - /// - /// A string containing a integer expression. - public override void SetValue(string value) - { - base.SetValue(value); - int i = 0; - try - { - i = Convert.ToInt32(value); - } - catch (Exception) - { - throw new CmdLineException(base.Name, "Value is not an integer."); - } - if (i < _min) - { - throw new CmdLineException(base.Name, string.Format("Value must be greather or equal to {0}.", _min)); - } - if (i > _max) - { - throw new CmdLineException(base.Name, string.Format("Value must be less or equal to {0}.", _max)); - } - Value = i; - } - - /// - /// A implicit converion to a int data type. - /// - /// - /// - public static implicit operator int(CmdLineInt s) - { - return s.Value; - } - - #endregion - } - - /// - /// Represents an string command line parameter. - /// - public class CmdLineString : CmdLineParameter - { - #region cTor - - public CmdLineString(string name, bool required, string helpMessage) - : base(name, required, helpMessage) - { - } - - #endregion - - #region Public methods - - public static implicit operator string(CmdLineString s) - { - return s.Value; - } - - #endregion - } - - /// - /// Provides a simple strongly typed interface to work with command line parameters. - /// - public class CmdLine - { - #region Fields - - // A private dictonary containing the parameters. - private readonly Dictionary parameters = []; - - #endregion - - #region cTor - - /// - /// Creats a new empty command line object. - /// - public CmdLine() - { - } - - #endregion - - #region Properties - - /// - /// Returns a command line parameter by the name. - /// - /// The name of the parameter (the word after the initial hyphen (-). - /// A reference to the named comman line object. - public CmdLineParameter this[string name] - { - get - { - if (!parameters.ContainsKey(name)) - { - throw new CmdLineException(name, "Not a registered parameter."); - } - return parameters[name]; - } - } - - #endregion - - #region Public methods - - /// - /// Registers a parameter to be used and adds it to the help screen. - /// - /// The parameter to add. - public void RegisterParameter(CmdLineParameter parameter) - { - if (parameters.ContainsKey(parameter.Name)) - { - throw new CmdLineException(parameter.Name, "Parameter is already registered."); - } - parameters.Add(parameter.Name, parameter); - } - - /// - /// Registers parameters to be used and adds hem to the help screen. - /// - /// The parameter to add. - public void RegisterParameter(CmdLineParameter[] parameters) - { - foreach (CmdLineParameter p in parameters) - { - RegisterParameter(p); - } - } - - - /// - /// Parses the command line and sets the value of each registered parmaters. - /// - /// The arguments array sent to main() - /// Any reminding strings after arguments has been processed. - public string[] Parse(string[] args) - { - int i = 0; - - List new_args = []; - - while (i < args.Length) - { - if (args[i].Length > 1 && args[i][0] == '-') - { - // The current string is a parameter name - string key = args[i].Substring(1, args[i].Length - 1).ToLower(); - string value = ""; - i++; - if (i < args.Length) - { - if (args[i].Length > 0 && args[i][0] == '-') - { - // The next string is a new parameter, do not nothing - } - else - { - // The next string is a value, read the value and move forward - value = args[i]; - i++; - } - } - if (!parameters.ContainsKey(key)) - { - throw new CmdLineException(key, "Parameter is not allowed."); - } - - if (parameters[key].Exists) - { - throw new CmdLineException(key, "Parameter is specified more than once."); - } - - parameters[key].SetValue(value); - } - else - { - new_args.Add(args[i]); - i++; - } - } - - - // Check that required parameters are present in the command line. - foreach (string key in parameters.Keys) - { - if (parameters[key].Required && !parameters[key].Exists) - { - throw new CmdLineException(key, "Required parameter is not found."); - } - } - - return new_args.ToArray(); - } - - /// - /// Generates the help screen. - /// - public string HelpScreen() - { - int len = 0; - foreach (string key in parameters.Keys) - { - len = Math.Max(len, key.Length); - } - - string help = "\nParameters:\n\n"; - foreach (string key in parameters.Keys) - { - string s = "-" + parameters[key].Name; - while (s.Length < len + 3) - { - s += " "; - } - s += parameters[key].Help + "\n"; - help += s; - } - return help; - } - - #endregion - } - - /// - /// Represents a CmdLine object to use with console applications. - /// The -help parameter will be registered automatically. - /// Any errors will be written to the console instead of generating exceptions. - /// - public class ConsoleCmdLine : CmdLine - { - #region cTor - - public ConsoleCmdLine() - { - base.RegisterParameter(new CmdLineString("help", false, "Prints the help screen.")); - } - - #endregion - - #region Public methods - - public new string[] Parse(string[] args) - { - string[] ret = null; - string error = ""; - try - { - ret = base.Parse(args); - } - catch (CmdLineException ex) - { - error = ex.Message; - } - - if (this["help"].Exists) - { - //foreach(string s in base.HelpScreen().Split('\n')) - // Console.WriteLine(s); - Console.WriteLine(base.HelpScreen()); - System.Environment.Exit(0); - } - - if (error != "") - { - Console.WriteLine(error); - Console.WriteLine("Use -help for more information."); - System.Environment.Exit(1); - } - return ret; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/ColumnCache.cs b/src/LogExpert/Classes/ColumnCache.cs deleted file mode 100644 index ba71a4e4..00000000 --- a/src/LogExpert/Classes/ColumnCache.cs +++ /dev/null @@ -1,40 +0,0 @@ -using LogExpert.Classes.ILogLineColumnizerCallback; -using LogExpert.Classes.Log; - -namespace LogExpert.Classes -{ - internal class ColumnCache - { - #region Fields - - private IColumnizedLogLine _cachedColumns; - private ILogLineColumnizer _lastColumnizer; - private int _lastLineNumber = -1; - - #endregion - - #region Internals - - internal IColumnizedLogLine GetColumnsForLine(LogfileReader logFileReader, int lineNumber, ILogLineColumnizer columnizer, ColumnizerCallback columnizerCallback) - { - if (_lastColumnizer != columnizer || _lastLineNumber != lineNumber && _cachedColumns != null || columnizerCallback.LineNum != lineNumber) - { - _lastColumnizer = columnizer; - _lastLineNumber = lineNumber; - ILogLine line = logFileReader.GetLogLineWithWait(lineNumber).Result; - if (line != null) - { - columnizerCallback.LineNum = lineNumber; - _cachedColumns = columnizer.SplitLine(columnizerCallback, line); - } - else - { - _cachedColumns = null; - } - } - return _cachedColumns; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Columnizer/ClfColumnizer.cs b/src/LogExpert/Classes/Columnizer/ClfColumnizer.cs deleted file mode 100644 index 20f8b4aa..00000000 --- a/src/LogExpert/Classes/Columnizer/ClfColumnizer.cs +++ /dev/null @@ -1,199 +0,0 @@ -using System; -using System.Globalization; -using System.Linq; -using System.Text.RegularExpressions; - -namespace LogExpert.Classes.Columnizer -{ - public class ClfColumnizer : ILogLineColumnizer - { - #region Fields - - private readonly Regex lineRegex = new("(.*) (-) (.*) (\\[.*\\]) (\".*\") (.*) (.*) (\".*\") (\".*\")"); - - protected CultureInfo cultureInfo = new("de-DE"); - protected int timeOffset = 0; - - #endregion - - #region cTor - - // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" - - public ClfColumnizer() - { - } - - #endregion - - #region Public methods - - public bool IsTimeshiftImplemented() - { - return true; - } - - public void SetTimeOffset(int msecOffset) - { - this.timeOffset = msecOffset; - } - - public int GetTimeOffset() - { - return this.timeOffset; - } - - public DateTime GetTimestamp(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) - { - IColumnizedLogLine cols = SplitLine(callback, line); - if (cols == null || cols.ColumnValues.Length < 8) - { - return DateTime.MinValue; - } - - if (cols.ColumnValues[2].FullValue.Length == 0) - { - return DateTime.MinValue; - } - - try - { - DateTime dateTime = DateTime.ParseExact(cols.ColumnValues[2].FullValue, "dd/MMM/yyyy:HH:mm:ss zzz", - new CultureInfo("en-US")); - return dateTime; - } - catch (Exception) - { - return DateTime.MinValue; - } - } - - public void PushValue(LogExpert.ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - if (column == 2) - { - try - { - DateTime newDateTime = - DateTime.ParseExact(value, "dd/MMM/yyyy:HH:mm:ss zzz", new CultureInfo("en-US")); - DateTime oldDateTime = - DateTime.ParseExact(oldValue, "dd/MMM/yyyy:HH:mm:ss zzz", new CultureInfo("en-US")); - long mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; - long mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - this.timeOffset = (int) (mSecsNew - mSecsOld); - } - catch (FormatException) - { - } - } - } - - public string GetName() - { - return "Webserver CLF Columnizer"; - } - - public string GetDescription() - { - return "Common Logfile Format used by webservers."; - } - - public int GetColumnCount() - { - return 8; - } - - public string[] GetColumnNames() - { - return new string[] {"IP", "User", "Date/Time", "Request", "Status", "Bytes", "Referrer", "User agent"}; - } - - public IColumnizedLogLine SplitLine(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) - { - ColumnizedLogLine cLogLine = new() - { - LogLine = line - }; - - Column[] columns = new Column[8] - { - new() {FullValue = "", Parent = cLogLine}, - new() {FullValue = "", Parent = cLogLine}, - new() {FullValue = "", Parent = cLogLine}, - new() {FullValue = "", Parent = cLogLine}, - new() {FullValue = "", Parent = cLogLine}, - new() {FullValue = "", Parent = cLogLine}, - new() {FullValue = "", Parent = cLogLine}, - new() {FullValue = "", Parent = cLogLine} - }; - - cLogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); - - string temp = line.FullLine; - if (temp.Length > 1024) - { - // spam - temp = temp.Substring(0, 1024); - columns[3].FullValue = temp; - return cLogLine; - } - // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 - // anon-212-34-174-126.suchen.de - - [08/Mar/2008:00:41:10 +0100] "GET /wiki/index.php?title=Bild:Poster_small.jpg&printable=yes&printable=yes HTTP/1.1" 304 0 "http://www.captain-kloppi.de/wiki/index.php?title=Bild:Poster_small.jpg&printable=yes" "gonzo1[P] +http://www.suchen.de/faq.html" - - if (this.lineRegex.IsMatch(temp)) - { - Match match = this.lineRegex.Match(temp); - GroupCollection groups = match.Groups; - if (groups.Count == 10) - { - columns[0].FullValue = groups[1].Value; - columns[1].FullValue = groups[3].Value; - columns[3].FullValue = groups[5].Value; - columns[4].FullValue = groups[6].Value; - columns[5].FullValue = groups[7].Value; - columns[6].FullValue = groups[8].Value; - columns[7].FullValue = groups[9].Value; - - string dateTimeStr = groups[4].Value.Substring(1, 26); - - // dirty probing of date/time format (much faster than DateTime.ParseExact() - if (dateTimeStr[2] == '/' && dateTimeStr[6] == '/' && dateTimeStr[11] == ':') - { - if (this.timeOffset != 0) - { - try - { - DateTime dateTime = DateTime.ParseExact(dateTimeStr, "dd/MMM/yyyy:HH:mm:ss zzz", - new CultureInfo("en-US")); - dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, this.timeOffset)); - string newDate = dateTime.ToString("dd/MMM/yyyy:HH:mm:ss zzz", - new CultureInfo("en-US")); - columns[2].FullValue = newDate; - } - catch (Exception) - { - columns[2].FullValue = "n/a"; - } - } - else - { - columns[2].FullValue = dateTimeStr; - } - } - else - { - columns[2].FullValue = dateTimeStr; - } - } - } - else - { - columns[3].FullValue = temp; - } - - return cLogLine; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Columnizer/ColumnizerPicker.cs b/src/LogExpert/Classes/Columnizer/ColumnizerPicker.cs deleted file mode 100644 index 4ccc4cc9..00000000 --- a/src/LogExpert/Classes/Columnizer/ColumnizerPicker.cs +++ /dev/null @@ -1,143 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using LogExpert.Config; -using LogExpert.Entities; - -namespace LogExpert.Classes.Columnizer -{ - public class ColumnizerPicker - { - public static ILogLineColumnizer FindColumnizerByName(string name, IList list) - { - foreach (ILogLineColumnizer columnizer in list) - { - if (columnizer.GetName().Equals(name)) - { - return columnizer; - } - } - return null; - } - - public static ILogLineColumnizer DecideColumnizerByName(string name, IList list) - { - foreach (ILogLineColumnizer columnizer in list) - { - if (columnizer.GetName().Equals(name)) - { - return columnizer; - } - } - - return FindColumnizer(null, null); - } - - public static ILogLineColumnizer CloneColumnizer(ILogLineColumnizer columnizer) - { - if (columnizer == null) - { - return null; - } - ConstructorInfo cti = columnizer.GetType().GetConstructor(Type.EmptyTypes); - - if (cti != null) - { - object o = cti.Invoke(new object[] { }); - if (o is IColumnizerConfigurator configurator) - { - configurator.LoadConfig(ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir); - } - return (ILogLineColumnizer)o; - } - return null; - } - - /// - /// This method implemented the "auto columnizer" feature. - /// This method should be called after each columnizer is changed to update the columizer. - /// - /// - /// - /// - /// - public static ILogLineColumnizer FindReplacementForAutoColumnizer(string fileName, - IAutoLogLineColumnizerCallback logFileReader, - ILogLineColumnizer logLineColumnizer) - { - if (logLineColumnizer == null || logLineColumnizer.GetName() == "Auto Columnizer") - { - return FindColumnizer(fileName, logFileReader); - } - return logLineColumnizer; - } - - public static ILogLineColumnizer FindBetterColumnizer(string fileName, - IAutoLogLineColumnizerCallback logFileReader, - ILogLineColumnizer logLineColumnizer) - { - var newColumnizer = FindColumnizer(fileName, logFileReader); - if (newColumnizer.GetType().Equals(logLineColumnizer.GetType())) - { - return null; - } - return newColumnizer; - } - - /// - /// This method will search all registered columnizer and return one according to the priority that returned - /// by the each columnizer. - /// - /// - /// - /// - public static ILogLineColumnizer FindColumnizer(string fileName, IAutoLogLineColumnizerCallback logFileReader) - { - if (string.IsNullOrEmpty(fileName)) - { - return new DefaultLogfileColumnizer(); - } - - List loglines = []; - - if (logFileReader != null) - { - loglines = - [ - // Sampling a few lines to select the correct columnizer - logFileReader.GetLogLine(0), - logFileReader.GetLogLine(1), - logFileReader.GetLogLine(2), - logFileReader.GetLogLine(3), - logFileReader.GetLogLine(4), - logFileReader.GetLogLine(5), - logFileReader.GetLogLine(25), - logFileReader.GetLogLine(100), - logFileReader.GetLogLine(200), - logFileReader.GetLogLine(400) - ]; - } - - var registeredColumnizer = PluginRegistry.Instance.RegisteredColumnizers; - - List> priorityListOfColumnizers = []; - - foreach (ILogLineColumnizer logLineColumnizer in registeredColumnizer) - { - Priority priority = default; - if (logLineColumnizer is IColumnizerPriority columnizerPriority) - { - priority = columnizerPriority.GetPriority(fileName, loglines); - } - - priorityListOfColumnizers.Add(new Tuple(priority, logLineColumnizer)); - } - - ILogLineColumnizer lineColumnizer = priorityListOfColumnizers.OrderByDescending(a => a.Item1).Select(a => a.Item2).First(); - - return lineColumnizer; - } - } -} diff --git a/src/LogExpert/Classes/Columnizer/SquareBracketColumnizer.cs b/src/LogExpert/Classes/Columnizer/SquareBracketColumnizer.cs deleted file mode 100644 index 6a8be193..00000000 --- a/src/LogExpert/Classes/Columnizer/SquareBracketColumnizer.cs +++ /dev/null @@ -1,321 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text.RegularExpressions; -using static LogExpert.Classes.Columnizer.TimeFormatDeterminer; - -namespace LogExpert.Classes.Columnizer -{ - public class SquareBracketColumnizer : ILogLineColumnizer, IColumnizerPriority - { - #region ILogLineColumnizer implementation - - protected int timeOffset = 0; - private TimeFormatDeterminer _timeFormatDeterminer = new(); - - // TODO: need preparing this columnizer with sample log lines before use it. - private int _columnCount = 5; - private bool _isTimeExists = false; - - public SquareBracketColumnizer() - { - } - - public SquareBracketColumnizer(int columnCount, bool isTimeExists) : this() - { - // Add message column - _columnCount = columnCount + 1; - _isTimeExists = isTimeExists; - if (_isTimeExists) - { - // Time and date - _columnCount += 2; - } - } - - public bool IsTimeshiftImplemented() - { - return true; - } - - public void SetTimeOffset(int msecOffset) - { - this.timeOffset = msecOffset; - } - - public int GetTimeOffset() - { - return this.timeOffset; - } - - public DateTime GetTimestamp(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) - { - IColumnizedLogLine cols = SplitLine(callback, line); - if (cols == null || cols.ColumnValues == null || cols.ColumnValues.Length < 2) - { - return DateTime.MinValue; - } - - if (cols.ColumnValues[0].FullValue.Length == 0 || cols.ColumnValues[1].FullValue.Length == 0) - { - return DateTime.MinValue; - } - - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); - if (formatInfo == null) - { - return DateTime.MinValue; - } - - try - { - DateTime dateTime = DateTime.ParseExact( - cols.ColumnValues[0].FullValue + " " + cols.ColumnValues[1].FullValue, formatInfo.DateTimeFormat, - formatInfo.CultureInfo); - return dateTime; - } - catch (Exception) - { - return DateTime.MinValue; - } - } - - public void PushValue(LogExpert.ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - if (column == 1) - { - try - { - FormatInfo formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); - if (formatInfo == null) - { - return; - } - - DateTime newDateTime = DateTime.ParseExact(value, formatInfo.TimeFormat, formatInfo.CultureInfo); - DateTime oldDateTime = DateTime.ParseExact(oldValue, formatInfo.TimeFormat, formatInfo.CultureInfo); - long mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; - long mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - this.timeOffset = (int) (mSecsNew - mSecsOld); - } - catch (FormatException) - { - } - } - } - - public string GetName() - { - return "Square Bracket Columnizer"; - } - - public string GetDescription() - { - return "Splits every line into n fields: Date, Time and the rest of the log message"; - } - - public int GetColumnCount() - { - return _columnCount; - } - - public string[] GetColumnNames() - { - var columnNames = new List(GetColumnCount()); - if (_isTimeExists) - { - columnNames.Add("Date"); - columnNames.Add("Time"); - } - - // TODO: Make this configurable. - if (GetColumnCount() > 3) - { - columnNames.Add("Level"); - } - - if (GetColumnCount() > 4) - { - columnNames.Add("Source"); - } - - // Last column is the message - columnNames.Add("Message"); - int i = 1; - while (columnNames.Count < GetColumnCount()) - { - columnNames.Insert(columnNames.Count - 1, "Source" + i++.ToString()); - } - - return columnNames.ToArray(); - } - - public IColumnizedLogLine SplitLine(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) - { - // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 - // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 - // 03.01.2008 14:48:00.066 - - ColumnizedLogLine clogLine = new() - { - LogLine = line - }; - - Column[] columns = new Column[] - { - new() {FullValue = "", Parent = clogLine}, - new() {FullValue = "", Parent = clogLine}, - new() {FullValue = "", Parent = clogLine}, - }; - - string temp = line.FullLine; - - if (temp.Length < 3) - { - columns[2].FullValue = temp; - return clogLine; - } - - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); - if (formatInfo == null) - { - columns[2].FullValue = temp; - SquareSplit(ref columns, temp, 0, 0, 0, clogLine); - } - else - { - int endPos = formatInfo.DateTimeFormat.Length; - int timeLen = formatInfo.TimeFormat.Length; - int dateLen = formatInfo.DateFormat.Length; - try - { - if (this.timeOffset != 0) - { - DateTime dateTime = DateTime.ParseExact(temp.Substring(0, endPos), formatInfo.DateTimeFormat, - formatInfo.CultureInfo); - dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, this.timeOffset)); - string newDate = dateTime.ToString(formatInfo.DateTimeFormat, formatInfo.CultureInfo); - - SquareSplit(ref columns, newDate, dateLen, timeLen, endPos, clogLine); - } - else - { - SquareSplit(ref columns, temp, dateLen, timeLen, endPos, clogLine); - } - } - catch (Exception) - { - columns[0].FullValue = "n/a"; - columns[1].FullValue = "n/a"; - columns[2].FullValue = temp; - } - } - - clogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); - - return clogLine; - } - - void SquareSplit(ref Column[] columns, string line, int dateLen, int timeLen, int dateTimeEndPos, ColumnizedLogLine clogLine) - { - List columnList = []; - int restColumn = _columnCount; - if (_isTimeExists) - { - columnList.Add(new Column {FullValue = line.Substring(0, dateLen), Parent = clogLine}); - columnList.Add(new Column {FullValue = line.Substring(dateLen + 1, timeLen), Parent = clogLine}); - restColumn -= 2; - } - - int nextPos = dateTimeEndPos; - - string rest = line; - - for (int i = 0; i < restColumn; i++) - { - rest = rest.Substring(nextPos); - //var fullValue = rest.Substring(0, rest.IndexOf(']')).TrimStart(new char[] {' '}).TrimEnd(new char[] { ' ' }); - var trimmed = rest.TrimStart(new char[] {' '}); - if (string.IsNullOrEmpty(trimmed) || trimmed[0] != '[' || rest.IndexOf(']') < 0 || i == restColumn - 1) - { - columnList.Add(new Column {FullValue = rest, Parent = clogLine}); - break; - } - - nextPos = rest.IndexOf(']') + 1; - var fullValue = rest.Substring(0, nextPos); - columnList.Add(new Column {FullValue = fullValue, Parent = clogLine}); - } - - while (columnList.Count < _columnCount) - { - columnList.Insert(columnList.Count - 1, new Column {FullValue = "", Parent = clogLine}); - } - - columns = columnList.ToArray(); - } - - public Priority GetPriority(string fileName, IEnumerable samples) - { - Priority result = Priority.NotSupport; - TimeFormatDeterminer timeDeterminer = new(); - int timeStampExistsCount = 0; - int bracketsExistsCount = 0; - int maxBracketNumbers = 1; - - foreach (var logline in samples) - { - string line = logline?.FullLine; - if (string.IsNullOrEmpty(line)) - { - continue; - } - - int bracketNumbers = 1; - if (null != timeDeterminer.DetermineDateTimeFormatInfo(line)) - { - timeStampExistsCount++; - } - else - { - timeStampExistsCount--; - } - - string noSpaceLine = line.Replace(" ", string.Empty); - if (noSpaceLine.IndexOf('[') >= 0 && noSpaceLine.IndexOf(']') >= 0 - && noSpaceLine.IndexOf('[') < noSpaceLine.IndexOf(']')) - { - bracketNumbers += Regex.Matches(noSpaceLine, @"\]\[").Count; - bracketsExistsCount++; - } - else - { - bracketsExistsCount--; - } - - maxBracketNumbers = Math.Max(bracketNumbers, maxBracketNumbers); - } - - // Add message - _columnCount = maxBracketNumbers + 1; - _isTimeExists = timeStampExistsCount > 0; - if (_isTimeExists) - { - _columnCount += 2; - } - - if (maxBracketNumbers > 1) - { - result = Priority.WellSupport; - if (bracketsExistsCount > 0) - { - result = Priority.PerfectlySupport; - } - } - - return result; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Columnizer/TimeFormatDeterminer.cs b/src/LogExpert/Classes/Columnizer/TimeFormatDeterminer.cs deleted file mode 100644 index 8a833047..00000000 --- a/src/LogExpert/Classes/Columnizer/TimeFormatDeterminer.cs +++ /dev/null @@ -1,242 +0,0 @@ -using System.Globalization; - -namespace LogExpert.Classes.Columnizer -{ - internal class TimeFormatDeterminer - { - #region FormatInfo helper class - - public class FormatInfo - { - #region cTor - - public FormatInfo(string dateFormat, string timeFormat, CultureInfo cultureInfo) - { - DateFormat = dateFormat; - TimeFormat = timeFormat; - CultureInfo = cultureInfo; - } - - #endregion - - #region Properties - - public string DateFormat { get; } - - public string TimeFormat { get; } - - public CultureInfo CultureInfo { get; } - - public string DateTimeFormat - { - get { return DateFormat + " " + TimeFormat; } - } - - public bool IgnoreFirstChar { get; set; } - - #endregion - } - - #endregion - - protected FormatInfo formatInfo1 = new("dd.MM.yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo2 = new("dd.MM.yyyy", "HH:mm:ss", new CultureInfo("de-DE")); - protected FormatInfo formatInfo3 = new("yyyy/MM/dd", "HH:mm:ss.fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo4 = new("yyyy/MM/dd", "HH:mm:ss", new CultureInfo("en-US")); - protected FormatInfo formatInfo5 = new("yyyy.MM.dd", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo6 = new("yyyy.MM.dd", "HH:mm:ss", new CultureInfo("de-DE")); - protected FormatInfo formatInfo7 = new("dd.MM.yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo8 = new("yyyy/MM/dd", "HH:mm:ss,fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo9 = new("yyyy.MM.dd", "HH:mm:ss,fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo10 = new("yyyy-MM-dd", "HH:mm:ss.fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo11 = new("yyyy-MM-dd", "HH:mm:ss,fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo12 = new("yyyy-MM-dd", "HH:mm:ss", new CultureInfo("en-US")); - protected FormatInfo formatInfo13 = new("dd MMM yyyy", "HH:mm:ss,fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo14 = new("dd MMM yyyy", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo15 = new("dd MMM yyyy", "HH:mm:ss", new CultureInfo("de-DE")); - protected FormatInfo formatInfo16 = new("dd.MM.yy", "HH:mm:ss.fff", new CultureInfo("de-DE")); - protected FormatInfo formatInfo17 = new("yyyy-MM-dd", "HH:mm:ss:ffff", new CultureInfo("en-US")); - protected FormatInfo formatInfo18 = new("dd/MM/yyyy", "HH:mm:ss.fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo19 = new("dd/MM/yyyy", "HH:mm:ss:fff", new CultureInfo("en-US")); - protected FormatInfo formatInfo20 = new("yyyy-MM-dd", "HH:mm:ss.ffff", new CultureInfo("en-US")); - protected FormatInfo formatInfo21 = new("yyyy-MM-dd", "HH:mm:ss,ffff", new CultureInfo("en-US")); - - - public FormatInfo DetermineDateTimeFormatInfo(string line) - { - if (line.Length < 21) - { - return null; - } - - string temp = line; - bool ignoreFirst = false; - - // determine if string starts with bracket and remove it - if (temp[0] == '[' || temp[0] == '(' || temp[0] == '{') - { - temp = temp.Substring(1); - ignoreFirst = true; - - } - - // dirty hardcoded probing of date/time format (much faster than DateTime.ParseExact() - if (temp[2] == '.' && temp[5] == '.' && temp[13] == ':' && temp[16] == ':') - { - if (temp[19] == '.') - { - formatInfo1.IgnoreFirstChar = ignoreFirst; - return formatInfo1; - } - else if (temp[19] == ',') - { - formatInfo7.IgnoreFirstChar = ignoreFirst; - return formatInfo7; - } - else - { - formatInfo2.IgnoreFirstChar = ignoreFirst; - return formatInfo2; - } - } - else if (temp[2] == '/' && temp[5] == '/' && temp[13] == ':' && temp[16] == ':') - { - if (temp[19] == '.') - { - formatInfo18.IgnoreFirstChar = ignoreFirst; - return formatInfo18; - } - else if (temp[19] == ':') - { - formatInfo19.IgnoreFirstChar = ignoreFirst; - return formatInfo19; - } - } - else if (temp[4] == '/' && temp[7] == '/' && temp[13] == ':' && temp[16] == ':') - { - if (temp[19] == '.') - { - formatInfo3.IgnoreFirstChar = ignoreFirst; - return formatInfo3; - } - else if (temp[19] == ',') - { - formatInfo8.IgnoreFirstChar = ignoreFirst; - return formatInfo8; - } - else - { - formatInfo4.IgnoreFirstChar = ignoreFirst; - return formatInfo4; - } - } - else if (temp[4] == '.' && temp[7] == '.' && temp[13] == ':' && temp[16] == ':') - { - if (temp[19] == '.') - { - formatInfo5.IgnoreFirstChar = ignoreFirst; - return formatInfo5; - } - else if (temp[19] == ',') - { - formatInfo9.IgnoreFirstChar = ignoreFirst; - return formatInfo9; - } - else - { - formatInfo6.IgnoreFirstChar = ignoreFirst; - return formatInfo6; - } - } - else if (temp[4] == '-' && temp[7] == '-' && temp[13] == ':' && temp[16] == ':') - { - if (temp[19] == '.') - { - if (temp.Length > 23 && char.IsDigit(temp[23])) - { - formatInfo20.IgnoreFirstChar = ignoreFirst; - return formatInfo20; - } - else - { - formatInfo10.IgnoreFirstChar = ignoreFirst; - return formatInfo10; - } - } - else if (temp[19] == ',') - { - if (temp.Length > 23 && char.IsDigit(temp[23])) - { - formatInfo21.IgnoreFirstChar = ignoreFirst; - return formatInfo21; - } - else - { - formatInfo11.IgnoreFirstChar = ignoreFirst; - return formatInfo11; - } - } - else if (temp[19] == ':') - { - formatInfo17.IgnoreFirstChar = ignoreFirst; - return formatInfo17; - } - else - { - formatInfo12.IgnoreFirstChar = ignoreFirst; - return formatInfo12; - } - } - else if (temp[2] == ' ' && temp[6] == ' ' && temp[14] == ':' && temp[17] == ':') - { - if (temp[20] == ',') - { - formatInfo13.IgnoreFirstChar = ignoreFirst; - return formatInfo13; - } - else if (temp[20] == '.') - { - formatInfo14.IgnoreFirstChar = ignoreFirst; - return formatInfo14; - } - else - { - formatInfo15.IgnoreFirstChar = ignoreFirst; - return formatInfo15; - } - } - //dd.MM.yy HH:mm:ss.fff - else if (temp[2] == '.' && temp[5] == '.' && temp[11] == ':' && temp[14] == ':' && temp[17] == '.') - { - formatInfo16.IgnoreFirstChar = ignoreFirst; - return formatInfo16; - } - - return null; - } - - public FormatInfo DetermineTimeFormatInfo(string field) - { - // dirty hardcoded probing of time format (much faster than DateTime.ParseExact() - if (field[2] == ':' && field[5] == ':') - { - if (field.Length > 8) - { - if (field[8] == '.') - { - return formatInfo1; - } - else if (field[8] == ',') - { - return formatInfo7; - } - } - else - { - return formatInfo2; - } - } - return null; - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Columnizer/TimestampColumnizer.cs b/src/LogExpert/Classes/Columnizer/TimestampColumnizer.cs deleted file mode 100644 index f7ed13b6..00000000 --- a/src/LogExpert/Classes/Columnizer/TimestampColumnizer.cs +++ /dev/null @@ -1,220 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; - -namespace LogExpert.Classes.Columnizer -{ - using static TimeFormatDeterminer; - - public class TimestampColumnizer : ILogLineColumnizer, IColumnizerPriority - { - - #region ILogLineColumnizer implementation - - protected int timeOffset = 0; - private TimeFormatDeterminer _timeFormatDeterminer = new(); - - public bool IsTimeshiftImplemented() - { - return true; - } - - public void SetTimeOffset(int msecOffset) - { - this.timeOffset = msecOffset; - } - - public int GetTimeOffset() - { - return this.timeOffset; - } - - - public DateTime GetTimestamp(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) - { - IColumnizedLogLine cols = SplitLine(callback, line); - if (cols == null || cols.ColumnValues == null || cols.ColumnValues.Length < 2) - { - return DateTime.MinValue; - } - if (cols.ColumnValues[0].FullValue.Length == 0 || cols.ColumnValues[1].FullValue.Length == 0) - { - return DateTime.MinValue; - } - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(line.FullLine); - if (formatInfo == null) - { - return DateTime.MinValue; - } - - try - { - DateTime dateTime = DateTime.ParseExact( - cols.ColumnValues[0].FullValue + " " + cols.ColumnValues[1].FullValue, formatInfo.DateTimeFormat, - formatInfo.CultureInfo); - return dateTime; - } - catch (Exception) - { - return DateTime.MinValue; - } - } - - - public void PushValue(LogExpert.ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - if (column == 1) - { - try - { - FormatInfo formatInfo = _timeFormatDeterminer.DetermineTimeFormatInfo(oldValue); - if (formatInfo == null) - { - return; - } - DateTime newDateTime = DateTime.ParseExact(value, formatInfo.TimeFormat, formatInfo.CultureInfo); - DateTime oldDateTime = DateTime.ParseExact(oldValue, formatInfo.TimeFormat, formatInfo.CultureInfo); - long mSecsOld = oldDateTime.Ticks / TimeSpan.TicksPerMillisecond; - long mSecsNew = newDateTime.Ticks / TimeSpan.TicksPerMillisecond; - this.timeOffset = (int) (mSecsNew - mSecsOld); - } - catch (FormatException) - { - } - } - } - - public string GetName() - { - return "Timestamp Columnizer"; - } - - public string GetDescription() - { - return "Splits every line into 3 fields: Date, Time and the rest of the log message"; - } - - public int GetColumnCount() - { - return 3; - } - - public string[] GetColumnNames() - { - return new string[] {"Date", "Time", "Message"}; - } - - public IColumnizedLogLine SplitLine(LogExpert.ILogLineColumnizerCallback callback, ILogLine line) - { - // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 - // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789 - // 03.01.2008 14:48:00.066 - - ColumnizedLogLine clogLine = new(); - clogLine.LogLine = line; - - Column[] columns = new Column[3] - { - new() {FullValue = "", Parent = clogLine}, - new() {FullValue = "", Parent = clogLine}, - new() {FullValue = "", Parent = clogLine}, - }; - - clogLine.ColumnValues = columns.Select(a => a as IColumn).ToArray(); - - string temp = line.FullLine; - - FormatInfo formatInfo = _timeFormatDeterminer.DetermineDateTimeFormatInfo(temp); - if (formatInfo == null) - { - columns[2].FullValue = temp; - return clogLine; - } - int endPos = formatInfo.DateTimeFormat.Length; - int timeLen = formatInfo.TimeFormat.Length; - int dateLen = formatInfo.DateFormat.Length; - try - { - if (this.timeOffset != 0) - { - if (formatInfo.IgnoreFirstChar) - { - // First character is a bracket and should be ignored - DateTime dateTime = DateTime.ParseExact(temp.Substring(1, endPos), formatInfo.DateTimeFormat, - formatInfo.CultureInfo); - dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, this.timeOffset)); - string newDate = dateTime.ToString(formatInfo.DateTimeFormat, formatInfo.CultureInfo); - columns[0].FullValue = newDate.Substring(0, dateLen); // date - columns[1].FullValue = newDate.Substring(dateLen + 1, timeLen); // time - columns[2].FullValue = temp.Substring(endPos + 2); // rest of line - } - else - { - DateTime dateTime = DateTime.ParseExact(temp.Substring(0, endPos), formatInfo.DateTimeFormat, - formatInfo.CultureInfo); - dateTime = dateTime.Add(new TimeSpan(0, 0, 0, 0, this.timeOffset)); - string newDate = dateTime.ToString(formatInfo.DateTimeFormat, formatInfo.CultureInfo); - columns[0].FullValue = newDate.Substring(0, dateLen); // date - columns[1].FullValue = newDate.Substring(dateLen + 1, timeLen); // time - columns[2].FullValue = temp.Substring(endPos); // rest of line - } - } - else - { - if (formatInfo.IgnoreFirstChar) - { - // First character is a bracket and should be ignored - columns[0].FullValue = temp.Substring(1, dateLen); // date - columns[1].FullValue = temp.Substring(dateLen + 2, timeLen); // time - columns[2].FullValue = temp.Substring(endPos + 2); // rest of line - } - else - { - columns[0].FullValue = temp.Substring(0, dateLen); // date - columns[1].FullValue = temp.Substring(dateLen + 1, timeLen); // time - columns[2].FullValue = temp.Substring(endPos); // rest of line - } - } - } - catch (Exception) - { - columns[0].FullValue = "n/a"; - columns[1].FullValue = "n/a"; - columns[2].FullValue = temp; - } - return clogLine; - } - - public Priority GetPriority(string fileName, IEnumerable samples) - { - Priority result = Priority.NotSupport; - - int timeStampCount = 0; - foreach (var line in samples) - { - if (line == null || string.IsNullOrEmpty(line.FullLine)) - { - continue; - } - var timeDeterminer = new TimeFormatDeterminer(); - if (null != timeDeterminer.DetermineDateTimeFormatInfo(line.FullLine)) - { - timeStampCount++; - } - else - { - timeStampCount--; - } - } - - if (timeStampCount > 0) - { - result = Priority.WellSupport; - } - - return result; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/CommandLine/CmdLine.cs b/src/LogExpert/Classes/CommandLine/CmdLine.cs new file mode 100644 index 00000000..a269f214 --- /dev/null +++ b/src/LogExpert/Classes/CommandLine/CmdLine.cs @@ -0,0 +1,194 @@ +/* + * Taken from https://cmdline.codeplex.com/ + * + */ + +//TODO: Replace with https://github.com/commandlineparser/commandline +//TODO: or with this https://github.com/natemcmaster/CommandLineUtils +namespace LogExpert.Classes.CommandLine; + +/// +/// Represents an string command line parameter. +/// +public class CmdLineString (string name, bool required, string helpMessage) : CmdLineParameter(name, required, helpMessage) +{ + + #region Public methods + + public static implicit operator string (CmdLineString s) + { + ArgumentNullException.ThrowIfNull(s, nameof(s)); + return s.Value; + } + + public override string ToString () + { + return Value; + } + + #endregion +} + +/// +/// Provides a simple strongly typed interface to work with command line parameters. +/// +public class CmdLine +{ + #region Fields + + // A private dictonary containing the parameters. + private readonly Dictionary parameters = []; + + #endregion + + #region cTor + + /// + /// Creats a new empty command line object. + /// + public CmdLine() + { + } + + #endregion + + #region Properties + + /// + /// Returns a command line parameter by the name. + /// + /// The name of the parameter (the word after the initial hyphen (-). + /// A reference to the named comman line object. + public CmdLineParameter this[string name] + { + get + { + if (parameters.TryGetValue(name, out CmdLineParameter value) == false) + { + throw new CmdLineException(name, "Not a registered parameter."); + } + return value; + } + } + + #endregion + + #region Public methods + + /// + /// Registers a parameter to be used and adds it to the help screen. + /// + /// The parameter to add. + public void RegisterParameter(CmdLineParameter parameter) + { + if (parameters.ContainsKey(parameter.Name)) + { + throw new CmdLineException(parameter.Name, "Parameter is already registered."); + } + parameters.Add(parameter.Name, parameter); + } + + /// + /// Registers parameters to be used and adds hem to the help screen. + /// + /// The parameter to add. + public void RegisterParameter(CmdLineParameter[] parameters) + { + foreach (CmdLineParameter p in parameters) + { + RegisterParameter(p); + } + } + + + /// + /// Parses the command line and sets the value of each registered parmaters. + /// + /// The arguments array sent to main() + /// Any reminding strings after arguments has been processed. + public string[] Parse(string[] args) + { + var i = 0; + + List new_args = []; + + while (i < args.Length) + { + if (args[i].Length > 1 && args[i][0] == '-') + { + // The current string is a parameter name + var key = args[i][1..].ToLower(); + var argsValue = string.Empty; + i++; + if (i < args.Length) + { + if (args[i].Length > 0 && args[i][0] == '-') + { + // The next string is a new parameter, do not nothing + } + else + { + // The next string is a value, read the value and move forward + argsValue = args[i]; + i++; + } + } + if (parameters.TryGetValue(key, out CmdLineParameter cmdLineParameter) == false) + { + throw new CmdLineException(key, "Parameter is not allowed."); + } + + if (cmdLineParameter.Exists) + { + throw new CmdLineException(key, "Parameter is specified more than once."); + } + + cmdLineParameter.SetValue(argsValue); + } + else + { + new_args.Add(args[i]); + i++; + } + } + + + // Check that required parameters are present in the command line. + foreach (var key in parameters.Keys) + { + if (parameters[key].Required && parameters[key].Exists == false) + { + throw new CmdLineException(key, "Required parameter is not found."); + } + } + + return new_args.ToArray(); + } + + /// + /// Generates the help screen. + /// + public string HelpScreen() + { + var len = 0; + foreach (var key in parameters.Keys) + { + len = Math.Max(len, key.Length); + } + + var help = "\nParameters:\n\n"; + foreach (var key in parameters.Keys) + { + var s = "-" + parameters[key].Name; + while (s.Length < len + 3) + { + s += " "; + } + s += parameters[key].Help + "\n"; + help += s; + } + return help; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Classes/CommandLine/CmdLineException.cs b/src/LogExpert/Classes/CommandLine/CmdLineException.cs new file mode 100644 index 00000000..01e67c7d --- /dev/null +++ b/src/LogExpert/Classes/CommandLine/CmdLineException.cs @@ -0,0 +1,34 @@ +/* + * Taken from https://cmdline.codeplex.com/ + * + */ + +//TODO: Replace with https://github.com/commandlineparser/commandline +//TODO: or with this https://github.com/natemcmaster/CommandLineUtils +namespace LogExpert.Classes.CommandLine; + +/// +/// Represents an error occuring during command line parsing. +/// +public class CmdLineException : Exception +{ + #region cTor + + public CmdLineException (string parameter, string message) : base($"Syntax error of parameter -{parameter}: {message}") + { + } + + public CmdLineException (string message) : base(message) + { + } + + public CmdLineException () + { + } + + public CmdLineException (string message, Exception innerException) : base(message, innerException) + { + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Classes/CommandLine/CmdLineInt.cs b/src/LogExpert/Classes/CommandLine/CmdLineInt.cs new file mode 100644 index 00000000..c9bfead4 --- /dev/null +++ b/src/LogExpert/Classes/CommandLine/CmdLineInt.cs @@ -0,0 +1,103 @@ +/* + * Taken from https://cmdline.codeplex.com/ + * + */ + +//TODO: Replace with https://github.com/commandlineparser/commandline +//TODO: or with this https://github.com/natemcmaster/CommandLineUtils +namespace LogExpert.Classes.CommandLine; + +/// +/// Represents an integer command line parameter. +/// +public class CmdLineInt : CmdLineParameter +{ + #region Fields + + private readonly int _max; + private readonly int _min; + + #endregion + + #region cTor + + /// + /// Creates a new instance of this class. + /// + /// Name of parameter. + /// Require that the parameter is present in the command line. + /// The explanation of the parameter to add to the help screen. + public CmdLineInt (string name, bool required, string helpMessage) + : base(name, required, helpMessage) + { + _max = int.MaxValue; + _min = int.MinValue; + } + + /// + /// Creates a new instance of this class. + /// + /// Name of parameter. + /// Require that the parameter is present in the command line. + /// The explanation of the parameter to add to the help screen. + /// The minimum value of the parameter. + /// The maximum valie of the parameter. + public CmdLineInt (string name, bool required, string helpMessage, int min, int max) + : base(name, required, helpMessage) + { + _max = min; + _max = max; + } + + #endregion + + #region Properties + + /// + /// Returns the current value of the parameter. + /// + public new int Value { get; private set; } + + #endregion + + #region Public methods + + /// + /// Sets the value of the parameter. + /// + /// A string containing a integer expression. + public override void SetValue (string value) + { + base.SetValue(value); + int i; + try + { + i = Convert.ToInt32(value); + } + catch (Exception) + { + throw new CmdLineException(Name, "Value is not an integer."); + } + + if (i < _min) + { + throw new CmdLineException(Name, $"Value must be greather or equal to {_min}."); + } + + if (i > _max) + { + throw new CmdLineException(Name, $"Value must be less or equal to {_max}."); + } + + Value = i; + } + + /// + /// A implicit converion to a int data type. + /// + /// + /// + public static implicit operator int (CmdLineInt s) => s.Value; + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Classes/CommandLine/CmdLineParameter.cs b/src/LogExpert/Classes/CommandLine/CmdLineParameter.cs new file mode 100644 index 00000000..5143ead3 --- /dev/null +++ b/src/LogExpert/Classes/CommandLine/CmdLineParameter.cs @@ -0,0 +1,65 @@ +/* + * Taken from https://cmdline.codeplex.com/ + * + */ + +//TODO: Replace with https://github.com/commandlineparser/commandline +//TODO: or with this https://github.com/natemcmaster/CommandLineUtils +namespace LogExpert.Classes.CommandLine; + +/// +/// Represents a command line parameter. +/// Parameters are words in the command line beginning with a hyphen (-). +/// The value of the parameter is the next word in +/// +/// +/// Creates a new instance of this class. +/// +/// Name of parameter. +/// Require that the parameter is present in the command line. +/// The explanation of the parameter to add to the help screen. +public class CmdLineParameter(string name, bool required, string helpMessage) +{ + #region Properties + + /// + /// Returns the value of the parameter. + /// + public string Value { get; private set; } = ""; + + /// + /// Returns the help message associated with the parameter. + /// + public string Help { get; } = helpMessage; + + /// + /// Returns true if the parameter was found in the command line. + /// + public bool Exists { get; private set; } + + /// + /// Returns true if the parameter is required in the command line. + /// + public bool Required { get; } = required; + + /// + /// Returns the name of the parameter. + /// + public string Name { get; } = name; + + #endregion + + #region Public methods + + /// + /// Sets the value of the parameter. + /// + /// A string containing a integer expression. + public virtual void SetValue(string value) + { + Value = value; + Exists = true; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Classes/CommandLine/ConsoleCmdLine.cs b/src/LogExpert/Classes/CommandLine/ConsoleCmdLine.cs new file mode 100644 index 00000000..408831e5 --- /dev/null +++ b/src/LogExpert/Classes/CommandLine/ConsoleCmdLine.cs @@ -0,0 +1,60 @@ +/* + * Taken from https://cmdline.codeplex.com/ + * + */ + +//TODO: Replace with https://github.com/commandlineparser/commandline +//TODO: or with this https://github.com/natemcmaster/CommandLineUtils +namespace LogExpert.Classes.CommandLine; + +/// +/// Represents a CmdLine object to use with console applications. +/// The -help parameter will be registered automatically. +/// Any errors will be written to the console instead of generating exceptions. +/// +public class ConsoleCmdLine : CmdLine +{ + #region cTor + + public ConsoleCmdLine() + { + RegisterParameter(new CmdLineString("help", false, "Prints the help screen.")); + } + + #endregion + + #region Public methods + + public new string[] Parse(string[] args) + { + string[] ret = []; + + var error = string.Empty; + + try + { + ret = base.Parse(args); + } + catch (CmdLineException ex) + { + error = ex.Message; + } + + if (this["help"].Exists) + { + Console.WriteLine(HelpScreen()); + Environment.Exit(0); + } + + if (error != string.Empty) + { + Console.WriteLine(error); + Console.WriteLine("Use -help for more information."); + Environment.Exit(1); + } + + return ret; + } + + #endregion +} \ No newline at end of file diff --git a/src/LogExpert/Classes/DateTimeParser/DateFormatPartAdjuster.cs b/src/LogExpert/Classes/DateTimeParser/DateFormatPartAdjuster.cs deleted file mode 100644 index c803ea76..00000000 --- a/src/LogExpert/Classes/DateTimeParser/DateFormatPartAdjuster.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace LogExpert.Classes.DateTimeParser -{ - // Ensures we have constant width (number of characters) date formats - public static class DateFormatPartAdjuster - { - private static readonly IDictionary _dateTimePartReplacements = new Dictionary(StringComparer.OrdinalIgnoreCase) - { - ["y"] = "yyy", - ["yyy"] = "yyyy", - ["m"] = "mm", - ["d"] = "dd", - ["h"] = "hh", - ["s"] = "ss" - }; - - public static string AdjustDateTimeFormatPart(string part) - { - if (!_dateTimePartReplacements.TryGetValue(part, out string adjustedPart)) - { - return part; - } - - if (char.IsUpper(part[0])) - { - return adjustedPart.ToUpper(); - } - else - { - return adjustedPart.ToLower(); - } - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/DateTimeParser/Parser.cs b/src/LogExpert/Classes/DateTimeParser/Parser.cs deleted file mode 100644 index 11346954..00000000 --- a/src/LogExpert/Classes/DateTimeParser/Parser.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System.Collections.Generic; -using System.Runtime.CompilerServices; - -namespace LogExpert.Classes.DateTimeParser -{ - public static class Parser - { - public static List
ParseSections(string formatString, out bool syntaxError) - { - var tokenizer = new Tokenizer(formatString); - var sections = new List
(); - syntaxError = false; - while (true) - { - var section = ParseSection(tokenizer, sections.Count, out var sectionSyntaxError); - - if (sectionSyntaxError) - { - syntaxError = true; - } - - if (section == null) - { - break; - } - - sections.Add(section); - } - - return sections; - } - - private static Section ParseSection(Tokenizer reader, int index, out bool syntaxError) - { - bool hasDateParts = false; - string token; - List tokens = []; - - while ((token = ReadToken(reader, out syntaxError)) != null) - { - if (token == ";") - { - break; - } - - if (Token.IsDatePart(token)) - { - hasDateParts |= true; - tokens.Add(token); - } - else - { - tokens.Add(token); - } - } - - if (syntaxError || tokens.Count == 0) - { - return null; - } - - List generalTextDateDuration = null; - - if (hasDateParts) - { - ParseMilliseconds(tokens, out generalTextDateDuration); - } - else - { - // Unable to parse format string - syntaxError = true; - return null; - } - - return new Section() - { - SectionIndex = index, - GeneralTextDateDurationParts = generalTextDateDuration - }; - } - - private static void ParseMilliseconds(List tokens, out List result) - { - // if tokens form .0 through .000.., combine to single subsecond token - result = []; - for (var i = 0; i < tokens.Count; i++) - { - var token = tokens[i]; - if (token == ".") - { - var zeros = 0; - while (i + 1 < tokens.Count && tokens[i + 1] == "0") - { - i++; - zeros++; - } - - if (zeros > 0) - { - result.Add("." + new string('0', zeros)); - } - else - { - result.Add("."); - } - } - else - { - result.Add(token); - } - } - } - - private static string ReadToken(Tokenizer reader, out bool syntaxError) - { - var offset = reader.Position; - if (ReadLiteral(reader)) - { - syntaxError = false; - var length = reader.Position - offset; - return reader.Substring(offset, length); - } - - if ( - // Symbols - reader.ReadOneOf("#?,!&%+-$€£0123456789{}():;/.@ ") || - - // Date - reader.ReadString("tt", true) || //AM / PM - reader.ReadOneOrMore('y') || - reader.ReadOneOrMore('Y') || - reader.ReadOneOrMore('m') || - reader.ReadOneOrMore('M') || - reader.ReadOneOrMore('d') || - reader.ReadOneOrMore('D') || - reader.ReadOneOrMore('h') || - reader.ReadOneOrMore('H') || - reader.ReadOneOrMore('s') || - reader.ReadOneOrMore('S') || - //Latin Date String: (a.C.n. ante Christum natum) - reader.ReadString("gg")) - { - syntaxError = false; - var length = reader.Position - offset; - return reader.Substring(offset, length); - } - - // Symbols - - syntaxError = reader.Position < reader.Length; - return null; - } - - private static bool ReadLiteral(Tokenizer reader) - { - if (reader.Peek() == '\\' || reader.Peek() == '*' || reader.Peek() == '_') - { - reader.Advance(2); - return true; - } - - if (reader.ReadEnclosed('"', '"')) - { - return true; - } - - if (reader.ReadEnclosed('\'', '\'')) - { - return true; - } - - return false; - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/DateTimeParser/Section.cs b/src/LogExpert/Classes/DateTimeParser/Section.cs deleted file mode 100644 index de17bd55..00000000 --- a/src/LogExpert/Classes/DateTimeParser/Section.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.Collections.Generic; - -namespace LogExpert.Classes.DateTimeParser -{ - public class Section - { - public int SectionIndex { get; set; } - - public List GeneralTextDateDurationParts { get; set; } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/DateTimeParser/Token.cs b/src/LogExpert/Classes/DateTimeParser/Token.cs deleted file mode 100644 index bf9794ce..00000000 --- a/src/LogExpert/Classes/DateTimeParser/Token.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace LogExpert.Classes.DateTimeParser -{ - public static class Token - { - public static bool IsDatePart(string token) - { - return - token.StartsWith("y", StringComparison.OrdinalIgnoreCase) || - token.StartsWith("m", StringComparison.OrdinalIgnoreCase) || - token.StartsWith("d", StringComparison.OrdinalIgnoreCase) || - token.StartsWith("s", StringComparison.OrdinalIgnoreCase) || - token.StartsWith("h", StringComparison.OrdinalIgnoreCase) || - string.Compare(token, "tt", StringComparison.OrdinalIgnoreCase) == 0; - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/DateTimeParser/Tokenizer.cs b/src/LogExpert/Classes/DateTimeParser/Tokenizer.cs deleted file mode 100644 index 39f5c9a2..00000000 --- a/src/LogExpert/Classes/DateTimeParser/Tokenizer.cs +++ /dev/null @@ -1,141 +0,0 @@ -using System; - -namespace LogExpert.Classes.DateTimeParser -{ - internal class Tokenizer - { - private string formatString; - private int formatStringPosition = 0; - - public Tokenizer(string fmt) - { - formatString = fmt; - } - - public int Position => formatStringPosition; - - public int Length => formatString.Length; - - public string Substring(int startIndex, int length) - { - return formatString.Substring(startIndex, length); - } - - public int Peek(int offset = 0) - { - if (formatStringPosition + offset >= formatString.Length) - { - return -1; - } - - return formatString[formatStringPosition + offset]; - } - - public int PeekUntil(int startOffset, int until) - { - int offset = startOffset; - while (true) - { - var c = Peek(offset++); - if (c == -1) - { - break; - } - - if (c == until) - { - return offset - startOffset; - } - } - return 0; - } - - public bool PeekOneOf(int offset, string s) - { - foreach (var c in s) - { - if (Peek(offset) == c) - { - return true; - } - } - return false; - } - - public void Advance(int characters = 1) - { - formatStringPosition = Math.Min(formatStringPosition + characters, formatString.Length); - } - - public bool ReadOneOrMore(int c) - { - if (Peek() != c) - { - return false; - } - - while (Peek() == c) - { - Advance(); - } - - return true; - } - - public bool ReadOneOf(string s) - { - if (PeekOneOf(0, s)) - { - Advance(); - return true; - } - return false; - } - - public bool ReadString(string s, bool ignoreCase = false) - { - if (formatStringPosition + s.Length > formatString.Length) - { - return false; - } - - for (var i = 0; i < s.Length; i++) - { - var c1 = s[i]; - var c2 = (char)Peek(i); - if (ignoreCase) - { - if (char.ToLower(c1) != char.ToLower(c2)) - { - return false; - } - } - else - { - if (c1 != c2) - { - return false; - } - } - } - - Advance(s.Length); - return true; - } - - public bool ReadEnclosed(char open, char close) - { - if (Peek() == open) - { - int length = PeekUntil(1, close); - if (length > 0) - { - Advance(1 + length); - return true; - } - } - - return false; - } - } -} diff --git a/src/LogExpert/Classes/FileSystemCallback.cs b/src/LogExpert/Classes/FileSystemCallback.cs deleted file mode 100644 index f5abfefb..00000000 --- a/src/LogExpert/Classes/FileSystemCallback.cs +++ /dev/null @@ -1,49 +0,0 @@ -using NLog; - -namespace LogExpert.Classes -{ - internal class FileSystemCallback : IFileSystemCallback - { - #region Public methods - - public ILogExpertLogger GetLogger() - { - return new NLogLogExpertWrapper(); - } - - #endregion - - private class NLogLogExpertWrapper : ILogExpertLogger - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - #endregion - - #region Public methods - - public void Info(string msg) - { - _logger.Info(msg); - } - - public void Debug(string msg) - { - _logger.Debug(msg); - } - - public void LogWarn(string msg) - { - _logger.Warn(msg); - } - - public void LogError(string msg) - { - _logger.Error(msg); - } - - #endregion - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Filter/Filter.cs b/src/LogExpert/Classes/Filter/Filter.cs deleted file mode 100644 index c65ddef8..00000000 --- a/src/LogExpert/Classes/Filter/Filter.cs +++ /dev/null @@ -1,178 +0,0 @@ -using LogExpert.Classes.ILogLineColumnizerCallback; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace LogExpert.Classes.Filter -{ - internal delegate void FilterFx(FilterParams filterParams, List filterResultLines, List lastFilterResultLines, List filterHitList); - - internal class Filter - { - #region Fields - - private const int PROGRESS_BAR_MODULO = 1000; - private const int SPREAD_MAX = 50; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private readonly ColumnizerCallback _callback; - - #endregion - - #region cTor - - public Filter(ColumnizerCallback callback) - { - _callback = callback; - FilterResultLines = []; - LastFilterLinesList = []; - FilterHitList = []; - } - - #endregion - - #region Properties - - public List FilterResultLines { get; } - - public List LastFilterLinesList { get; } - - public List FilterHitList { get; } - - public bool ShouldCancel { get; set; } = false; - - #endregion - - #region Public methods - - public int DoFilter(FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback) - { - return DoFilter(filterParams, startLine, maxCount, FilterResultLines, LastFilterLinesList, FilterHitList, progressCallback); - } - - #endregion - - #region Private Methods - - private int DoFilter(FilterParams filterParams, int startLine, int maxCount, List filterResultLines, - List lastFilterLinesList, List filterHitList, ProgressCallback progressCallback) - { - int lineNum = startLine; - int count = 0; - int callbackCounter = 0; - - try - { - filterParams.Reset(); - while ((count++ < maxCount || filterParams.isInRange) && !ShouldCancel) - { - if (lineNum >= _callback.GetLineCount()) - { - return count; - } - - ILogLine line = _callback.GetLogLine(lineNum); - if (line == null) - { - return count; - } - - _callback.LineNum = lineNum; - if (Util.TestFilterCondition(filterParams, line, _callback)) - { - AddFilterLine(lineNum, false, filterParams, filterResultLines, lastFilterLinesList, - filterHitList); - } - - lineNum++; - callbackCounter++; - - if (lineNum % PROGRESS_BAR_MODULO == 0) - { - progressCallback(callbackCounter); - callbackCounter = 0; - } - } - } - 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"); - } - - return count; - } - - private void AddFilterLine(int lineNum, bool immediate, FilterParams filterParams, List filterResultLines, List lastFilterLinesList, List filterHitList) - { - filterHitList.Add(lineNum); - IList filterResult = GetAdditionalFilterResults(filterParams, lineNum, lastFilterLinesList); - - filterResultLines.AddRange(filterResult); - - lastFilterLinesList.AddRange(filterResult); - - if (lastFilterLinesList.Count > SPREAD_MAX * 2) - { - lastFilterLinesList.RemoveRange(0, lastFilterLinesList.Count - SPREAD_MAX * 2); - } - } - - - /// - /// 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 = []; - - if (filterParams.spreadBefore == 0 && filterParams.spreadBehind == 0) - { - resultList.Add(lineNum); - return resultList; - } - - // back spread - for (int 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 (int i = 1; i <= filterParams.spreadBehind; ++i) - { - if (lineNum + i < _callback.GetLineCount()) - { - if (!resultList.Contains(lineNum + i) && !checkList.Contains(lineNum + i)) - { - resultList.Add(lineNum + i); - } - } - } - return resultList; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Filter/FilterCancelHandler.cs b/src/LogExpert/Classes/Filter/FilterCancelHandler.cs deleted file mode 100644 index ef11b340..00000000 --- a/src/LogExpert/Classes/Filter/FilterCancelHandler.cs +++ /dev/null @@ -1,34 +0,0 @@ -using LogExpert.Interface; -using NLog; - -namespace LogExpert.Classes.Filter -{ - internal class FilterCancelHandler : BackgroundProcessCancelHandler - { - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - #region Fields - - private readonly FilterStarter _filterStarter; - - #endregion - - #region cTor - - public FilterCancelHandler(FilterStarter filterStarter) - { - _filterStarter = filterStarter; - } - - #endregion - - #region Public methods - - public void EscapePressed() - { - _logger.Info("FilterCancelHandler called."); - _filterStarter.CancelFilter(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Filter/FilterParams.cs b/src/LogExpert/Classes/Filter/FilterParams.cs deleted file mode 100644 index 84febf51..00000000 --- a/src/LogExpert/Classes/Filter/FilterParams.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Drawing; -using System.Text.RegularExpressions; - -namespace LogExpert.Classes.Filter -{ - [Serializable] - public class FilterParams - { - #region Fields - - public string _rangeSearchText = ""; - public string _searchText = ""; - - public Color color = Color.Black; - - //public List historyList = new List(); - //public List rangeHistoryList = new List(); - public List columnList = []; // list of columns in which to search - - public bool columnRestrict = false; - - [NonSerialized] public ILogLineColumnizer currentColumnizer; - - public bool emptyColumnHit; - public bool emptyColumnUsePrev; - - public bool exactColumnMatch = false; - - //public bool isFuzzy; - public int fuzzyValue = 0; - - public bool isCaseSensitive; - public bool isFilterTail; - - [NonSerialized] public bool isInRange = false; // false=looking for start, true=looking for end - - public bool isInvert; - public bool isRangeSearch = false; - public bool isRegex; - - [NonSerialized] public string lastLine = ""; - - [NonSerialized] public Hashtable lastNonEmptyCols = []; - - [NonSerialized] public bool lastResult; - - [NonSerialized] public string lowerRangeSearchText = ""; - - // transient members: - [NonSerialized] public string lowerSearchText = ""; - - [NonSerialized] public Regex rangeRex; - - [NonSerialized] public Regex rex; - - public int spreadBefore; - public int spreadBehind; - - #endregion - - #region Properties - - public string searchText - { - get => _searchText; - set - { - _searchText = value; - lowerSearchText = _searchText.ToLower(); - } - } - - public string rangeSearchText - { - get => _rangeSearchText; - set - { - _rangeSearchText = value; - lowerRangeSearchText = _rangeSearchText.ToLower(); - } - } - - public bool SpreadEnabled => spreadBefore > 0 || spreadBehind > 0; - - #endregion - - #region Public methods - - public FilterParams CreateCopy2() - { - FilterParams newParams = CreateCopy(); - newParams.Init(); - // removed cloning of columnizer for filtering, because this causes issues with columnizers that hold internal states (like CsvColumnizer) - // newParams.currentColumnizer = Util.CloneColumnizer(this.currentColumnizer); - newParams.currentColumnizer = currentColumnizer; - return newParams; - } - - // call after deserialization! - public void Init() - { - lastNonEmptyCols = []; - lowerRangeSearchText = _rangeSearchText.ToLower(); - lowerSearchText = _searchText.ToLower(); - lastLine = ""; - } - - // Reset before a new search - public void Reset() - { - lastNonEmptyCols.Clear(); - isInRange = false; - } - - public void CreateRegex() - { - if (_searchText != null) - { - rex = new Regex(_searchText, - isCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - } - if (_rangeSearchText != null && isRangeSearch) - { - rangeRex = new Regex(_rangeSearchText, - isCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - } - } - - public FilterParams CreateCopy() - { - return (FilterParams) MemberwiseClone(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Filter/FilterPipe.cs b/src/LogExpert/Classes/Filter/FilterPipe.cs deleted file mode 100644 index 3d679795..00000000 --- a/src/LogExpert/Classes/Filter/FilterPipe.cs +++ /dev/null @@ -1,197 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using LogExpert.Controls.LogWindow; -using NLog; - -namespace LogExpert.Classes.Filter -{ - internal class FilterPipe - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private IList _lineMappingList = new List(); - private StreamWriter _writer; - - #endregion - - #region cTor - - public FilterPipe(FilterParams filterParams, LogWindow logWindow) - { - FilterParams = filterParams; - LogWindow = logWindow; - IsStopped = false; - FileName = Path.GetTempFileName(); - - _logger.Info("Created temp file: {0}", FileName); - } - - #endregion - - #region Delegates - - public delegate void ClosedEventHandler(object sender, EventArgs e); - - #endregion - - #region Events - - public event ClosedEventHandler Closed; - - #endregion - - #region Properties - - public bool IsStopped { get; set; } - - public string FileName { get; } - - public FilterParams FilterParams { get; } - - public IList LastLinesHistoryList { get; } = new List(); - - public LogWindow LogWindow { get; } - - public LogWindow OwnLogWindow { get; set; } - - #endregion - - #region Public methods - - public void OpenFile() - { - FileStream fStream = new(FileName, FileMode.Append, FileAccess.Write, FileShare.Read); - _writer = new StreamWriter(fStream, new UnicodeEncoding(false, false)); - } - - public void CloseFile() - { - if (_writer != null) - { - _writer.Close(); - _writer = null; - } - } - - public bool WriteToPipe(ILogLine textLine, int orgLineNum) - { - try - { - lock (FileName) - { - lock (_lineMappingList) - { - try - { - _writer.WriteLine(textLine.FullLine); - _lineMappingList.Add(orgLineNum); - return true; - } - catch (IOException e) - { - _logger.Error(e, "writeToPipe()"); - return false; - } - } - } - } - catch (IOException ex) - { - _logger.Error(ex, "writeToPipe(): file was closed"); - return false; - } - } - - public int GetOriginalLineNum(int lineNum) - { - lock (_lineMappingList) - { - if (_lineMappingList.Count > lineNum) - { - return _lineMappingList[lineNum]; - } - - return -1; - } - } - - public void ShiftLineNums(int offset) - { - _logger.Debug("FilterPipe.ShiftLineNums() offset={0}", offset); - List newList = []; - lock (_lineMappingList) - { - foreach (int lineNum in _lineMappingList) - { - int line = lineNum - offset; - if (line >= 0) - { - newList.Add(line); - } - else - { - newList.Add(-1); - } - } - _lineMappingList = newList; - } - } - - public void ClearLineNums() - { - _logger.Debug("FilterPipe.ClearLineNums()"); - lock (_lineMappingList) - { - for (int i = 0; i < _lineMappingList.Count; ++i) - { - _lineMappingList[i] = -1; - } - } - } - - public void ClearLineList() - { - lock (_lineMappingList) - { - _lineMappingList.Clear(); - } - } - - public void RecreateTempFile() - { - lock (_lineMappingList) - { - _lineMappingList = new List(); - } - lock (FileName) - { - CloseFile(); - // trunc file - FileStream fStream = new(FileName, FileMode.Truncate, FileAccess.Write, FileShare.Read); - fStream.SetLength(0); - fStream.Close(); - } - } - - public void CloseAndDisconnect() - { - ClearLineList(); - OnClosed(); - } - - #endregion - - #region Private Methods - - private void OnClosed() - { - Closed?.Invoke(this, EventArgs.Empty); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Filter/FilterStarter.cs b/src/LogExpert/Classes/Filter/FilterStarter.cs deleted file mode 100644 index 9ce8d025..00000000 --- a/src/LogExpert/Classes/Filter/FilterStarter.cs +++ /dev/null @@ -1,222 +0,0 @@ -using LogExpert.Classes.ILogLineColumnizerCallback; -using NLog; -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace LogExpert.Classes.Filter -{ - public delegate void ProgressCallback(int lineCount); - - internal class FilterStarter - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private readonly ColumnizerCallback _callback; - private readonly SortedDictionary _filterHitDict; - private readonly List _filterReadyList; - private readonly SortedDictionary _filterResultDict; - - private readonly List _filterWorkerList; - - private readonly SortedDictionary _lastFilterLinesDict; - - private ProgressCallback _progressCallback; - private int _progressLineCount; - private bool _shouldStop; - - #endregion - - #region cTor - - public FilterStarter(ColumnizerCallback callback, int minThreads) - { - _callback = callback; - FilterResultLines = []; - LastFilterLinesList = []; - FilterHitList = []; - _filterReadyList = []; - _filterWorkerList = []; - _filterHitDict = []; - _filterResultDict = []; - _lastFilterLinesDict = []; - ThreadCount = Environment.ProcessorCount * 4; - ThreadCount = minThreads; - ThreadPool.GetMinThreads(out _, out var completion); - ThreadPool.SetMinThreads(minThreads, completion); - ThreadPool.GetMaxThreads(out _, out _); - } - - #endregion - - #region Properties - - public List FilterResultLines { get; set; } - - public List LastFilterLinesList { get; set; } - - public List FilterHitList { get; set; } - - public int ThreadCount { get; set; } - - #endregion - - #region Public methods - - public async void DoFilter(FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback) - { - FilterResultLines.Clear(); - LastFilterLinesList.Clear(); - FilterHitList.Clear(); - _filterHitDict.Clear(); - _filterReadyList.Clear(); - _filterResultDict.Clear(); - _lastFilterLinesDict.Clear(); - _filterWorkerList.Clear(); - _shouldStop = false; - - int interval = maxCount / ThreadCount; - - if (interval < 1) - { - interval = 1; - } - int workStartLine = startLine; - List handleList = []; - _progressLineCount = 0; - _progressCallback = progressCallback; - while (workStartLine < startLine + maxCount) - { - if (workStartLine + interval > maxCount) - { - interval = maxCount - workStartLine; - if (interval == 0) - { - break; - } - } - _logger.Info("FilterStarter starts worker for line {0}, lineCount {1}", workStartLine, interval); - - await Task.Run(() => DoWork(filterParams, workStartLine, interval, ThreadProgressCallback)).ContinueWith(FilterDoneCallback); - workStartLine += interval; - } - - WaitHandle[] handles = [.. handleList]; - // wait for worker threads completion - if (handles.Length > 0) - { - WaitHandle.WaitAll(handles); - } - - MergeResults(); - } - - /// - /// Requests the FilterStarter to stop all filter threads. Call this from another thread (e.g. GUI). The function returns - /// immediately without waiting for filter end. - /// - public void CancelFilter() - { - _shouldStop = true; - lock (_filterWorkerList) - { - _logger.Info("Filter cancel requested. Stopping all {0} threads.", _filterWorkerList.Count); - foreach (Filter filter in _filterWorkerList) - { - filter.ShouldCancel = true; - } - } - } - - #endregion - - #region Private Methods - - private void ThreadProgressCallback(int lineCount) - { - int count = Interlocked.Add(ref _progressLineCount, lineCount); - _progressCallback(count); - } - - private Filter DoWork(FilterParams filterParams, int startLine, int maxCount, ProgressCallback progressCallback) - { - _logger.Info("Started Filter worker [{0}] for line {1}", Environment.CurrentManagedThreadId, startLine); - - // Give every thread own copies of ColumnizerCallback and FilterParams, because the state of the objects changes while filtering - FilterParams threadFilterParams = filterParams.CreateCopy2(); - ColumnizerCallback threadColumnizerCallback = _callback.CreateCopy(); - - Filter filter = new(threadColumnizerCallback); - lock (_filterWorkerList) - { - _filterWorkerList.Add(filter); - } - - if (_shouldStop) - { - return filter; - } - - _ = filter.DoFilter(threadFilterParams, startLine, maxCount, progressCallback); - _logger.Info("Filter worker [{0}] for line {1} has completed.", Thread.CurrentThread.ManagedThreadId, startLine); - - lock (_filterReadyList) - { - _filterReadyList.Add(filter); - } - - return filter; - } - - private void FilterDoneCallback(Task filterTask) - { - if (filterTask.IsCompleted) - { - Filter filter = filterTask.Result; - - lock (_filterReadyList) - { - _filterReadyList.Add(filter); - } - } - } - - private void MergeResults() - { - _logger.Info("Merging filter results."); - foreach (Filter filter in _filterReadyList) - { - foreach (int lineNum in filter.FilterHitList) - { - if (!_filterHitDict.ContainsKey(lineNum)) - { - _filterHitDict.Add(lineNum, lineNum); - } - } - foreach (int lineNum in filter.FilterResultLines) - { - if (!_filterResultDict.ContainsKey(lineNum)) - { - _filterResultDict.Add(lineNum, lineNum); - } - } - foreach (int lineNum in filter.LastFilterLinesList) - { - if (!_lastFilterLinesDict.ContainsKey(lineNum)) - { - _lastFilterLinesDict.Add(lineNum, lineNum); - } - } - } - FilterHitList.AddRange(_filterHitDict.Keys); - FilterResultLines.AddRange(_filterResultDict.Keys); - LastFilterLinesList.AddRange(_lastFilterLinesDict.Keys); - _logger.Info("Merging done."); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Highlight/ActionEntry.cs b/src/LogExpert/Classes/Highlight/ActionEntry.cs deleted file mode 100644 index 1d65712f..00000000 --- a/src/LogExpert/Classes/Highlight/ActionEntry.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; - -namespace LogExpert.Classes.Highlight -{ - [Serializable] - public class ActionEntry : ICloneable - { - #region Fields - - public string ActionParam { get; set; } - - public string PluginName { get; set; } - - public object Clone() - { - var actionEntry = new ActionEntry - { - PluginName = PluginName, - ActionParam = ActionParam - }; - - return actionEntry; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Highlight/HilightEntry.cs b/src/LogExpert/Classes/Highlight/HilightEntry.cs deleted file mode 100644 index 18e02db9..00000000 --- a/src/LogExpert/Classes/Highlight/HilightEntry.cs +++ /dev/null @@ -1,108 +0,0 @@ -using Newtonsoft.Json; - -using System; -using System.Drawing; -using System.Text.RegularExpressions; - -namespace LogExpert.Classes.Highlight -{ - [Serializable] - [method: JsonConstructor] - public class HilightEntry() : ICloneable - { - #region Fields - - [NonSerialized] private Regex regex = null; - - private string _searchText = string.Empty; - - #endregion Fields - - #region Properties - - public bool IsStopTail { get; set; } - - public bool IsSetBookmark { get; set; } - - public bool IsRegEx { get; set; } - - public bool IsCaseSensitive { get; set; } - - public Color ForegroundColor { get; set; } - - public Color BackgroundColor { get; set; } - - public string SearchText - { - get => _searchText; - set - { - _searchText = value; - regex = null; - } - } - - public bool IsLedSwitch { get; set; } - - public ActionEntry ActionEntry { get; set; } - - public bool IsActionEntry { get; set; } - - public string BookmarkComment { get; set; } - - public Regex Regex - { - get - { - if (regex == null) - { - if (IsRegEx) - { - regex = new Regex(SearchText, IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - } - else - { - regex = new Regex(Regex.Escape(SearchText), IsCaseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - } - } - return regex; - } - } - - public bool IsWordMatch { get; set; } - - // highlightes search result - [field: NonSerialized] - public bool IsSearchHit { get; set; } - - public bool IsBold { get; set; } - - public bool NoBackground { get; set; } - - public object Clone() - { - var highLightEntry = new HilightEntry - { - SearchText = SearchText, - ForegroundColor = ForegroundColor, - BackgroundColor = BackgroundColor, - IsRegEx = IsRegEx, - IsCaseSensitive = IsCaseSensitive, - IsLedSwitch = IsLedSwitch, - IsStopTail = IsStopTail, - IsSetBookmark = IsSetBookmark, - IsActionEntry = IsActionEntry, - ActionEntry = ActionEntry != null ? (ActionEntry)ActionEntry.Clone() : null, - IsWordMatch = IsWordMatch, - IsBold = IsBold, - BookmarkComment = BookmarkComment, - NoBackground = NoBackground, - IsSearchHit = IsSearchHit - }; - - return highLightEntry; - } - - #endregion Properties - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Highlight/HilightMatchEntry.cs b/src/LogExpert/Classes/Highlight/HilightMatchEntry.cs deleted file mode 100644 index b1e3fcdd..00000000 --- a/src/LogExpert/Classes/Highlight/HilightMatchEntry.cs +++ /dev/null @@ -1,27 +0,0 @@ -namespace LogExpert.Classes.Highlight -{ - /// - /// Class for storing word-wise hilight matches. Used for colouring different matches on one line. - /// - public class HilightMatchEntry - { - #region Properties - - public HilightEntry HilightEntry { get; set; } - - public int StartPos { get; set; } - - public int Length { get; set; } - - #endregion - - #region Public methods - - public override string ToString() - { - return $"{HilightEntry.SearchText}/{StartPos}/{Length}"; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/ILogLineColumnizerCallback/ColumnizerCallback.cs b/src/LogExpert/Classes/ILogLineColumnizerCallback/ColumnizerCallback.cs deleted file mode 100644 index 2abb7c4c..00000000 --- a/src/LogExpert/Classes/ILogLineColumnizerCallback/ColumnizerCallback.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System.Collections.Generic; -using LogExpert.Controls.LogWindow; - -namespace LogExpert.Classes.ILogLineColumnizerCallback -{ - internal class ColumnizerCallback : LogExpert.ILogLineColumnizerCallback, IAutoLogLineColumnizerCallback - { - #region Fields - - protected LogWindow logWindow; - - #endregion - - #region cTor - - public ColumnizerCallback(LogWindow logWindow) - { - this.logWindow = logWindow; - } - - private ColumnizerCallback(ColumnizerCallback original) - { - logWindow = original.logWindow; - LineNum = original.LineNum; - } - - #endregion - - #region Properties - - public int LineNum { get; set; } - - #endregion - - #region Public methods - - public ColumnizerCallback CreateCopy() - { - return new ColumnizerCallback(this); - } - - public int GetLineNum() - { - return LineNum; - } - - public string GetFileName() - { - return logWindow.GetCurrentFileName(LineNum); - } - - public ILogLine GetLogLine(int lineNum) - { - return logWindow.GetLine(lineNum); - } - - public IList GetRegisteredColumnizers() - { - return PluginRegistry.Instance.RegisteredColumnizers; - } - - public int GetLineCount() - { - return logWindow._logFileReader.LineCount; - } - - #endregion - } -} diff --git a/src/LogExpert/Classes/ILogLineColumnizerCallback/LogExpertCallback.cs b/src/LogExpert/Classes/ILogLineColumnizerCallback/LogExpertCallback.cs deleted file mode 100644 index 20a8c89d..00000000 --- a/src/LogExpert/Classes/ILogLineColumnizerCallback/LogExpertCallback.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Generic; -using LogExpert.Controls.LogWindow; - -namespace LogExpert.Classes.ILogLineColumnizerCallback -{ - internal class LogExpertCallback : ColumnizerCallback, ILogExpertCallback - { - #region cTor - - public LogExpertCallback(LogWindow logWindow) - : base(logWindow) - { - } - - #endregion - - #region Public methods - - public void AddTempFileTab(string fileName, string title) - { - logWindow.AddTempFileTab(fileName, title); - } - - public void AddPipedTab(IList lineEntryList, string title) - { - logWindow.WritePipeTab(lineEntryList, title); - } - - public string GetTabTitle() - { - return logWindow.Text; - } - - #endregion - } -} diff --git a/src/LogExpert/Classes/LocalFileSystem.cs b/src/LogExpert/Classes/LocalFileSystem.cs deleted file mode 100644 index 9594dc6c..00000000 --- a/src/LogExpert/Classes/LocalFileSystem.cs +++ /dev/null @@ -1,49 +0,0 @@ -using System; -using LogExpert.Classes.Log; - -namespace LogExpert.Classes -{ - public class LocalFileSystem : IFileSystemPlugin - { - #region IFileSystemPlugin Member - - public bool CanHandleUri(string uriString) - { - try - { - Uri uri = new(uriString); - return uri.IsFile; - } - catch (Exception) - { - return false; - } - } - - public ILogFileInfo GetLogfileInfo(string uriString) - { - Uri uri = new(uriString); - if (uri.IsFile) - { - ILogFileInfo logFileInfo = new LogFileInfo(uri); - return logFileInfo; - } - else - { - throw new UriFormatException("Uri " + uriString + " is no file Uri"); - } - } - - public string Text - { - get { return "Local file system"; } - } - - public string Description - { - get { return "Access files from normal file system."; } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/LogBuffer.cs b/src/LogExpert/Classes/Log/LogBuffer.cs deleted file mode 100644 index d9c07400..00000000 --- a/src/LogExpert/Classes/Log/LogBuffer.cs +++ /dev/null @@ -1,125 +0,0 @@ -using System.Collections.Generic; -using NLog; - -namespace LogExpert.Classes.Log -{ - public class LogBuffer - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - -#if DEBUG - private readonly IList _filePositions = new List(); // file position for every line -#endif - - private readonly IList _logLines = new List(); - private int MAX_LINES = 500; - private long _size; - - #endregion - - #region cTor - - //public LogBuffer() { } - - public LogBuffer(ILogFileInfo fileInfo, int maxLines) - { - FileInfo = fileInfo; - MAX_LINES = maxLines; - } - - #endregion - - #region Properties - - public long StartPos { set; get; } = 0; - - public long Size - { - set - { - _size = value; -#if DEBUG - if (_filePositions.Count > 0) - { - if (_size < _filePositions[_filePositions.Count - 1] - StartPos) - { - _logger.Error("LogBuffer overall Size must be greater than last line file position!"); - } - } -#endif - } - get => _size; - } - - public int StartLine { set; get; } = 0; - - public int LineCount { get; private set; } - - public bool IsDisposed { get; private set; } - - public ILogFileInfo FileInfo { get; set; } - - public int DroppedLinesCount { get; set; } = 0; - - public int PrevBuffersDroppedLinesSum { get; set; } = 0; - - #endregion - - #region Public methods - - public void AddLine(ILogLine line, long filePos) - { - _logLines.Add(line); -#if DEBUG - _filePositions.Add(filePos); -#endif - LineCount++; - IsDisposed = false; - } - - public void ClearLines() - { - _logLines.Clear(); - LineCount = 0; - } - - public void DisposeContent() - { - _logLines.Clear(); - IsDisposed = true; -#if DEBUG - DisposeCount++; -#endif - } - - public ILogLine GetLineOfBlock(int num) - { - if (num < _logLines.Count && num >= 0) - { - return _logLines[num]; - } - - return null; - } - - #endregion - -#if DEBUG - public long DisposeCount { get; private set; } - - - public long GetFilePosForLineOfBlock(int line) - { - if (line >= 0 && line < _filePositions.Count) - { - return _filePositions[line]; - } - - return -1; - } - -#endif - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/LogBufferCacheEntry.cs b/src/LogExpert/Classes/Log/LogBufferCacheEntry.cs deleted file mode 100644 index c80ca6ed..00000000 --- a/src/LogExpert/Classes/Log/LogBufferCacheEntry.cs +++ /dev/null @@ -1,37 +0,0 @@ -using System; - -namespace LogExpert.Classes.Log -{ - internal class LogBufferCacheEntry - { - #region Fields - - #endregion - - #region cTor - - public LogBufferCacheEntry() - { - Touch(); - } - - #endregion - - #region Properties - - internal LogBuffer LogBuffer { get; set; } - - public long LastUseTimeStamp { get; private set; } - - #endregion - - #region Public methods - - public void Touch() - { - LastUseTimeStamp = (long) (Environment.TickCount & int.MaxValue); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/LogFileInfo.cs b/src/LogExpert/Classes/Log/LogFileInfo.cs deleted file mode 100644 index 31bd9bc8..00000000 --- a/src/LogExpert/Classes/Log/LogFileInfo.cs +++ /dev/null @@ -1,188 +0,0 @@ -using System; -using System.IO; -using System.Threading; -using LogExpert.Config; -using NLog; - -namespace LogExpert.Classes.Log -{ - public class LogFileInfo : ILogFileInfo - { - #region Fields - - private const int RETRY_COUNT = 5; - private const int RETRY_SLEEP = 250; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - //FileStream fStream; - private readonly FileInfo fInfo; - - private long lastLength; - - #endregion - - #region cTor - - public LogFileInfo(Uri fileUri) - { - this.fInfo = new FileInfo(fileUri.LocalPath); - this.Uri = fileUri; - this.OriginalLength = lastLength = LengthWithoutRetry; - //this.oldLength = 0; - } - - #endregion - - #region Properties - - public string FullName - { - get { return this.fInfo.FullName; } - } - - public string FileName - { - get { return this.fInfo.Name; } - } - - - public string DirectoryName - { - get { return this.fInfo.DirectoryName; } - } - - public char DirectorySeparatorChar - { - get { return Path.DirectorySeparatorChar; } - } - - public Uri Uri { get; } - - - public long Length - { - get - { - if (fInfo == null) - { - return -1; - } - int retry = RETRY_COUNT; - while (retry > 0) - { - try - { - this.fInfo.Refresh(); - return this.fInfo.Length; - } - catch (IOException e) - { - if (--retry <= 0) - { - _logger.Warn(e, "LogFileInfo.Length"); - return -1; - } - Thread.Sleep(RETRY_SLEEP); - } - } - return -1; - } - } - - public long OriginalLength { get; } - - public bool FileExists - { - get - { - this.fInfo.Refresh(); - return this.fInfo.Exists; - } - } - - public int PollInterval - { - get { return ConfigManager.Settings.Preferences.pollingInterval; } - } - - public long LengthWithoutRetry - { - get - { - if (fInfo == null) - { - return -1; - } - try - { - this.fInfo.Refresh(); - return this.fInfo.Length; - } - catch (IOException) - { - return -1; - } - } - } - - #endregion - - #region Public methods - - /// - /// Creates a new FileStream for the file. The caller is responsible for closing. - /// If file opening fails it will be tried RETRY_COUNT times. This may be needed sometimes - /// if the file is locked for a short amount of time or temporarly unaccessible because of - /// rollover situations. - /// - /// - public Stream OpenStream() - { - int retry = RETRY_COUNT; - while (true) - { - try - { - return new FileStream(this.fInfo.FullName, FileMode.Open, FileAccess.Read, - FileShare.ReadWrite | FileShare.Delete); - } - catch (IOException fe) - { - _logger.Debug(fe, "LogFileInfo.OpenFile(): \r\nRetry counter {0}", retry); - if (--retry <= 0) - { - throw; - } - Thread.Sleep(RETRY_SLEEP); - } - catch (UnauthorizedAccessException uae) - { - _logger.Debug(uae, "LogFileInfo.OpenFile(): \r\nRetry counter: {0}", retry); - if (--retry <= 0) - { - throw new IOException("Error opening file", uae); - } - Thread.Sleep(RETRY_SLEEP); - } - } - } - - public bool FileHasChanged() - { - if (this.LengthWithoutRetry != this.lastLength) - { - this.lastLength = this.LengthWithoutRetry; - return true; - } - return false; - } - - - public override string ToString() - { - return this.fInfo.FullName + ", OldLen: " + OriginalLength + ", Len: " + Length; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/LogStreamReaderBase.cs b/src/LogExpert/Classes/Log/LogStreamReaderBase.cs deleted file mode 100644 index e47bc9af..00000000 --- a/src/LogExpert/Classes/Log/LogStreamReaderBase.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System; -using System.Text; -using LogExpert.Interface; - -namespace LogExpert.Classes.Log -{ - public abstract class LogStreamReaderBase : ILogStreamReader - { - #region cTor - - protected LogStreamReaderBase() - { - - } - - ~LogStreamReaderBase() - { - Dispose(false); - } - - #endregion - - #region Properties - - /// - /// Current position in the stream. - /// - public abstract long Position { get; set; } - - public abstract bool IsBufferComplete { get; } - - public abstract Encoding Encoding { get; } - - /// - /// Indicates whether or not the stream reader has already been disposed. - /// - public bool IsDisposed { get; private set; } - - #endregion - - #region Public methods - - /// - /// Destroy and release the current stream reader. - /// - public void Dispose() - { - try - { - Dispose(true); - GC.SuppressFinalize(this); - } - finally - { - IsDisposed = true; - } - } - /// - /// Destroy and release the current stream reader. - /// - /// Specifies whether or not the managed objects should be released. - protected abstract void Dispose(bool disposing); - - public abstract int ReadChar(); - - public abstract string ReadLine(); - - #endregion - } -} diff --git a/src/LogExpert/Classes/Log/LogfileReader.cs b/src/LogExpert/Classes/Log/LogfileReader.cs deleted file mode 100644 index 521edf06..00000000 --- a/src/LogExpert/Classes/Log/LogfileReader.cs +++ /dev/null @@ -1,1844 +0,0 @@ -using LogExpert.Classes.xml; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; -using LogExpert.Interface; - -using NLog; - -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Threading; -using System.Threading.Tasks; - -namespace LogExpert.Classes.Log -{ - public class LogfileReader : IAutoLogLineColumnizerCallback - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private readonly GetLogLineFx _logLineFx; - - private readonly string _fileName; - private readonly int _MAX_BUFFERS = 10; - private readonly int _MAX_LINES_PER_BUFFER = 100; - - private readonly object _monitor = new(); - private readonly MultiFileOptions _multiFileOptions; - - private IList _bufferList; - private ReaderWriterLock _bufferListLock; - private IList _bufferLru; - private bool _contentDeleted; - private int _currLineCount; - private ReaderWriterLock _disposeLock; - private EncodingOptions _encodingOptions; - private long _fileLength; - - private Task _garbageCollectorTask; - private Task _monitorTask; - private readonly CancellationTokenSource cts = new(); - - private bool _isDeleted; - private bool _isFailModeCheckCallPending; - private bool _isFastFailOnGetLogLine; - private bool _isLineCountDirty = true; - private IList _logFileInfoList = []; - private Dictionary _lruCacheDict; - - private ReaderWriterLock _lruCacheDictLock; - - - private bool _shouldStop; - private ILogFileInfo _watchedILogFileInfo; - - #endregion - - #region cTor - - public LogfileReader(string fileName, EncodingOptions encodingOptions, bool multiFile, int bufferCount, int linesPerBuffer, MultiFileOptions multiFileOptions) - { - if (fileName == null) - { - return; - } - - _fileName = fileName; - EncodingOptions = encodingOptions; - IsMultiFile = multiFile; - _MAX_BUFFERS = bufferCount; - _MAX_LINES_PER_BUFFER = linesPerBuffer; - _multiFileOptions = multiFileOptions; - _logLineFx = GetLogLineInternal; - InitLruBuffers(); - - if (multiFile) - { - ILogFileInfo info = GetLogFileInfo(fileName); - RolloverFilenameHandler rolloverHandler = new(info, _multiFileOptions); - LinkedList nameList = rolloverHandler.GetNameList(); - - ILogFileInfo fileInfo = null; - foreach (string name in nameList) - { - fileInfo = AddFile(name); - } - - _watchedILogFileInfo = fileInfo; // last added file in the list is the watched file - } - else - { - _watchedILogFileInfo = AddFile(fileName); - } - - StartGCThread(); - } - - public LogfileReader(string[] fileNames, EncodingOptions encodingOptions, int bufferCount, int linesPerBuffer, MultiFileOptions multiFileOptions) - { - if (fileNames == null || fileNames.Length < 1) - { - return; - } - - EncodingOptions = encodingOptions; - IsMultiFile = true; - _MAX_BUFFERS = bufferCount; - _MAX_LINES_PER_BUFFER = linesPerBuffer; - _multiFileOptions = multiFileOptions; - _logLineFx = GetLogLineInternal; - - InitLruBuffers(); - - ILogFileInfo fileInfo = null; - foreach (string name in fileNames) - { - fileInfo = AddFile(name); - } - - _watchedILogFileInfo = fileInfo; - _fileName = fileInfo.FullName; - - StartGCThread(); - } - - #endregion - - #region Delegates - - public delegate void BlockLoadedEventHandler(object sender, LoadFileEventArgs e); - - public delegate void FileNotFoundEventHandler(object sender, EventArgs e); - - public delegate void FileRespawnedEventHandler(object sender, EventArgs e); - - public delegate void FileSizeChangedEventHandler(object sender, LogEventArgs e); - - public delegate void FinishedLoadingEventHandler(object sender, EventArgs e); - - private delegate Task GetLogLineFx(int lineNum); - - public delegate void LoadingStartedEventHandler(object sender, LoadFileEventArgs e); - - #endregion - - #region Events - - public event FileSizeChangedEventHandler FileSizeChanged; - public event BlockLoadedEventHandler LoadFile; - public event LoadingStartedEventHandler LoadingStarted; - public event FinishedLoadingEventHandler LoadingFinished; - public event FileNotFoundEventHandler FileNotFound; - public event FileRespawnedEventHandler Respawned; - - #endregion - - #region Properties - - public int LineCount - { - get - { - if (_isLineCountDirty) - { - _currLineCount = 0; - AcquireBufferListReaderLock(); - foreach (LogBuffer buffer in _bufferList) - { - _currLineCount += buffer.LineCount; - } - - ReleaseBufferListReaderLock(); - _isLineCountDirty = false; - } - - return _currLineCount; - } - set => _currLineCount = value; - } - - public bool IsMultiFile { get; } - - public Encoding CurrentEncoding { get; private set; } - - public long FileSize { get; private set; } - - public bool IsXmlMode { get; set; } = false; - - public IXmlLogConfiguration XmlLogConfig { get; set; } - - public IPreProcessColumnizer PreProcessColumnizer { get; set; } = null; - - public EncodingOptions EncodingOptions - { - get => _encodingOptions; - set - { - { - _encodingOptions = new EncodingOptions - { - DefaultEncoding = value.DefaultEncoding, - Encoding = value.Encoding - }; - } - } - } - - public bool UseNewReader { get; set; } - - #endregion - - #region Public methods - - /// - /// Public for unit test reasons - /// - public void ReadFiles() - { - FileSize = 0; - LineCount = 0; - //this.lastReturnedLine = ""; - //this.lastReturnedLineNum = -1; - //this.lastReturnedLineNumForBuffer = -1; - _isDeleted = false; - ClearLru(); - AcquireBufferListWriterLock(); - _bufferList.Clear(); - ReleaseBufferListWriterLock(); - try - { - foreach (ILogFileInfo info in _logFileInfoList) - { - //info.OpenFile(); - ReadToBufferList(info, 0, LineCount); - } - - if (_logFileInfoList.Count > 0) - { - ILogFileInfo info = _logFileInfoList[_logFileInfoList.Count - 1]; - _fileLength = info.Length; - _watchedILogFileInfo = info; - } - } - catch (IOException e) - { - _logger.Warn(e, "IOException"); - _fileLength = 0; - _isDeleted = true; - LineCount = 0; - } - - LogEventArgs args = new() - { - PrevFileSize = 0, - PrevLineCount = 0, - LineCount = LineCount, - FileSize = FileSize - }; - - OnFileSizeChanged(args); - } - - /// - /// Public for unit tests. - /// - /// - public int ShiftBuffers() - { - _logger.Info("ShiftBuffers() begin for {0}{1}", _fileName, IsMultiFile ? " (MultiFile)" : ""); - AcquireBufferListWriterLock(); - int offset = 0; - _isLineCountDirty = true; - lock (_monitor) - { - RolloverFilenameHandler rolloverHandler = new(_watchedILogFileInfo, _multiFileOptions); - LinkedList fileNameList = rolloverHandler.GetNameList(); - - ResetBufferCache(); - IList lostILogFileInfoList = []; - IList readNewILogFileInfoList = []; - IList newFileInfoList = []; - IEnumerator enumerator = _logFileInfoList.GetEnumerator(); - while (enumerator.MoveNext()) - { - ILogFileInfo logFileInfo = enumerator.Current; - string fileName = logFileInfo.FullName; - _logger.Debug("Testing file {0}", fileName); - LinkedListNode node = fileNameList.Find(fileName); - if (node == null) - { - _logger.Warn("File {0} not found", fileName); - continue; - } - - if (node.Previous != null) - { - fileName = node.Previous.Value; - ILogFileInfo newILogFileInfo = GetLogFileInfo(fileName); - _logger.Debug("{0} exists\r\nOld size={1}, new size={2}", fileName, logFileInfo.OriginalLength, newILogFileInfo.Length); - // is the new file the same as the old buffer info? - if (newILogFileInfo.Length == logFileInfo.OriginalLength) - { - ReplaceBufferInfos(logFileInfo, newILogFileInfo); - newFileInfoList.Add(newILogFileInfo); - } - else - { - _logger.Debug("Buffer for {0} must be re-read.", fileName); - // not the same. so must read the rest of the list anew from the files - readNewILogFileInfoList.Add(newILogFileInfo); - while (enumerator.MoveNext()) - { - fileName = enumerator.Current.FullName; - node = fileNameList.Find(fileName); - if (node == null) - { - _logger.Warn("File {0} not found", fileName); - continue; - } - - if (node.Previous != null) - { - fileName = node.Previous.Value; - _logger.Debug("New name is {0}", fileName); - readNewILogFileInfoList.Add(GetLogFileInfo(fileName)); - } - else - { - _logger.Warn("No previous file for {0} found", fileName); - } - } - } - } - else - { - _logger.Info("{0} does not exist", fileName); - lostILogFileInfoList.Add(logFileInfo); -#if DEBUG // for better overview in logfile: - //ILogFileInfo newILogFileInfo = new ILogFileInfo(fileName); - //ReplaceBufferInfos(ILogFileInfo, newILogFileInfo); -#endif - } - } - - if (lostILogFileInfoList.Count > 0) - { - _logger.Info("Deleting buffers for lost files"); - foreach (ILogFileInfo ILogFileInfo in lostILogFileInfoList) - { - //this.ILogFileInfoList.Remove(ILogFileInfo); - LogBuffer lastBuffer = DeleteBuffersForInfo(ILogFileInfo, false); - if (lastBuffer != null) - { - offset += lastBuffer.StartLine + lastBuffer.LineCount; - } - } - - _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); - _logger.Info("Adjusting StartLine values in {0} buffers by offset {1}", _bufferList.Count, offset); - foreach (LogBuffer buffer in _bufferList) - { - SetNewStartLineForBuffer(buffer, buffer.StartLine - offset); - } - - _lruCacheDictLock.ReleaseWriterLock(); -#if DEBUG - if (_bufferList.Count > 0) - { - _logger.Debug("First buffer now has StartLine {0}", _bufferList[0].StartLine); - } -#endif - } - - // Read anew all buffers following a buffer info that couldn't be matched with the corresponding existing file - _logger.Info("Deleting buffers for files that must be re-read"); - foreach (ILogFileInfo ILogFileInfo in readNewILogFileInfoList) - { - DeleteBuffersForInfo(ILogFileInfo, true); - //this.ILogFileInfoList.Remove(ILogFileInfo); - } - - _logger.Info("Deleting buffers for the watched file"); - DeleteBuffersForInfo(_watchedILogFileInfo, true); - int startLine = LineCount - 1; - _logger.Info("Re-Reading files"); - foreach (ILogFileInfo ILogFileInfo in readNewILogFileInfoList) - { - //ILogFileInfo.OpenFile(); - ReadToBufferList(ILogFileInfo, 0, LineCount); - //this.ILogFileInfoList.Add(ILogFileInfo); - newFileInfoList.Add(ILogFileInfo); - } - - //this.watchedILogFileInfo = this.ILogFileInfoList[this.ILogFileInfoList.Count - 1]; - _logFileInfoList = newFileInfoList; - _watchedILogFileInfo = GetLogFileInfo(_watchedILogFileInfo.FullName); - _logFileInfoList.Add(_watchedILogFileInfo); - _logger.Info("Reading watched file"); - ReadToBufferList(_watchedILogFileInfo, 0, LineCount); - } - - _logger.Info("ShiftBuffers() end. offset={0}", offset); - ReleaseBufferListWriterLock(); - return offset; - } - - public ILogLine GetLogLine(int lineNum) - { - return GetLogLineInternal(lineNum).Result; - } - - /// - /// Get the text content of the given line number. - /// The actual work is done in an async thread. This method waits for thread completion for only 1 second. If the async - /// thread has not returned, the method will return null. This is because this method is also called from GUI thread - /// (e.g. LogWindow draw events). Under some circumstances, repeated calls to this method would lead the GUI to freeze. E.g. when - /// trying to re-load content from disk but the file was deleted. Especially on network shares. - /// - /// - /// Once the method detects a timeout it will enter a kind of 'fast fail mode'. That means all following calls will be returned with - /// null immediately (without 1 second wait). A background call to GetLogLineInternal() will check if a result is available. - /// If so, the 'fast fail mode' is switched off. In most cases a fail is caused by a deleted file. But it may also be caused by slow - /// network connections. So all this effort is needed to prevent entering an endless 'fast fail mode' just because of temporary problems. - /// - /// line to retrieve - /// - public async Task GetLogLineWithWait(int lineNum) - { - const int WAIT_TIME = 1000; - - ILogLine result = null; - - if (!_isFastFailOnGetLogLine) - { - var task = Task.Run(() => _logLineFx(lineNum)); - if (task.Wait(WAIT_TIME)) - { - result = task.Result; - _isFastFailOnGetLogLine = false; - } - else - { - _isFastFailOnGetLogLine = true; - _logger.Debug("No result after {0}ms. Returning .", WAIT_TIME); - } - } - else - { - _logger.Debug("Fast failing GetLogLine()"); - if (!_isFailModeCheckCallPending) - { - _isFailModeCheckCallPending = true; - var logLine = await _logLineFx(lineNum); - GetLineFinishedCallback(logLine); - } - } - - return result; - } - - /// - /// Returns the file name of the actual file for the given line. Needed for MultiFile. - /// - /// - /// - public string GetLogFileNameForLine(int lineNum) - { - AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); - string fileName = logBuffer?.FileInfo.FullName; - ReleaseBufferListReaderLock(); - return fileName; - } - - /// - /// Returns the ILogFileInfo for the actual file for the given line. Needed for MultiFile. - /// - /// - /// - public ILogFileInfo GetLogFileInfoForLine(int lineNum) - { - AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); - ILogFileInfo info = logBuffer?.FileInfo; - ReleaseBufferListReaderLock(); - return info; - } - - /// - /// Returns the line number (starting from the given number) where the next multi file - /// starts. - /// - /// - /// - public int GetNextMultiFileLine(int lineNum) - { - int result = -1; - AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); - if (logBuffer != null) - { - int index = _bufferList.IndexOf(logBuffer); - if (index != -1) - { - for (int i = index; i < _bufferList.Count; ++i) - { - if (_bufferList[i].FileInfo != logBuffer.FileInfo) - { - result = _bufferList[i].StartLine; - break; - } - } - } - } - - ReleaseBufferListReaderLock(); - return result; - } - - public int GetPrevMultiFileLine(int lineNum) - { - int result = -1; - AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); - if (logBuffer != null) - { - int index = _bufferList.IndexOf(logBuffer); - if (index != -1) - { - for (int i = index; i >= 0; --i) - { - if (_bufferList[i].FileInfo != logBuffer.FileInfo) - { - result = _bufferList[i].StartLine + _bufferList[i].LineCount; - break; - } - } - } - } - - ReleaseBufferListReaderLock(); - return result; - } - - /// - /// Returns the actual line number in the file for the given 'virtual line num'. - /// This is needed for multi file mode. 'Virtual' means that the given line num is a line - /// number in the collections of the files currently viewed together in multi file mode as one large virtual file. - /// This method finds the real file for the line number and maps the line number to the correct position - /// in that file. This is needed when launching external tools to provide correct line number arguments. - /// - /// - /// - public int GetRealLineNumForVirtualLineNum(int lineNum) - { - AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); - int result = -1; - if (logBuffer != null) - { - logBuffer = GetFirstBufferForFileByLogBuffer(logBuffer); - if (logBuffer != null) - { - result = lineNum - logBuffer.StartLine; - } - } - - ReleaseBufferListReaderLock(); - return result; - } - - public void StartMonitoring() - { - _logger.Info("startMonitoring()"); - _monitorTask = Task.Run(MonitorThreadProc, cts.Token); - _shouldStop = false; - } - - public void StopMonitoring() - { - _logger.Info("stopMonitoring()"); - _shouldStop = true; - - Thread.Sleep(_watchedILogFileInfo.PollInterval); // leave time for the threads to stop by themselves - - if (_monitorTask != null) - { - if (_monitorTask.Status == TaskStatus.Running) // if thread has not finished, abort it - { - cts.Cancel(); - } - } - - if (_garbageCollectorTask.IsCanceled == false) - { - if (_garbageCollectorTask.Status == TaskStatus.Running) // if thread has not finished, abort it - { - cts.Cancel(); - } - } - - //this.loadThread = null; - //_monitorThread = null; - //_garbageCollectorThread = null; // preventive call - CloseFiles(); - } - - /// - /// calls stopMonitoring() in a background thread and returns to the caller immediately. - /// This is useful for a fast responding GUI (e.g. when closing a file tab) - /// - public void StopMonitoringAsync() - { - Task task = Task.Run(StopMonitoring); - - //Thread stopperThread = new(new ThreadStart(StopMonitoring)) - //{ - // IsBackground = true - //}; - //stopperThread.Start(); - } - - /// - /// Deletes all buffer lines and disposes their content. Use only when the LogfileReader - /// is about to be closed! - /// - public void DeleteAllContent() - { - if (_contentDeleted) - { - _logger.Debug("Buffers for {0} already deleted.", Util.GetNameFromPath(_fileName)); - return; - } - - _logger.Info("Deleting all log buffers for {0}. Used mem: {1:N0}", Util.GetNameFromPath(_fileName), GC.GetTotalMemory(true)); //TODO [Z] uh GC collect calls creepy - AcquireBufferListWriterLock(); - _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); - _disposeLock.AcquireWriterLock(Timeout.Infinite); - - foreach (LogBuffer logBuffer in _bufferList) - { - if (!logBuffer.IsDisposed) - { - logBuffer.DisposeContent(); - } - } - - _lruCacheDict.Clear(); - _bufferList.Clear(); - - _disposeLock.ReleaseWriterLock(); - _lruCacheDictLock.ReleaseWriterLock(); - ReleaseBufferListWriterLock(); - GC.Collect(); - _contentDeleted = true; - _logger.Info("Deleting complete. Used mem: {0:N0}", GC.GetTotalMemory(true)); //TODO [Z] uh GC collect calls creepy - } - - /// - /// Explicit change the encoding. - /// - /// - public void ChangeEncoding(Encoding encoding) - { - CurrentEncoding = encoding; - EncodingOptions.Encoding = encoding; - ResetBufferCache(); - ClearLru(); - } - - /// - /// For unit tests only. - /// - /// - public IList GetLogFileInfoList() - { - return _logFileInfoList; - } - - /// - /// For unit tests only - /// - /// - public IList GetBufferList() - { - return _bufferList; - } - - #endregion - - #region Internals - -#if DEBUG - - internal void LogBufferInfoForLine(int lineNum) - { - AcquireBufferListReaderLock(); - LogBuffer buffer = GetBufferForLine(lineNum); - if (buffer == null) - { - ReleaseBufferListReaderLock(); - _logger.Error("Cannot find buffer for line {0}, file: {1}{2}", lineNum, _fileName, IsMultiFile ? " (MultiFile)" : ""); - return; - } - - _logger.Info("-----------------------------------"); - _disposeLock.AcquireReaderLock(Timeout.Infinite); - _logger.Info("Buffer info for line {0}", lineNum); - DumpBufferInfos(buffer); - _logger.Info("File pos for current line: {0}", buffer.GetFilePosForLineOfBlock(lineNum - buffer.StartLine)); - _disposeLock.ReleaseReaderLock(); - _logger.Info("-----------------------------------"); - ReleaseBufferListReaderLock(); - } -#endif - -#if DEBUG - internal void LogBufferDiagnostic() - { - _logger.Info("-------- Buffer diagnostics -------"); - _lruCacheDictLock.AcquireReaderLock(Timeout.Infinite); - int cacheCount = _lruCacheDict.Count; - _logger.Info("LRU entries: {0}", cacheCount); - _lruCacheDictLock.ReleaseReaderLock(); - - AcquireBufferListReaderLock(); - _logger.Info("File: {0}\r\nBuffer count: {1}\r\nDisposed buffers: {2}", _fileName, _bufferList.Count, _bufferList.Count - cacheCount); - int lineNum = 0; - long disposeSum = 0; - long maxDispose = 0; - long minDispose = int.MaxValue; - for (int i = 0; i < _bufferList.Count; ++i) - { - LogBuffer buffer = _bufferList[i]; - _disposeLock.AcquireReaderLock(Timeout.Infinite); - if (buffer.StartLine != lineNum) - { - _logger.Error("Start line of buffer is: {0}, expected: {1}", buffer.StartLine, lineNum); - _logger.Info("Info of buffer follows:"); - DumpBufferInfos(buffer); - } - - lineNum += buffer.LineCount; - disposeSum += buffer.DisposeCount; - maxDispose = Math.Max(maxDispose, buffer.DisposeCount); - minDispose = Math.Min(minDispose, buffer.DisposeCount); - _disposeLock.ReleaseReaderLock(); - } - - ReleaseBufferListReaderLock(); - _logger.Info("Dispose count sum is: {0}\r\nMin dispose count is: {1}\r\nMax dispose count is: {2}\r\n-----------------------------------", disposeSum, minDispose, maxDispose); - } - -#endif - - #endregion - - #region Private Methods - - private ILogFileInfo AddFile(string fileName) - { - _logger.Info("Adding file to ILogFileInfoList: " + fileName); - ILogFileInfo info = GetLogFileInfo(fileName); - _logFileInfoList.Add(info); - return info; - } - - private Task GetLogLineInternal(int lineNum) - { - if (_isDeleted) - { - _logger.Debug("Returning null for line {0} because file is deleted.", lineNum); - - // fast fail if dead file was detected. Prevents repeated lags in GUI thread caused by callbacks from control (e.g. repaint) - return null; - } - - AcquireBufferListReaderLock(); - LogBuffer logBuffer = GetBufferForLine(lineNum); - if (logBuffer == null) - { - ReleaseBufferListReaderLock(); - _logger.Error("Cannot find buffer for line {0}, file: {1}{2}", lineNum, _fileName, IsMultiFile ? " (MultiFile)" : ""); - return null; - } - - // disposeLock prevents that the garbage collector is disposing just in the moment we use the buffer - _disposeLock.AcquireReaderLock(Timeout.Infinite); - if (logBuffer.IsDisposed) - { - LockCookie cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); - lock (logBuffer.FileInfo) - { - ReReadBuffer(logBuffer); - } - - _disposeLock.DowngradeFromWriterLock(ref cookie); - } - - ILogLine line = logBuffer.GetLineOfBlock(lineNum - logBuffer.StartLine); - _disposeLock.ReleaseReaderLock(); - ReleaseBufferListReaderLock(); - - return Task.FromResult(line); - } - - private void InitLruBuffers() - { - _bufferList = []; - _bufferLru = new List(_MAX_BUFFERS + 1); - //this.lruDict = new Dictionary(this.MAX_BUFFERS + 1); // key=startline, value = index in bufferLru - _lruCacheDict = new Dictionary(_MAX_BUFFERS + 1); - _lruCacheDictLock = new ReaderWriterLock(); - _bufferListLock = new ReaderWriterLock(); - _disposeLock = new ReaderWriterLock(); - } - - private void StartGCThread() - { - _garbageCollectorTask = Task.Run(GarbageCollectorThreadProc, cts.Token); - //_garbageCollectorThread = new Thread(new ThreadStart(GarbageCollectorThreadProc)); - //_garbageCollectorThread.IsBackground = true; - //_garbageCollectorThread.Start(); - } - - private void ResetBufferCache() - { - FileSize = 0; - LineCount = 0; - //this.lastReturnedLine = ""; - //this.lastReturnedLineNum = -1; - //this.lastReturnedLineNumForBuffer = -1; - } - - private void CloseFiles() - { - //foreach (ILogFileInfo info in this.ILogFileInfoList) - //{ - // info.CloseFile(); - //} - FileSize = 0; - LineCount = 0; - //this.lastReturnedLine = ""; - //this.lastReturnedLineNum = -1; - //this.lastReturnedLineNumForBuffer = -1; - } - - private ILogFileInfo GetLogFileInfo(string fileNameOrUri) - { - IFileSystemPlugin fs = PluginRegistry.Instance.FindFileSystemForUri(fileNameOrUri) ?? throw new LogFileException("No file system plugin found for " + fileNameOrUri); - ILogFileInfo logFileInfo = fs.GetLogfileInfo(fileNameOrUri); - return logFileInfo ?? throw new LogFileException("Cannot find " + fileNameOrUri); - } - - private void ReplaceBufferInfos(ILogFileInfo oldLogFileInfo, ILogFileInfo newLogFileInfo) - { - _logger.Debug("ReplaceBufferInfos() " + oldLogFileInfo.FullName + " -> " + newLogFileInfo.FullName); - AcquireBufferListReaderLock(); - foreach (LogBuffer buffer in _bufferList) - { - if (buffer.FileInfo == oldLogFileInfo) - { - _logger.Debug("Buffer with startLine={0}, lineCount={1}, filePos={2}, size={3} gets new filename {4}", buffer.StartLine, buffer.LineCount, buffer.StartPos, buffer.Size, newLogFileInfo.FullName); - buffer.FileInfo = newLogFileInfo; - } - } - - ReleaseBufferListReaderLock(); - } - - private LogBuffer DeleteBuffersForInfo(ILogFileInfo ILogFileInfo, bool matchNamesOnly) - { - _logger.Info("Deleting buffers for file {0}", ILogFileInfo.FullName); - LogBuffer lastRemovedBuffer = null; - IList deleteList = []; - AcquireBufferListWriterLock(); - _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); - if (matchNamesOnly) - { - foreach (LogBuffer buffer in _bufferList) - { - if (buffer.FileInfo.FullName.ToLower().Equals(ILogFileInfo.FullName.ToLower())) - { - lastRemovedBuffer = buffer; - deleteList.Add(buffer); - } - } - } - else - { - foreach (LogBuffer buffer in _bufferList) - { - if (buffer.FileInfo == ILogFileInfo) - { - lastRemovedBuffer = buffer; - deleteList.Add(buffer); - } - } - } - - foreach (LogBuffer buffer in deleteList) - { - RemoveFromBufferList(buffer); - } - - _lruCacheDictLock.ReleaseWriterLock(); - ReleaseBufferListWriterLock(); - if (lastRemovedBuffer == null) - { - _logger.Info("lastRemovedBuffer is null"); - } - else - { - _logger.Info("lastRemovedBuffer: startLine={0}", lastRemovedBuffer.StartLine); - } - - return lastRemovedBuffer; - } - - /// - /// The caller must have writer locks for lruCache and buffer list! - /// - /// - private void RemoveFromBufferList(LogBuffer buffer) - { - Util.AssertTrue(_lruCacheDictLock.IsWriterLockHeld, "No writer lock for lru cache"); - Util.AssertTrue(_bufferListLock.IsWriterLockHeld, "No writer lock for buffer list"); - _lruCacheDict.Remove(buffer.StartLine); - _bufferList.Remove(buffer); - } - - private void ReadToBufferList(ILogFileInfo logFileInfo, long filePos, int startLine) - { - try - { - using Stream fileStream = logFileInfo.OpenStream(); - try - { - using ILogStreamReader reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); - reader.Position = filePos; - _fileLength = logFileInfo.Length; - - int lineNum = startLine; - LogBuffer logBuffer; - AcquireBufferListReaderLock(); - if (_bufferList.Count == 0) - { - logBuffer = new LogBuffer(logFileInfo, _MAX_LINES_PER_BUFFER); - logBuffer.StartLine = startLine; - logBuffer.StartPos = filePos; - LockCookie cookie = UpgradeBufferListLockToWriter(); - AddBufferToList(logBuffer); - DowngradeBufferListLockFromWriter(ref cookie); - } - else - { - logBuffer = _bufferList[_bufferList.Count - 1]; - - if (!logBuffer.FileInfo.FullName.Equals(logFileInfo.FullName)) - { - logBuffer = new LogBuffer(logFileInfo, _MAX_LINES_PER_BUFFER); - logBuffer.StartLine = startLine; - logBuffer.StartPos = filePos; - LockCookie cookie = UpgradeBufferListLockToWriter(); - AddBufferToList(logBuffer); - DowngradeBufferListLockFromWriter(ref cookie); - } - - _disposeLock.AcquireReaderLock(Timeout.Infinite); - if (logBuffer.IsDisposed) - { - LockCookie cookie = _disposeLock.UpgradeToWriterLock(Timeout.Infinite); - ReReadBuffer(logBuffer); - _disposeLock.DowngradeFromWriterLock(ref cookie); - } - - _disposeLock.ReleaseReaderLock(); - } - - Monitor.Enter(logBuffer); // Lock the buffer - ReleaseBufferListReaderLock(); - int lineCount = logBuffer.LineCount; - int droppedLines = logBuffer.PrevBuffersDroppedLinesSum; - filePos = reader.Position; - - while (ReadLine(reader, logBuffer.StartLine + logBuffer.LineCount, logBuffer.StartLine + logBuffer.LineCount + droppedLines, out var line)) - { - LogLine logLine = new(); - if (_shouldStop) - { - Monitor.Exit(logBuffer); - return; - } - - if (line == null) - { - logBuffer.DroppedLinesCount += 1; - droppedLines++; - continue; - } - - lineCount++; - if (lineCount > _MAX_LINES_PER_BUFFER && reader.IsBufferComplete) - { - OnLoadFile(new LoadFileEventArgs(logFileInfo.FullName, filePos, false, logFileInfo.Length, false)); - - Monitor.Exit(logBuffer); - logBuffer = new LogBuffer(logFileInfo, _MAX_LINES_PER_BUFFER); - Monitor.Enter(logBuffer); - logBuffer.StartLine = lineNum; - logBuffer.StartPos = filePos; - logBuffer.PrevBuffersDroppedLinesSum = droppedLines; - AcquireBufferListWriterLock(); - AddBufferToList(logBuffer); - ReleaseBufferListWriterLock(); - lineCount = 1; - } - - logLine.FullLine = line; - logLine.LineNumber = logBuffer.StartLine + logBuffer.LineCount; - - logBuffer.AddLine(logLine, filePos); - filePos = reader.Position; - lineNum++; - } - - logBuffer.Size = filePos - logBuffer.StartPos; - Monitor.Exit(logBuffer); - _isLineCountDirty = true; - FileSize = reader.Position; - CurrentEncoding = reader.Encoding; // Reader may have detected another encoding - if (!_shouldStop) - { - OnLoadFile(new LoadFileEventArgs(logFileInfo.FullName, filePos, true, _fileLength, false)); - // Fire "Ready" Event - } - } - catch (IOException ioex) - { - _logger.Warn(ioex); - } - } - catch (IOException fe) - { - _logger.Warn(fe, "IOException: "); - _isDeleted = true; - LineCount = 0; - FileSize = 0; - OnFileNotFound(); // notify LogWindow - } - } - - private void AddBufferToList(LogBuffer logBuffer) - { -#if DEBUG - _logger.Debug("AddBufferToList(): {0}/{1}/{2}", logBuffer.StartLine, logBuffer.LineCount, logBuffer.FileInfo.FullName); -#endif - _bufferList.Add(logBuffer); - //UpdateLru(logBuffer); - UpdateLruCache(logBuffer); - } - - private void UpdateLruCache(LogBuffer logBuffer) - { - _lruCacheDictLock.AcquireReaderLock(Timeout.Infinite); - if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out LogBufferCacheEntry cacheEntry)) - { - cacheEntry.Touch(); - } - else - { - LockCookie cookie = _lruCacheDictLock.UpgradeToWriterLock(Timeout.Infinite); - if (!_lruCacheDict.TryGetValue(logBuffer.StartLine, out cacheEntry) - ) // #536: re-test, because multiple threads may have been waiting for writer lock - { - cacheEntry = new LogBufferCacheEntry(); - cacheEntry.LogBuffer = logBuffer; - try - { - _lruCacheDict.Add(logBuffer.StartLine, cacheEntry); - } - catch (ArgumentException e) - { - _logger.Error(e, "Error in LRU cache: " + e.Message); -#if DEBUG // there seems to be a bug with double added key - - _logger.Info("Added buffer:"); - DumpBufferInfos(logBuffer); - if (_lruCacheDict.TryGetValue(logBuffer.StartLine, out LogBufferCacheEntry existingEntry)) - { - _logger.Info("Existing buffer: "); - DumpBufferInfos(existingEntry.LogBuffer); - } - else - { - _logger.Warn("Ooops? Cannot find the already existing entry in LRU."); - } -#endif - _lruCacheDictLock.ReleaseLock(); - throw; - } - } - - _lruCacheDictLock.DowngradeFromWriterLock(ref cookie); - } - - _lruCacheDictLock.ReleaseReaderLock(); - } - - /// - /// Sets a new start line in the given buffer and updates the LRU cache, if the buffer - /// is present in the cache. The caller must have write lock for 'lruCacheDictLock'; - /// - /// - /// - private void SetNewStartLineForBuffer(LogBuffer logBuffer, int newLineNum) - { - Util.AssertTrue(_lruCacheDictLock.IsWriterLockHeld, "No writer lock for lru cache"); - if (_lruCacheDict.ContainsKey(logBuffer.StartLine)) - { - _lruCacheDict.Remove(logBuffer.StartLine); - logBuffer.StartLine = newLineNum; - LogBufferCacheEntry cacheEntry = new(); - cacheEntry.LogBuffer = logBuffer; - _lruCacheDict.Add(logBuffer.StartLine, cacheEntry); - } - else - { - logBuffer.StartLine = newLineNum; - } - } - - private void GarbageCollectLruCache() - { -#if DEBUG - long startTime = Environment.TickCount; -#endif - _logger.Debug("Starting garbage collection"); - int threshold = 10; - _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); - int diff = 0; - if (_lruCacheDict.Count - (_MAX_BUFFERS + threshold) > 0) - { - diff = _lruCacheDict.Count - _MAX_BUFFERS; -#if DEBUG - if (diff > 0) - { - _logger.Info("Removing {0} entries from LRU cache for {1}", diff, Util.GetNameFromPath(_fileName)); - } -#endif - SortedList useSorterList = []; - // sort by usage counter - foreach (LogBufferCacheEntry entry in _lruCacheDict.Values) - { - if (!useSorterList.ContainsKey(entry.LastUseTimeStamp)) - { - useSorterList.Add(entry.LastUseTimeStamp, entry.LogBuffer.StartLine); - } - } - - // remove first entries (least usage) - _disposeLock.AcquireWriterLock(Timeout.Infinite); - for (int i = 0; i < diff; ++i) - { - if (i >= useSorterList.Count) - { - break; - } - - int startLine = useSorterList.Values[i]; - LogBufferCacheEntry entry = _lruCacheDict[startLine]; - _lruCacheDict.Remove(startLine); - entry.LogBuffer.DisposeContent(); - } - - _disposeLock.ReleaseWriterLock(); - } - - _lruCacheDictLock.ReleaseWriterLock(); -#if DEBUG - if (diff > 0) - { - long endTime = Environment.TickCount; - _logger.Info("Garbage collector time: " + (endTime - startTime) + " ms."); - } -#endif - } - - private void GarbageCollectorThreadProc() - { - while (!_shouldStop) - { - try - { - Thread.Sleep(10000); - } - catch (Exception) - { - } - - GarbageCollectLruCache(); - } - } - - // private void UpdateLru(LogBuffer logBuffer) - // { - // lock (this.monitor) - // { - // int index; - // if (this.lruDict.TryGetValue(logBuffer.StartLine, out index)) - // { - // RemoveBufferFromLru(logBuffer, index); - // AddBufferToLru(logBuffer); - // } - // else - // { - // if (this.bufferLru.Count > MAX_BUFFERS - 1) - // { - // LogBuffer looser = this.bufferLru[0]; - // if (looser != null) - // { - //#if DEBUG - // _logger.logDebug("Disposing buffer: " + looser.StartLine + "/" + looser.LineCount + "/" + looser.FileInfo.FileName); - //#endif - // looser.DisposeContent(); - // RemoveBufferFromLru(looser); - // } - // } - // AddBufferToLru(logBuffer); - // } - // } - // } - - ///// - ///// Removes a LogBuffer from the LRU. Note that the LogBuffer is searched in the lruDict - ///// via StartLine. So this property must have a consistent value. - ///// - ///// - //private void RemoveBufferFromLru(LogBuffer buffer) - //{ - // int index; - // lock (this.monitor) - // { - // if (this.lruDict.TryGetValue(buffer.StartLine, out index)) - // { - // RemoveBufferFromLru(buffer, index); - // } - // } - //} - - ///// - ///// Removes a LogBuffer from the LRU with known index. Note that the LogBuffer is searched in the lruDict - ///// via StartLine. So this property must have a consistent value. - ///// - ///// - ///// - //private void RemoveBufferFromLru(LogBuffer buffer, int index) - //{ - // lock (this.monitor) - // { - // this.bufferLru.RemoveAt(index); - // this.lruDict.Remove(buffer.StartLine); - // // adjust indizes, they have changed because of the remove - // for (int i = index; i < this.bufferLru.Count; ++i) - // { - // this.lruDict[this.bufferLru[i].StartLine] = this.lruDict[this.bufferLru[i].StartLine] - 1; - // } - // } - //} - - //private void AddBufferToLru(LogBuffer logBuffer) - //{ - // lock (this.monitor) - // { - // this.bufferLru.Add(logBuffer); - // int newIndex = this.bufferLru.Count - 1; - // this.lruDict[logBuffer.StartLine] = newIndex; - // } - //} - - private void ClearLru() - { - //lock (this.monitor) - //{ - // foreach (LogBuffer buffer in this.bufferLru) - // { - // buffer.DisposeContent(); - // } - // this.bufferLru.Clear(); - // this.lruDict.Clear(); - //} - _logger.Info("Clearing LRU cache."); - _lruCacheDictLock.AcquireWriterLock(Timeout.Infinite); - _disposeLock.AcquireWriterLock(Timeout.Infinite); - foreach (LogBufferCacheEntry entry in _lruCacheDict.Values) - { - entry.LogBuffer.DisposeContent(); - } - - _lruCacheDict.Clear(); - _disposeLock.ReleaseWriterLock(); - _lruCacheDictLock.ReleaseWriterLock(); - _logger.Info("Clearing done."); - } - - private void ReReadBuffer(LogBuffer logBuffer) - { -#if DEBUG - _logger.Info("re-reading buffer: {0}/{1}/{2}", logBuffer.StartLine, logBuffer.LineCount, logBuffer.FileInfo.FullName); -#endif - try - { - Monitor.Enter(logBuffer); - Stream fileStream = null; - try - { - fileStream = logBuffer.FileInfo.OpenStream(); - } - catch (IOException e) - { - _logger.Warn(e); - return; - } - - try - { - ILogStreamReader reader = GetLogStreamReader(fileStream, EncodingOptions, UseNewReader); - - long filePos = logBuffer.StartPos; - reader.Position = logBuffer.StartPos; - int maxLinesCount = logBuffer.LineCount; - int lineCount = 0; - int dropCount = logBuffer.PrevBuffersDroppedLinesSum; - logBuffer.ClearLines(); - - while (ReadLine(reader, logBuffer.StartLine + logBuffer.LineCount, logBuffer.StartLine + logBuffer.LineCount + dropCount, out string line)) - { - if (lineCount >= maxLinesCount) - { - break; - } - - if (line == null) - { - dropCount++; - continue; - } - - LogLine logLine = new() - { - FullLine = line, - LineNumber = logBuffer.StartLine + logBuffer.LineCount - }; - - logBuffer.AddLine(logLine, filePos); - filePos = reader.Position; - lineCount++; - } - - if (maxLinesCount != logBuffer.LineCount) - { - _logger.Warn("LineCount in buffer differs after re-reading. old={0}, new={1}", maxLinesCount, logBuffer.LineCount); - } - - if (dropCount - logBuffer.PrevBuffersDroppedLinesSum != logBuffer.DroppedLinesCount) - { - _logger.Warn("DroppedLinesCount in buffer differs after re-reading. old={0}, new={1}", logBuffer.DroppedLinesCount, dropCount); - logBuffer.DroppedLinesCount = dropCount - logBuffer.PrevBuffersDroppedLinesSum; - } - - GC.KeepAlive(fileStream); - } - catch (IOException e) - { - _logger.Warn(e); - } - finally - { - fileStream.Close(); - } - } - finally - { - Monitor.Exit(logBuffer); - } - } - - private LogBuffer GetBufferForLine(int lineNum) - { -#if DEBUG - long startTime = Environment.TickCount; -#endif - LogBuffer logBuffer = null; - AcquireBufferListReaderLock(); - //if (lineNum == this.lastReturnedLineNumForBuffer) - //{ - // return this.lastReturnedBuffer; - //} - - //int startIndex = lineNum / LogBuffer.MAX_LINES; // doesn't work anymore since XML buffer may contain more lines than MAX_LINES - int startIndex = 0; - int count = _bufferList.Count; - for (int i = startIndex; i < count; ++i) - { - logBuffer = _bufferList[i]; - if (lineNum >= logBuffer.StartLine && lineNum < logBuffer.StartLine + logBuffer.LineCount) - { - //UpdateLru(logBuffer); - UpdateLruCache(logBuffer); - //this.lastReturnedLineNumForBuffer = lineNum; - //this.lastReturnedBuffer = logBuffer; - break; - } - } -#if DEBUG - long endTime = Environment.TickCount; - //_logger.logDebug("getBufferForLine(" + lineNum + ") duration: " + ((endTime - startTime)) + " ms. Buffer start line: " + logBuffer.StartLine); -#endif - ReleaseBufferListReaderLock(); - return logBuffer; - } - - /// - /// Async callback used to check if the GetLogLine() call is succeeding again after a detected timeout. - /// - private void GetLineFinishedCallback(ILogLine line) - { - _isFailModeCheckCallPending = false; - if (line != null) - { - _logger.Debug("'isFastFailOnGetLogLine' flag was reset"); - _isFastFailOnGetLogLine = false; - } - - _logger.Debug("'isLogLineCallPending' flag was reset."); - } - - private LogBuffer GetFirstBufferForFileByLogBuffer(LogBuffer logBuffer) - { - ILogFileInfo info = logBuffer.FileInfo; - AcquireBufferListReaderLock(); - int index = _bufferList.IndexOf(logBuffer); - if (index == -1) - { - ReleaseBufferListReaderLock(); - return null; - } - - LogBuffer resultBuffer = logBuffer; - while (true) - { - index--; - if (index < 0 || _bufferList[index].FileInfo != info) - { - break; - } - - resultBuffer = _bufferList[index]; - } - - ReleaseBufferListReaderLock(); - return resultBuffer; - } - - private void MonitorThreadProc() - { - Thread.CurrentThread.Name = "MonitorThread"; - //IFileSystemPlugin fs = PluginRegistry.GetInstance().FindFileSystemForUri(this.watchedILogFileInfo.FullName); - _logger.Info("MonitorThreadProc() for file {0}", _watchedILogFileInfo.FullName); - - long oldSize = 0; - try - { - OnLoadingStarted(new LoadFileEventArgs(_fileName, 0, false, 0, false)); - ReadFiles(); - if (!_isDeleted) - { - oldSize = _fileLength; - OnLoadingFinished(); - } - } - catch (Exception e) - { - _logger.Error(e); - } - - while (!_shouldStop) - { - try - { - int pollInterval = _watchedILogFileInfo.PollInterval; - //#if DEBUG - // if (_logger.IsDebug) - // { - // _logger.logDebug("Poll interval for " + this.fileName + ": " + pollInterval); - // } - //#endif - Thread.Sleep(pollInterval); - } - catch (Exception e) - { - _logger.Error(e); - } - - if (_shouldStop) - { - return; - } - - try - { - if (_watchedILogFileInfo.FileHasChanged()) - { - _fileLength = _watchedILogFileInfo.Length; - if (_fileLength == -1) - { - MonitoredFileNotFound(); - } - else - { - oldSize = _fileLength; - FileChanged(); - } - } - } - catch (FileNotFoundException) - { - MonitoredFileNotFound(); - } - } - } - - private void MonitoredFileNotFound() - { - long oldSize; - if (!_isDeleted) - { - _logger.Debug("File not FileNotFoundException catched. Switching to 'deleted' mode."); - _isDeleted = true; - oldSize = _fileLength = -1; - FileSize = 0; - OnFileNotFound(); // notify LogWindow - } -#if DEBUG - else - { - _logger.Debug("File not FileNotFoundException catched. Already in deleted mode."); - } -#endif - } - - private void FileChanged() - { - if (_isDeleted) - { - OnRespawned(); - // prevent size update events. The window should reload the complete file. - FileSize = _fileLength; - } - - long newSize = _fileLength; - //if (this.currFileSize != newSize) - { - _logger.Info("file size changed. new size={0}, file: {1}", newSize, _fileName); - FireChangeEvent(); - } - } - - private void FireChangeEvent() - { - LogEventArgs args = new(); - args.PrevFileSize = FileSize; - args.PrevLineCount = LineCount; - long newSize = _fileLength; - if (newSize < FileSize || _isDeleted) - { - _logger.Info("File was created anew: new size={0}, oldSize={1}", newSize, FileSize); - // Fire "New File" event - FileSize = 0; - LineCount = 0; - try - { - if (!IsMultiFile) - { - // ReloadBufferList(); // removed because reloading is triggered by owning LogWindow - // Trigger "new file" handling (reload) - OnLoadFile(new LoadFileEventArgs(_fileName, 0, true, _fileLength, true)); - - if (_isDeleted) - { - args.FileSize = newSize; - args.LineCount = LineCount; - if (args.PrevLineCount != args.LineCount && !_shouldStop) - { - OnFileSizeChanged(args); - } - } - - _isDeleted = false; - } - else - { - int offset = ShiftBuffers(); - //this.currFileSize = newSize; // removed because ShiftBuffers() calls ReadToBuffer() which will set the actual read size - args.FileSize = newSize; - args.LineCount = LineCount; - args.IsRollover = true; - args.RolloverOffset = offset; - _isDeleted = false; - if (!_shouldStop) - { - OnFileSizeChanged(args); - } - } - } - catch (FileNotFoundException e) - { - // trying anew in next poll intervall. So let currFileSize untouched. - _logger.Warn(e); - } - } - else - { - ReadToBufferList(_watchedILogFileInfo, FileSize, LineCount); - args.FileSize = newSize; - args.LineCount = LineCount; - //if (args.PrevLineCount != args.LineCount && !this.shouldStop) - OnFileSizeChanged(args); - } - } - - private ILogStreamReader GetLogStreamReader(Stream stream, EncodingOptions encodingOptions, bool useNewReader) - { - ILogStreamReader reader = CreateLogStreamReader(stream, encodingOptions, useNewReader); - - return IsXmlMode ? new XmlBlockSplitter(new XmlLogReader(reader), XmlLogConfig) : reader; - } - - private ILogStreamReader CreateLogStreamReader(Stream stream, EncodingOptions encodingOptions, bool useSystemReader) - { - if (useSystemReader) - { - return new PositionAwareStreamReaderSystem(stream, encodingOptions); - } - - return new PositionAwareStreamReaderLegacy(stream, encodingOptions); - } - - private bool ReadLine(ILogStreamReader reader, int lineNum, int realLineNum, out string outLine) - { - string line = null; - try - { - line = reader.ReadLine(); - } - catch (IOException e) - { - _logger.Warn(e); - } - catch (NotSupportedException e) - { - // Bug#11: "Reading operations are not supported by the stream" - // Currently not reproducible. Probably happens at an unlucky time interval (after opening the file) - // when the file is being deleted (rolling) - // This will be handled as EOF. - _logger.Warn(e); - } - - if (line == null) // EOF or catched Exception - { - outLine = null; - return false; - } - - if (PreProcessColumnizer != null) - { - line = PreProcessColumnizer.PreProcessLine(line, lineNum, realLineNum); - } - - outLine = line; - return true; - } - - private void AcquireBufferListReaderLock() - { - try - { - _bufferListLock.AcquireReaderLock(10000); -#if DEBUG && TRACE_LOCKS - StackTrace st = new StackTrace(true); - StackFrame callerFrame = st.GetFrame(2); - this.bufferListLockInfo = -"Read lock from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); -#endif - } - catch (ApplicationException e) - { - _logger.Warn(e, "Reader lock wait for bufferList timed out. Now trying infinite."); -#if DEBUG && TRACE_LOCKS - _logger.logInfo(this.bufferListLockInfo); -#endif - _bufferListLock.AcquireReaderLock(Timeout.Infinite); - } - } - - private void ReleaseBufferListReaderLock() - { - _bufferListLock.ReleaseReaderLock(); - } - - private void AcquireBufferListWriterLock() - { - try - { - _bufferListLock.AcquireWriterLock(10000); -#if DEBUG && TRACE_LOCKS - StackTrace st = new StackTrace(true); - StackFrame callerFrame = st.GetFrame(1); - this.bufferListLockInfo = -"Write lock from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); - callerFrame.GetFileName(); -#endif - } - catch (ApplicationException e) - { - _logger.Warn(e, "Writer lock wait for bufferList timed out. Now trying infinite."); -#if DEBUG && TRACE_LOCKS - _logger.logInfo(this.bufferListLockInfo); -#endif - _bufferListLock.AcquireWriterLock(Timeout.Infinite); - } - } - - private void ReleaseBufferListWriterLock() - { - _bufferListLock.ReleaseWriterLock(); - } - - private LockCookie UpgradeBufferListLockToWriter() - { - try - { - LockCookie cookie = _bufferListLock.UpgradeToWriterLock(10000); -#if DEBUG && TRACE_LOCKS - StackTrace st = new StackTrace(true); - StackFrame callerFrame = st.GetFrame(2); - this.bufferListLockInfo += -", upgraded to writer from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); -#endif - return cookie; - } - catch (ApplicationException e) - { - _logger.Warn(e, "Writer lock update wait for bufferList timed out. Now trying infinite."); -#if DEBUG && TRACE_LOCKS - _logger.logInfo(this.bufferListLockInfo); -#endif - return _bufferListLock.UpgradeToWriterLock(Timeout.Infinite); - } - } - - private void DowngradeBufferListLockFromWriter(ref LockCookie cookie) - { - _bufferListLock.DowngradeFromWriterLock(ref cookie); -#if DEBUG && TRACE_LOCKS - StackTrace st = new StackTrace(true); - StackFrame callerFrame = st.GetFrame(2); - this.bufferListLockInfo += -", downgraded to reader from " + callerFrame.GetMethod().DeclaringType.Name + "." + callerFrame.GetMethod().Name + "() " + callerFrame.GetFileLineNumber(); -#endif - } - -#if DEBUG - private void DumpBufferInfos(LogBuffer buffer) - { - if (_logger.IsTraceEnabled) - { - _logger.Trace("StartLine: {0}\r\nLineCount: {1}\r\nStartPos: {2}\r\nSize: {3}\r\nDisposed: {4}\r\nDisposeCount: {5}\r\nFile: {6}", - buffer.StartLine, - buffer.LineCount, - buffer.StartPos, - buffer.Size, - buffer.IsDisposed ? "yes" : "no", - buffer.DisposeCount, - buffer.FileInfo.FullName); - } - } - -#endif - - #endregion - - ~LogfileReader() - { - DeleteAllContent(); - } - - protected virtual void OnFileSizeChanged(LogEventArgs e) - { - FileSizeChanged?.Invoke(this, e); - } - - protected virtual void OnLoadFile(LoadFileEventArgs e) - { - LoadFile?.Invoke(this, e); - } - - protected virtual void OnLoadingStarted(LoadFileEventArgs e) - { - LoadingStarted?.Invoke(this, e); - } - - protected virtual void OnLoadingFinished() - { - LoadingFinished?.Invoke(this, EventArgs.Empty); - } - - protected virtual void OnFileNotFound() - { - FileNotFound?.Invoke(this, EventArgs.Empty); - } - - protected virtual void OnRespawned() - { - _logger.Info("OnRespawned()"); - Respawned?.Invoke(this, EventArgs.Empty); - } - - private class LogLine : ILogLine - { - #region Properties - - public string FullLine { get; set; } - - public int LineNumber { get; set; } - - string ITextValue.Text => FullLine; - - #endregion - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/PositionAwareStreamReaderBase.cs b/src/LogExpert/Classes/Log/PositionAwareStreamReaderBase.cs deleted file mode 100644 index 68e46989..00000000 --- a/src/LogExpert/Classes/Log/PositionAwareStreamReaderBase.cs +++ /dev/null @@ -1,224 +0,0 @@ -using LogExpert.Config; -using LogExpert.Entities; - -using System; -using System.IO; -using System.Text; - -namespace LogExpert.Classes.Log -{ - public abstract class PositionAwareStreamReaderBase : LogStreamReaderBase - { - #region Fields - - private const int MAX_LINE_LEN = 20000; - - private static readonly Encoding[] _preambleEncodings = { Encoding.UTF8, Encoding.Unicode, Encoding.BigEndianUnicode, Encoding.UTF32 }; - - private readonly BufferedStream _stream; - private readonly StreamReader _reader; - - private readonly int _preambleLength; - private readonly int _posIncPrecomputed; - - private long _position; - - #endregion - - #region cTor - - protected PositionAwareStreamReaderBase(Stream stream, EncodingOptions encodingOptions) - { - _stream = new BufferedStream(stream); - - _preambleLength = DetectPreambleLengthAndEncoding(out Encoding detectedEncoding); - - Encoding usedEncoding = GetUsedEncoding(encodingOptions, detectedEncoding); - _posIncPrecomputed = GetPosIncPrecomputed(usedEncoding); - - _reader = new StreamReader(_stream, usedEncoding, true); - - Position = 0; - } - - #endregion - - #region Properties - - /// - /// Current position in the stream. - /// - public sealed override long Position - { - get => _position; - set - { - /* - * 1: Sometime commented (+Encoding.GetPreamble().Length) - * 2: Date 1.1 3207 - * 3: Error Message from Piet because of Unicode-Bugs. - * No Idea, if this is OK. - * 4: 27.07.09: Preamble-Length is now calculated in CT, because Encoding.GetPreamble().Length - * always delivers a fixed length (does not mater what kind of data) - */ - _position = value; // +Encoding.GetPreamble().Length; // 1 - //stream.Seek(pos, SeekOrigin.Begin); // 2 - //stream.Seek(pos + Encoding.GetPreamble().Length, SeekOrigin.Begin); // 3 - _stream.Seek(_position + _preambleLength, SeekOrigin.Begin); // 4 - - ResetReader(); - } - } - - public sealed override Encoding Encoding => _reader.CurrentEncoding; - - public sealed override bool IsBufferComplete => true; - - protected static int MaxLineLen => ConfigManager.Settings.Preferences.MaxLineLength; - - #endregion - - #region Public methods - - /// - /// Destroy and release the current stream reader. - /// - /// Specifies whether or not the managed objects should be released. - protected override void Dispose(bool disposing) - { - if (disposing) - { - _stream.Dispose(); - _reader.Dispose(); - } - } - - public override unsafe int ReadChar() - { - if (IsDisposed) - { - throw new ObjectDisposedException(ToString()); - } - - try - { - int readInt = _reader.Read(); - if (readInt != -1) - { - char readChar = (char)readInt; - if (_posIncPrecomputed != 0) - { - _position += _posIncPrecomputed; - } - else - { - _position += _reader.CurrentEncoding.GetByteCount(&readChar, 1); - } - } - return readInt; - } - catch (IOException) - { - return -1; - } - } - - protected virtual void ResetReader() - { - _reader.DiscardBufferedData(); - } - - protected StreamReader GetStreamReader() - { - return IsDisposed ? throw new ObjectDisposedException(ToString()) : _reader; - } - - protected void MovePosition(int offset) - { - _position += offset; - } - - #endregion - - #region Private Methods - - /// - /// Determines the actual number of preamble bytes in the file. - /// - /// Number of preamble bytes in the file - private int DetectPreambleLengthAndEncoding(out Encoding detectedEncoding) - { - /* - UTF-8: EF BB BF - UTF-16-Big-Endian-Byteorder: FE FF - UTF-16-Little-Endian-Byteorder: FF FE - UTF-32-Big-Endian-Byteorder: 00 00 FE FF - UTF-32-Little-Endian-Byteorder: FF FE 00 00 - */ - - byte[] readPreamble = new byte[4]; - int readLen = _stream.Read(readPreamble, 0, 4); - if (readLen >= 2) - { - foreach (Encoding encoding in _preambleEncodings) - { - byte[] preamble = encoding.GetPreamble(); - bool fail = false; - for (int i = 0; i < readLen && i < preamble.Length; ++i) - { - if (readPreamble[i] != preamble[i]) - { - fail = true; - break; - } - } - - if (!fail) - { - detectedEncoding = encoding; - return preamble.Length; - } - } - } - - // not found or less than 2 byte read - detectedEncoding = null; - return 0; - } - - private Encoding GetUsedEncoding(EncodingOptions encodingOptions, Encoding detectedEncoding) - { - if (encodingOptions.Encoding != null) - { - return encodingOptions.Encoding; - } - - if (detectedEncoding != null) - { - return detectedEncoding; - } - - return encodingOptions.DefaultEncoding ?? Encoding.Default; - } - private int GetPosIncPrecomputed(Encoding usedEncoding) - { - switch (usedEncoding) - { - case UTF8Encoding _: - { - return 0; - } - case UnicodeEncoding _: - { - return 2; - } - default: - { - return 1; - } - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/PositionAwareStreamReaderLegacy.cs b/src/LogExpert/Classes/Log/PositionAwareStreamReaderLegacy.cs deleted file mode 100644 index 594eccff..00000000 --- a/src/LogExpert/Classes/Log/PositionAwareStreamReaderLegacy.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System.IO; -using LogExpert.Entities; - -namespace LogExpert.Classes.Log -{ - public class PositionAwareStreamReaderLegacy : PositionAwareStreamReaderBase - { - #region Fields - - private readonly char[] _charBuffer = new char[MaxLineLen]; - - private int _charBufferPos; - private bool _crDetect; - - #endregion - - #region cTor - - public PositionAwareStreamReaderLegacy(Stream stream, EncodingOptions encodingOptions) : base(stream, encodingOptions) - { - - } - - #endregion - - #region Public methods - - public override string ReadLine() - { - int readInt; - - while (-1 != (readInt = ReadChar())) - { - char readChar = (char)readInt; - - switch (readChar) - { - case '\n': - { - _crDetect = false; - return GetLineAndResetCharBufferPos(); - } - case '\r': - { - if (_crDetect) - { - return GetLineAndResetCharBufferPos(); - } - - _crDetect = true; - break; - } - default: - { - if (_crDetect) - { - _crDetect = false; - string line = GetLineAndResetCharBufferPos(); - AppendToCharBuffer(readChar); - return line; - } - - AppendToCharBuffer(readChar); - break; - } - } - } - - string result = GetLineAndResetCharBufferPos(); - if (readInt == -1 && result.Length == 0 && !_crDetect) - { - return null; // EOF - } - _crDetect = false; - return result; - } - - protected override void ResetReader() - { - ResetCharBufferPos(); - - base.ResetReader(); - } - - #endregion - - #region Private Methods - - private string GetLineAndResetCharBufferPos() - { - string result = new(_charBuffer, 0, _charBufferPos); - ResetCharBufferPos(); - return result; - } - - private void AppendToCharBuffer(char readChar) - { - if (_charBufferPos < MaxLineLen) - { - _charBuffer[_charBufferPos++] = readChar; - } - } - - private void ResetCharBufferPos() - { - _charBufferPos = 0; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/PositionAwareStreamReaderSystem.cs b/src/LogExpert/Classes/Log/PositionAwareStreamReaderSystem.cs deleted file mode 100644 index c74b30df..00000000 --- a/src/LogExpert/Classes/Log/PositionAwareStreamReaderSystem.cs +++ /dev/null @@ -1,96 +0,0 @@ -using System.IO; -using LogExpert.Entities; - -namespace LogExpert.Classes.Log -{ - /// - /// This class is responsible for reading line from the log file. It also decodes characters with the appropriate charset encoding. - /// PositionAwareStreamReaderSystem tries a BOM detection to determine correct file offsets when directly seeking into the file (on re-loading flushed buffers). - /// UTF-8 handling is a bit slower, because after reading a character the byte length of the character must be determined. - /// Lines are read char-by-char. StreamReader.ReadLine() is not used because StreamReader cannot tell a file position. - /// - public class PositionAwareStreamReaderSystem : PositionAwareStreamReaderBase - { - #region Fields - - private const int CHAR_CR = 0x0D; - private const int CHAR_LF = 0x0A; - - private int _newLineSequenceLength; - - #endregion - - #region cTor - - public PositionAwareStreamReaderSystem(Stream stream, EncodingOptions encodingOptions) : base(stream, encodingOptions) - { - - } - - #endregion - - #region Public methods - - public override string ReadLine() - { - StreamReader reader = GetStreamReader(); - - if (_newLineSequenceLength == 0) - { - _newLineSequenceLength = GuessNewLineSequenceLength(reader); - } - - string line = reader.ReadLine(); - - if (line != null) - { - MovePosition(Encoding.GetByteCount(line) + _newLineSequenceLength); - - if (line.Length > MaxLineLen) - { - line = line.Remove(MaxLineLen); - } - } - - return line; - } - - #endregion - - #region Private Methods - - private int GuessNewLineSequenceLength(StreamReader reader) - { - long currentPos = Position; - - try - { - string line = reader.ReadLine(); - - if (line != null) - { - Position += Encoding.GetByteCount(line); - - int firstChar = reader.Read(); - if (firstChar == CHAR_CR) // check \r - { - int secondChar = reader.Read(); - if (secondChar == CHAR_LF) // check \n - { - return Encoding.GetByteCount("\r\n"); - } - } - return Encoding.GetByteCount(((char)firstChar).ToString()); - } - - return 0; - } - finally - { - Position = currentPos; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/RolloverFilenameBuilder.cs b/src/LogExpert/Classes/Log/RolloverFilenameBuilder.cs deleted file mode 100644 index f2cdc7c9..00000000 --- a/src/LogExpert/Classes/Log/RolloverFilenameBuilder.cs +++ /dev/null @@ -1,238 +0,0 @@ -using System; -using System.Globalization; -using System.Text; -using System.Text.RegularExpressions; - -namespace LogExpert.Classes.Log -{ - /* Needed info: - * - Date/time mask - * - index counters - * - counter direction (up/down) - * - counter limit - * - whether the files are shifted or not - * - whether the indexes start with zero (or n/a) on a new date period - * - * Format: - * *$D(yyyy-MM-dd)$I - * *$J(.) - * - * *(yyyy-MM-dd)[I] - * - */ - - /// - /// This class is responsible for building file names for multifile. - /// - public class RolloverFilenameBuilder - { - #region Fields - - private string _condContent; - private Group _condGroup; - private string _currentFileName; - - private Group _dateGroup; - - //private Regex regexCond; - private DateTime _dateTime; - - //private DateTimeFormatInfo dateFormat; - private string _dateTimeFormat; - - private bool _hideZeroIndex; - private Group _indexGroup; - private Regex _regex; - - #endregion - - #region cTor - - public RolloverFilenameBuilder(string formatString) - { - ParseFormatString(formatString); - } - - #endregion - - #region Properties - - public int Index { get; set; } - - public bool IsDatePattern => _dateGroup != null && _dateGroup.Success; - - public bool IsIndexPattern => _indexGroup != null && _indexGroup.Success; - - #endregion - - #region Public methods - - public void SetFileName(string fileName) - { - _currentFileName = fileName; - Match match = _regex.Match(fileName); - if (match.Success) - { - _dateGroup = match.Groups["date"]; - if (_dateGroup.Success) - { - string date = fileName.Substring(_dateGroup.Index, _dateGroup.Length); - if (DateTime.TryParseExact(date, _dateTimeFormat, DateTimeFormatInfo.InvariantInfo, - DateTimeStyles.None, - out _dateTime)) - { - } - } - _indexGroup = match.Groups["index"]; - if (_indexGroup.Success) - { - Index = _indexGroup.Value.Length > 0 ? int.Parse(_indexGroup.Value) : 0; - } - _condGroup = match.Groups["cond"]; - } - } - - public void IncrementDate() - { - _dateTime = _dateTime.AddDays(1); - } - - public void DecrementDate() - { - _dateTime = _dateTime.AddDays(-1); - } - - - public string BuildFileName() - { - string fileName = _currentFileName; - if (_dateGroup != null && _dateGroup.Success) - { - string newDate = _dateTime.ToString(_dateTimeFormat, DateTimeFormatInfo.InvariantInfo); - fileName = fileName.Remove(_dateGroup.Index, _dateGroup.Length); - fileName = fileName.Insert(_dateGroup.Index, newDate); - } - - if (_indexGroup != null && _indexGroup.Success) - { - fileName = fileName.Remove(_indexGroup.Index, _indexGroup.Length); - - if (!_hideZeroIndex || Index > 0) - { - string format = "D" + _indexGroup.Length; - fileName = fileName.Insert(_indexGroup.Index, Index.ToString(format)); - if (_hideZeroIndex && _condContent != null) - { - fileName = fileName.Insert(_indexGroup.Index, _condContent); - } - } - } - - // this.currentFileName = fileName; - // SetFileName(fileName); - return fileName; - } - - #endregion - - #region Private Methods - - private void ParseFormatString(string formatString) - { - string fmt = EscapeNonvarRegions(formatString); - int datePos = formatString.IndexOf("$D("); - if (datePos != -1) - { - int endPos = formatString.IndexOf(')', datePos); - if (endPos != -1) - { - _dateTimeFormat = formatString.Substring(datePos + 3, endPos - datePos - 3); - _dateTimeFormat = _dateTimeFormat.ToUpper(); - _dateTimeFormat = _dateTimeFormat.Replace('D', 'd').Replace('Y', 'y'); - - string dtf = _dateTimeFormat; - dtf = dtf.ToUpper(); - dtf = dtf.Replace("D", "\\d"); - dtf = dtf.Replace("Y", "\\d"); - dtf = dtf.Replace("M", "\\d"); - fmt = fmt.Remove(datePos, 2); // remove $D - fmt = fmt.Remove(datePos + 1, _dateTimeFormat.Length); // replace with regex version of format - fmt = fmt.Insert(datePos + 1, dtf); - fmt = fmt.Insert(datePos + 1, "?'date'"); // name the regex group - } - } - - int condPos = fmt.IndexOf("$J("); - if (condPos != -1) - { - int endPos = fmt.IndexOf(')', condPos); - if (endPos != -1) - { - _condContent = fmt.Substring(condPos + 3, endPos - condPos - 3); - fmt = fmt.Remove(condPos + 2, endPos - condPos - 1); - } - } - - fmt = fmt.Replace("*", ".*"); - _hideZeroIndex = fmt.Contains("$J"); - fmt = fmt.Replace("$I", "(?'index'[\\d]+)"); - fmt = fmt.Replace("$J", "(?'index'[\\d]*)"); - - _regex = new Regex(fmt); - } - - private string EscapeNonvarRegions(string formatString) - { - string fmt = formatString.Replace('*', '\xFFFD'); - StringBuilder result = new(); - int state = 0; - StringBuilder segment = new(); - for (int i = 0; i < fmt.Length; ++i) - { - switch (state) - { - case 0: // looking for $ - if (fmt[i] == '$') - { - result.Append(Regex.Escape(segment.ToString())); - segment = new StringBuilder(); - state = 1; - } - segment.Append(fmt[i]); - break; - case 1: // the char behind $ - segment.Append(fmt[i]); - result.Append(segment.ToString()); - segment = new StringBuilder(); - state = 2; - break; - case 2: // checking if ( or other char - if (fmt[i] == '(') - { - segment.Append(fmt[i]); - state = 3; - } - else - { - segment.Append(fmt[i]); - state = 0; - } - break; - case 3: // looking for ) - segment.Append(fmt[i]); - if (fmt[i] == ')') - { - result.Append(segment.ToString()); - segment = new StringBuilder(); - state = 0; - } - break; - } - } - fmt = result.ToString().Replace('\xFFFD', '*'); - return fmt; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Log/RolloverFilenameHandler.cs b/src/LogExpert/Classes/Log/RolloverFilenameHandler.cs deleted file mode 100644 index 00553c35..00000000 --- a/src/LogExpert/Classes/Log/RolloverFilenameHandler.cs +++ /dev/null @@ -1,109 +0,0 @@ -using System.Collections.Generic; -using LogExpert.Entities; - -namespace LogExpert.Classes.Log -{ - /// - /// Handles rollover naming. The names built by the RolloverFilenameBuilder will be used - /// to check if the file exist. Names will be built by incrmenting an index and decrementing a date. - /// A configurable number of days in the past will be checked (date gaps may occur on days without log file activity). - /// Date checking is only performed if the format pattern contains a date format. Index checking - /// is only performed of the format pattern contains an index placeholder. - /// - public class RolloverFilenameHandler - { - #region Fields - - private readonly RolloverFilenameBuilder _filenameBuilder; - private readonly ILogFileInfo _logFileInfo; - private readonly MultiFileOptions _options; - - #endregion - - #region cTor - - /// - /// Constructor. - /// - /// The complete path of the logfile - /// Multifile option (e.g. format pattern) - public RolloverFilenameHandler(ILogFileInfo logFileInfo, MultiFileOptions options) - { - _options = options; - _logFileInfo = logFileInfo; - _filenameBuilder = new RolloverFilenameBuilder(_options.FormatPattern); - _filenameBuilder.SetFileName(logFileInfo.FileName); - } - - #endregion - - #region Public methods - - /// - /// Returns a list of the built file names (complete path) which also exists on disk. - /// The list is created by using the RolloverFilenameBuilder and checking for file existence. - /// The first entry in the list contains the oldest file. The last entry contains the file given - /// in the contructor. - /// - /// - public LinkedList GetNameList() - { - LinkedList fileList = new(); - string fileName = _filenameBuilder.BuildFileName(); - string filePath = _logFileInfo.DirectoryName + _logFileInfo.DirectorySeparatorChar + fileName; - fileList.AddFirst(filePath); - bool found = true; - while (found) - { - found = false; - // increment index and check if file exists - if (_filenameBuilder.IsIndexPattern) - { - _filenameBuilder.Index += 1; - fileName = _filenameBuilder.BuildFileName(); - filePath = _logFileInfo.DirectoryName + _logFileInfo.DirectorySeparatorChar + fileName; - if (FileExists(filePath)) - { - fileList.AddFirst(filePath); - found = true; - continue; - } - } - // if file with index isn't found or no index is in format pattern, decrement the current date - if (_filenameBuilder.IsDatePattern) - { - int tryCounter = 0; - _filenameBuilder.Index = 0; - while (tryCounter < _options.MaxDayTry) - { - _filenameBuilder.DecrementDate(); - fileName = _filenameBuilder.BuildFileName(); - filePath = _logFileInfo.DirectoryName + _logFileInfo.DirectorySeparatorChar + fileName; - if (FileExists(filePath)) - { - fileList.AddFirst(filePath); - found = true; - break; - } - - tryCounter++; - } - } - } - return fileList; - } - - #endregion - - #region Private Methods - - private bool FileExists(string filePath) - { - IFileSystemPlugin fs = PluginRegistry.Instance.FindFileSystemForUri(filePath); - ILogFileInfo info = fs.GetLogfileInfo(filePath); - return info.FileExists; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/LogExpertApplicationContext.cs b/src/LogExpert/Classes/LogExpertApplicationContext.cs index 0a6b49f4..1b3940bb 100644 --- a/src/LogExpert/Classes/LogExpertApplicationContext.cs +++ b/src/LogExpert/Classes/LogExpertApplicationContext.cs @@ -1,36 +1,35 @@ -using System; +using LogExpert.Core.Interface; +using System; using System.Windows.Forms; -using LogExpert.Controls.LogTabWindow; -namespace LogExpert.Classes -{ - internal class LogExpertApplicationContext : ApplicationContext - { - #region Fields +namespace LogExpert.Classes; - private readonly LogExpertProxy _proxy; +internal class LogExpertApplicationContext : ApplicationContext +{ + #region Fields - #endregion + private readonly LogExpertProxy _proxy; - #region cTor + #endregion - public LogExpertApplicationContext(LogExpertProxy proxy, LogTabWindow firstLogWin) - { - _proxy = proxy; - _proxy.LastWindowClosed += new LogExpertProxy.LastWindowClosedEventHandler(OnProxyLastWindowClosed); - firstLogWin.Show(); - } + #region cTor - #endregion + public LogExpertApplicationContext(LogExpertProxy proxy, ILogTabWindow firstLogWin) + { + _proxy = proxy; + _proxy.LastWindowClosed += OnProxyLastWindowClosed; + firstLogWin.Show(); + } - #region Events handler + #endregion - private void OnProxyLastWindowClosed(object sender, EventArgs e) - { - ExitThread(); - Application.Exit(); - } + #region Events handler - #endregion + private void OnProxyLastWindowClosed(object sender, EventArgs e) + { + ExitThread(); + Application.Exit(); } + + #endregion } \ No newline at end of file diff --git a/src/LogExpert/Classes/LogExpertProxy.cs b/src/LogExpert/Classes/LogExpertProxy.cs index 9109a803..558899ab 100644 --- a/src/LogExpert/Classes/LogExpertProxy.cs +++ b/src/LogExpert/Classes/LogExpertProxy.cs @@ -1,178 +1,177 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using LogExpert.Controls.LogTabWindow; -using LogExpert.Grpc; -using LogExpert.Interface; +using LogExpert.Config; +using LogExpert.Core.Interface; +using LogExpert.UI.Controls.LogWindow; +using LogExpert.UI.Extensions.LogWindow; + using NLog; -namespace LogExpert.Classes -{ - internal class LogExpertProxy : LogExpertService.LogExpertServiceBase, ILogExpertProxy - { - #region Fields +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Windows.Forms; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); +namespace LogExpert.Classes; - [NonSerialized] private readonly List _windowList = []; +internal class LogExpertProxy : ILogExpertProxy +{ + #region Fields - [NonSerialized] private LogTabWindow _firstLogTabWindow; + private static readonly Logger _logger = LogManager.GetCurrentClassLogger(); - [NonSerialized] private int _logWindowIndex = 1; + [NonSerialized] private readonly List _windowList = []; - #endregion + [NonSerialized] private ILogTabWindow _firstLogTabWindow; - #region cTor + [NonSerialized] private int _logWindowIndex = 1; - public LogExpertProxy(LogTabWindow logTabWindow) - { - AddWindow(logTabWindow); - logTabWindow.LogExpertProxy = this; - _firstLogTabWindow = logTabWindow; - } + #endregion - #endregion + #region cTor - #region Delegates + public LogExpertProxy(ILogTabWindow logTabWindow) + { + AddWindow(logTabWindow); + logTabWindow.LogExpertProxy = this; + _firstLogTabWindow = logTabWindow; + } - //public void BroadcastSettingsChanged(Object cookie) - //{ - // lock (this.windowList) - // { - // foreach (LogTabWindow logTabWindow in this.windowList) - // { - // logTabWindow.NotifySettingsChanged(cookie); - // } - // } - //} + #endregion + #region Delegates - public delegate void LastWindowClosedEventHandler(object sender, EventArgs e); + //public void BroadcastSettingsChanged(Object cookie) + //{ + // lock (this.windowList) + // { + // foreach (LogTabWindow logTabWindow in this.windowList) + // { + // logTabWindow.NotifySettingsChanged(cookie); + // } + // } + //} - #endregion + #endregion - #region Events + #region Events - public event LastWindowClosedEventHandler LastWindowClosed; + public event EventHandler LastWindowClosed; - #endregion + #endregion - #region Public methods + #region Public methods - public void LoadFiles(string[] fileNames) - { - _logger.Info("Loading files into existing LogTabWindow"); - LogTabWindow logWin = _windowList[^1]; - _ = logWin.Invoke(new MethodInvoker(logWin.SetForeground)); - logWin.LoadFiles(fileNames); - } + public void LoadFiles(string[] fileNames) + { + _logger.Info(CultureInfo.InvariantCulture, "Loading files into existing LogTabWindow"); + ILogTabWindow logWin = _windowList[^1]; + _ = logWin.Invoke(new MethodInvoker(logWin.SetForeground)); + logWin.LoadFiles(fileNames); + } - public void NewWindow(string[] fileNames) + public void NewWindow(string[] fileNames) + { + if (_firstLogTabWindow.IsDisposed) { - if (_firstLogTabWindow.IsDisposed) + _logger.Warn(CultureInfo.InvariantCulture, "first GUI thread window is disposed. Setting a new one."); + // may occur if a window is closed because of unhandled exception. + // Determine a new 'firstWindow'. If no window is left, start a new one. + RemoveWindow(_firstLogTabWindow); + if (_windowList.Count == 0) { - _logger.Warn("first GUI thread window is disposed. Setting a new one."); - // may occur if a window is closed because of unhandled exception. - // Determine a new 'firstWindow'. If no window is left, start a new one. - RemoveWindow(_firstLogTabWindow); - if (_windowList.Count == 0) - { - _logger.Info("No windows left. New created window will be the new 'first' GUI window"); - LoadFiles(fileNames); - } - else - { - _firstLogTabWindow = _windowList[^1]; - NewWindow(fileNames); - } + _logger.Info(CultureInfo.InvariantCulture, "No windows left. New created window will be the new 'first' GUI window"); + LoadFiles(fileNames); } else { - _ = _firstLogTabWindow.Invoke(new NewWindowFx(NewWindowWorker), new object[] { fileNames }); + _firstLogTabWindow = _windowList[^1]; + NewWindow(fileNames); } } + else + { + _ = _firstLogTabWindow.Invoke(new NewWindowFx(NewWindowWorker), [fileNames]); + } + } - public void NewWindowOrLockedWindow(string[] fileNames) + public void NewWindowOrLockedWindow(string[] fileNames) + { + foreach (var logWin in _windowList) { - foreach (LogTabWindow logWin in _windowList) + if (AbstractLogTabWindow.StaticData.CurrentLockedMainWindow == logWin) { - if (LogTabWindow.StaticData.CurrentLockedMainWindow == logWin) - { - _ = logWin.Invoke(new MethodInvoker(logWin.SetForeground)); - logWin.LoadFiles(fileNames); - return; - } + _ = logWin.Invoke(new MethodInvoker(logWin.SetForeground)); + logWin.LoadFiles(fileNames); + return; } - // No locked window was found --> create a new one - NewWindow(fileNames); } + // No locked window was found --> create a new one + NewWindow(fileNames); + } - public void NewWindowWorker(string[] fileNames) - { - _logger.Info("Creating new LogTabWindow"); - LogTabWindow logWin = new(fileNames.Length > 0 ? fileNames : null, _logWindowIndex++, true) - { - LogExpertProxy = this - }; - AddWindow(logWin); - logWin.Show(); - logWin.Activate(); - } + public void NewWindowWorker(string[] fileNames) + { + _logger.Info(CultureInfo.InvariantCulture, "Creating new LogTabWindow"); + IConfigManager configManager = ConfigManager.Instance; + ILogTabWindow logWin = AbstractLogTabWindow.Create(fileNames.Length > 0 ? fileNames : null, _logWindowIndex++, true, configManager); + logWin.LogExpertProxy = this; + AddWindow(logWin); + logWin.Show(); + logWin.Activate(); + } - public void WindowClosed(LogTabWindow logWin) + public void WindowClosed(ILogTabWindow logWin) + { + RemoveWindow(logWin); + if (_windowList.Count == 0) { - RemoveWindow(logWin); - if (_windowList.Count == 0) - { - _logger.Info("Last LogTabWindow was closed"); - PluginRegistry.Instance.CleanupPlugins(); - OnLastWindowClosed(); - } - else - { - if (_firstLogTabWindow == logWin) - { - // valid firstLogTabWindow is needed for the Invoke()-Calls in NewWindow() - _firstLogTabWindow = _windowList[^1]; - } - } + _logger.Info(CultureInfo.InvariantCulture, "Last LogTabWindow was closed"); + PluginRegistry.PluginRegistry.Instance.CleanupPlugins(); + OnLastWindowClosed(); } - - public int GetLogWindowCount() + else { - return _windowList.Count; + if (_firstLogTabWindow == logWin) + { + // valid firstLogTabWindow is needed for the Invoke()-Calls in NewWindow() + _firstLogTabWindow = _windowList[^1]; + } } + } - //public override object InitializeLifetimeService() - //{ - // return null; - //} + public int GetLogWindowCount() + { + return _windowList.Count; + } - #endregion + //public override object InitializeLifetimeService() + //{ + // return null; + //} - #region Private Methods + #endregion - private void AddWindow(LogTabWindow window) - { - _logger.Info("Adding window to list"); - _windowList.Add(window); - } + #region Private Methods - private void RemoveWindow(LogTabWindow window) - { - _logger.Info("Removing window from list"); - _ = _windowList.Remove(window); - } + private void AddWindow(ILogTabWindow window) + { + _logger.Info(CultureInfo.InvariantCulture, "Adding window to list"); + _windowList.Add(window); + } - #endregion + private void RemoveWindow(ILogTabWindow window) + { + _logger.Info(CultureInfo.InvariantCulture, "Removing window from list"); + _ = _windowList.Remove(window); + } - protected void OnLastWindowClosed() - { - LastWindowClosed?.Invoke(this, new EventArgs()); - } + #endregion - private delegate void NewWindowFx(string[] fileNames); + protected void OnLastWindowClosed() + { + LastWindowClosed?.Invoke(this, new EventArgs()); } + + private delegate void NewWindowFx(string[] fileNames); } \ No newline at end of file diff --git a/src/LogExpert/Classes/ObjectClone.cs b/src/LogExpert/Classes/ObjectClone.cs deleted file mode 100644 index 70176ea4..00000000 --- a/src/LogExpert/Classes/ObjectClone.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.IO; -using System.Text.Json; - -namespace LogExpert.Classes -{ - public static class ObjectClone - { - #region Public methods - - public static T Clone(T RealObject) - { - using MemoryStream objectStream = new (); - - JsonSerializer.Serialize(objectStream, RealObject); - objectStream.Seek(0, SeekOrigin.Begin); - return JsonSerializer.Deserialize(objectStream); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/PaintHelper.cs b/src/LogExpert/Classes/PaintHelper.cs deleted file mode 100644 index 043f921a..00000000 --- a/src/LogExpert/Classes/PaintHelper.cs +++ /dev/null @@ -1,485 +0,0 @@ -using LogExpert.Classes.Highlight; -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using LogExpert.Interface; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Classes -{ - internal class PaintHelper - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - //TODO Make configurable - private Color _bookmarkColor = Color.FromArgb(165, 200, 225); - - #endregion - - #region Properties - - private static Preferences Preferences => ConfigManager.Settings.Preferences; - - #endregion - - #region Public methods - - public static void CellPainting(ILogPaintContext logPaintCtx, DataGridView gridView, int rowIndex, - DataGridViewCellPaintingEventArgs e) - { - if (rowIndex < 0 || e.ColumnIndex < 0) - { - e.Handled = false; - return; - } - ILogLine line = logPaintCtx.GetLogLine(rowIndex); - if (line != null) - { - HilightEntry entry = logPaintCtx.FindHighlightEntry(line, true); - e.Graphics.SetClip(e.CellBounds); - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) - { - Color backColor = e.CellStyle.SelectionBackColor; - Brush brush; - if (gridView.Focused) - { - brush = new SolidBrush(e.CellStyle.SelectionBackColor); - } - else - { - Color color = Color.FromArgb(255, 170, 170, 170); - brush = new SolidBrush(color); - } - e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); - } - else - { - Color bgColor = LogExpert.Config.ColorMode.DockBackgroundColor; - if (!DebugOptions.disableWordHighlight) - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - else - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - e.CellStyle.BackColor = bgColor; - e.PaintBackground(e.ClipBounds, false); - } - - if (DebugOptions.disableWordHighlight) - { - e.PaintContent(e.CellBounds); - } - else - { - PaintCell(logPaintCtx, e, gridView, false, entry); - } - - if (e.ColumnIndex == 0) - { - Entities.Bookmark bookmark = logPaintCtx.GetBookmarkForLine(rowIndex); - if (bookmark != null) - { - 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(logPaintCtx.BookmarkColor); - e.Graphics.FillRectangle(brush, r); - brush.Dispose(); - if (bookmark.Text.Length > 0) - { - StringFormat format = new(); - format.LineAlignment = StringAlignment.Center; - format.Alignment = StringAlignment.Center; - Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - Font font = logPaintCtx.MonospacedFont; - e.Graphics.DrawString("i", font, brush2, new RectangleF(r.Left, r.Top, r.Width, r.Height), - format); - brush2.Dispose(); - } - } - } - - e.Paint(e.CellBounds, DataGridViewPaintParts.Border); - e.Handled = true; - } - } - - - public static DataGridViewTextBoxColumn CreateMarkerColumn() - { - DataGridViewTextBoxColumn markerColumn = new(); - markerColumn.HeaderText = ""; - markerColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - markerColumn.Resizable = DataGridViewTriState.False; - markerColumn.DividerWidth = 1; - markerColumn.ReadOnly = true; - markerColumn.SortMode = DataGridViewColumnSortMode.NotSortable; - - return markerColumn; - } - - public static DataGridViewTextBoxColumn CreateLineNumberColumn() - { - DataGridViewTextBoxColumn lineNumberColumn = new(); - lineNumberColumn.HeaderText = "Line"; - lineNumberColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - lineNumberColumn.Resizable = DataGridViewTriState.NotSet; - lineNumberColumn.DividerWidth = 1; - lineNumberColumn.ReadOnly = true; - lineNumberColumn.SortMode = DataGridViewColumnSortMode.NotSortable; - - return lineNumberColumn; - } - - public static DataGridViewColumn CreateTitleColumn(string colName) - { - DataGridViewColumn titleColumn = new LogTextColumn(); - titleColumn.HeaderText = colName; - titleColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.NotSet; - titleColumn.Resizable = DataGridViewTriState.NotSet; - titleColumn.DividerWidth = 1; - titleColumn.SortMode = DataGridViewColumnSortMode.NotSortable; - - return titleColumn; - } - - public static void SetColumnizer(ILogLineColumnizer columnizer, DataGridView gridView) - { - int rowCount = gridView.RowCount; - int currLine = gridView.CurrentCellAddress.Y; - int currFirstLine = gridView.FirstDisplayedScrollingRowIndex; - - try - { - gridView.Columns.Clear(); - } - catch (ArgumentOutOfRangeException ae) - { - // Occures sometimes on empty gridViews (no lines) if bookmark window was closed and re-opened in floating mode. - // Don't know why. - _logger.Error(ae); - } - - gridView.Columns.Add(CreateMarkerColumn()); - - gridView.Columns.Add(CreateLineNumberColumn()); - - foreach (string colName in columnizer.GetColumnNames()) - { - gridView.Columns.Add(CreateTitleColumn(colName)); - } - - gridView.RowCount = rowCount; - if (currLine != -1) - { - gridView.CurrentCell = gridView.Rows[currLine].Cells[0]; - } - if (currFirstLine != -1) - { - gridView.FirstDisplayedScrollingRowIndex = currFirstLine; - } - //gridView.Refresh(); - //AutoResizeColumns(gridView); - } - - public static void AutoResizeColumns(DataGridView 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: "); - } - } - - public static void ApplyDataGridViewPrefs(DataGridView dataGridView, Preferences prefs) - { - if (dataGridView.Columns.Count > 1) - { - if (prefs.setLastColumnWidth) - { - dataGridView.Columns[dataGridView.Columns.Count - 1].MinimumWidth = prefs.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.Count - 1].MinimumWidth = 5; // default - } - } - if (dataGridView.RowCount > 0) - { - dataGridView.UpdateRowHeightInfo(0, true); - } - dataGridView.Invalidate(); - dataGridView.Refresh(); - AutoResizeColumns(dataGridView); - } - - public static Rectangle BorderWidths(DataGridViewAdvancedBorderStyle advancedBorderStyle) - { - Rectangle rect = new(); - - rect.X = advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; - if (advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.OutsetDouble || - advancedBorderStyle.Left == DataGridViewAdvancedCellBorderStyle.InsetDouble) - { - rect.X++; - } - - rect.Y = advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; - if (advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.OutsetDouble || - advancedBorderStyle.Top == DataGridViewAdvancedCellBorderStyle.InsetDouble) - { - rect.Y++; - } - - rect.Width = advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; - if (advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.OutsetDouble || - advancedBorderStyle.Right == DataGridViewAdvancedCellBorderStyle.InsetDouble) - { - rect.Width++; - } - - rect.Height = advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.None ? 0 : 1; - if (advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.OutsetDouble || - advancedBorderStyle.Bottom == DataGridViewAdvancedCellBorderStyle.InsetDouble) - { - rect.Height++; - } - - //rect.Width += this.owningColumn.DividerWidth; - //rect.Height += this.owningRow.DividerHeight; - - return rect; - } - - #endregion - - #region Private Methods - - private static void PaintCell(ILogPaintContext logPaintCtx, DataGridViewCellPaintingEventArgs e, DataGridView gridView, bool noBackgroundFill, HilightEntry groundEntry) - { - PaintHighlightedCell(logPaintCtx, e, gridView, noBackgroundFill, groundEntry); - } - - private static void PaintHighlightedCell(ILogPaintContext logPaintCtx, DataGridViewCellPaintingEventArgs e, DataGridView gridView, bool noBackgroundFill, HilightEntry groundEntry) - { - object value = e.Value ?? string.Empty; - - IList matchList = logPaintCtx.FindHighlightMatches(value as ILogLine); - // too many entries per line seem to cause problems with the GDI - while (matchList.Count > 50) - { - matchList.RemoveAt(50); - } - - if (value is Column column) - { - if (string.IsNullOrEmpty(column.FullValue) == false) - { - HilightMatchEntry hme = new(); - hme.StartPos = 0; - hme.Length = column.FullValue.Length; - - var he = new HilightEntry - { - SearchText = column.FullValue, - ForegroundColor = groundEntry?.ForegroundColor ?? ColorMode.ForeColor, - BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, - IsRegEx = false, - IsCaseSensitive = false, - IsLedSwitch = false, - IsStopTail = false, - IsSetBookmark = false, - IsActionEntry = false, - IsWordMatch = false - }; - - hme.HilightEntry = he; - - matchList = MergeHighlightMatchEntries(matchList, hme); - } - } - - int 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; - 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; - } - - - TextFormatFlags 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); - - Point wordPos = valBounds.Location; - Size proposedSize = new(valBounds.Width, valBounds.Height); - - Rectangle r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); - e.Graphics.SetClip(e.CellBounds); - - foreach (HilightMatchEntry matchEntry in matchList) - { - Font font = matchEntry != null && matchEntry.HilightEntry.IsBold - ? logPaintCtx.BoldFont - : logPaintCtx.NormalFont; - - Brush bgBrush = matchEntry.HilightEntry.BackgroundColor != Color.Empty - ? new SolidBrush(matchEntry.HilightEntry.BackgroundColor) - : null; - - string matchWord = string.Empty; - if (value is Column again) - { - if (string.IsNullOrEmpty(again.FullValue) == false) - { - matchWord = again.FullValue.Substring(matchEntry.StartPos, matchEntry.Length); - } - } - - Size wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); - wordSize.Height = e.CellBounds.Height; - Rectangle wordRect = new(wordPos, wordSize); - - Color foreColor = matchEntry.HilightEntry.ForegroundColor; - if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) - { - if (!noBackgroundFill && bgBrush != null && !matchEntry.HilightEntry.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); - 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 HilightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. - private static IList MergeHighlightMatchEntries(IList matchList, HilightMatchEntry groundEntry) - { - // Fill an area with lenth of whole text with a default hilight entry - HilightEntry[] entryArray = new HilightEntry[groundEntry.Length]; - for (int i = 0; i < entryArray.Length; ++i) - { - entryArray[i] = groundEntry.HilightEntry; - } - - // "overpaint" with all matching word match enries - // Non-word-mode matches will not overpaint because they use the groundEntry - foreach (HilightMatchEntry me in matchList) - { - int endPos = me.StartPos + me.Length; - for (int i = me.StartPos; i < endPos; ++i) - { - if (me.HilightEntry.IsWordMatch) - { - entryArray[i] = me.HilightEntry; - } - //else - //{ - // //entryArray[i].ForegroundColor = me.HilightEntry.ForegroundColor; - //} - } - } - - // collect areas with same hilight entry and build new highlight match entries for it - IList mergedList = new List(); - if (entryArray.Length > 0) - { - HilightEntry currentEntry = entryArray[0]; - int lastStartPos = 0; - int pos = 0; - for (; pos < entryArray.Length; ++pos) - { - if (entryArray[pos] != currentEntry) - { - HilightMatchEntry me = new(); - me.StartPos = lastStartPos; - me.Length = pos - lastStartPos; - me.HilightEntry = currentEntry; - mergedList.Add(me); - currentEntry = entryArray[pos]; - lastStartPos = pos; - } - } - HilightMatchEntry me2 = new(); - me2.StartPos = lastStartPos; - me2.Length = pos - lastStartPos; - me2.HilightEntry = currentEntry; - mergedList.Add(me2); - } - return mergedList; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/ParamParser.cs b/src/LogExpert/Classes/ParamParser.cs deleted file mode 100644 index 9d40665a..00000000 --- a/src/LogExpert/Classes/ParamParser.cs +++ /dev/null @@ -1,106 +0,0 @@ -using System.IO; -using System.Text; -using System.Text.RegularExpressions; - -namespace LogExpert.Classes -{ - internal class ParamParser - { - #region Fields - - private readonly string argLine; - - #endregion - - #region cTor - - public ParamParser(string argTemplate) - { - this.argLine = argTemplate; - } - - #endregion - - #region Public methods - - public string ReplaceParams(ILogLine logLine, int lineNum, string fileName) - { - FileInfo fileInfo = new(fileName); - StringBuilder builder = new(this.argLine); - builder.Replace("%L", "" + lineNum); - builder.Replace("%P", - fileInfo.DirectoryName.Contains(" ") ? "\"" + fileInfo.DirectoryName + "\"" : fileInfo.DirectoryName); - builder.Replace("%N", fileInfo.Name.Contains(" ") ? "\"" + fileInfo.Name + "\"" : fileInfo.Name); - builder.Replace("%F", - fileInfo.FullName.Contains(" ") ? "\"" + fileInfo.FullName + "\"" : fileInfo.FullName); - builder.Replace("%E", - fileInfo.Extension.Contains(" ") ? "\"" + fileInfo.Extension + "\"" : fileInfo.Extension); - string stripped = StripExtension(fileInfo.Name); - builder.Replace("%M", stripped.Contains(" ") ? "\"" + stripped + "\"" : stripped); - int sPos = 0; - string reg; - string replace; - do - { - reg = GetNextGroup(builder, ref sPos); - replace = GetNextGroup(builder, ref sPos); - if (reg != null && replace != null) - { - string result = Regex.Replace(logLine.FullLine, reg, replace); - builder.Insert(sPos, result); - } - } while (replace != null); - return builder.ToString(); - } - - public static string StripExtension(string fileName) - { - int i = fileName.LastIndexOf('.'); - if (i < 0) - { - i = fileName.Length - 1; - } - return fileName.Substring(0, i); - } - - #endregion - - #region Private Methods - - private string GetNextGroup(StringBuilder builder, ref int sPos) - { - int count = 0; - int ePos; - while (sPos < builder.Length) - { - if (builder[sPos] == '{') - { - ePos = sPos + 1; - count = 1; - while (ePos < builder.Length) - { - if (builder[ePos] == '{') - { - count++; - } - if (builder[ePos] == '}') - { - count--; - } - if (count == 0) - { - string reg = builder.ToString(sPos + 1, ePos - sPos - 1); - builder.Remove(sPos, ePos - sPos + 1); - return reg; - } - ePos++; - } - } - sPos++; - } - return null; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/PatternBlock.cs b/src/LogExpert/Classes/PatternBlock.cs deleted file mode 100644 index e37ccca2..00000000 --- a/src/LogExpert/Classes/PatternBlock.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Collections.Generic; - -namespace LogExpert.Classes -{ - public class QualityInfo - { - #region Fields - - public int quality; - - #endregion - } - - public class PatternBlock - { - #region Fields - - public int blockId; - - public int endLine; - - // key: line num - public Dictionary qualityInfoList = []; - - public SortedDictionary srcLines = []; - public int startLine; - public int targetEnd; - public SortedDictionary targetLines = []; - public int targetStart; - public int weigth; - - #endregion - - #region Public methods - - public override string ToString() - { - return "srcStart=" + startLine + ", srcEnd=" + endLine + ", targetStart=" + targetStart + - ", targetEnd=" + targetEnd + ", weight=" + weigth; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Persister/FilterTabData.cs b/src/LogExpert/Classes/Persister/FilterTabData.cs deleted file mode 100644 index 63c571d5..00000000 --- a/src/LogExpert/Classes/Persister/FilterTabData.cs +++ /dev/null @@ -1,14 +0,0 @@ -using LogExpert.Classes.Filter; - -namespace LogExpert.Classes.Persister -{ - public class FilterTabData - { - #region Fields - - public FilterParams filterParams; - public PersistenceData persistenceData; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Persister/Persister.cs b/src/LogExpert/Classes/Persister/Persister.cs deleted file mode 100644 index 8d951c98..00000000 --- a/src/LogExpert/Classes/Persister/Persister.cs +++ /dev/null @@ -1,688 +0,0 @@ -using LogExpert.Classes.Filter; -using LogExpert.Config; -using LogExpert.Entities; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Text; -using System.Text.Json; -using System.Windows.Forms; -using System.Xml; - -namespace LogExpert.Classes.Persister -{ - public class PersistenceData - { - #region Fields - - public SortedList bookmarkList = []; - public int bookmarkListPosition = 300; - public bool bookmarkListVisible = false; - public string columnizerName; - public int currentLine = -1; - public Encoding encoding; - public string fileName = null; - public bool filterAdvanced = false; - public List filterParamsList = []; - public int filterPosition = 222; - public bool filterSaveListVisible = false; - public List filterTabDataList = []; - public bool filterVisible = false; - public int firstDisplayedLine = -1; - public bool followTail = true; - public string highlightGroupName; - public int lineCount; - - public bool multiFile = false; - public int multiFileMaxDays; - public List multiFileNames = []; - public string multiFilePattern; - public SortedList rowHeightList = []; - public string sessionFileName = null; - public bool showBookmarkCommentColumn; - public string tabName = null; - - public string settingsSaveLoadLocation; - - #endregion - } - - public class Persister - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - #endregion - - #region Public methods - - public static string SavePersistenceData(string logFileName, PersistenceData persistenceData, Preferences preferences) - { - string fileName; - - if (persistenceData.sessionFileName != null) - { - fileName = persistenceData.sessionFileName; - } - else - { - fileName = BuildPersisterFileName(logFileName, preferences); - } - if (preferences.saveLocation == SessionSaveLocation.SameDir) - { - // make to log file in .lxp file relative - string filePart = Path.GetFileName(persistenceData.fileName); - persistenceData.fileName = filePart; - } - - Save(fileName, persistenceData); - return fileName; - } - - public static string SavePersistenceDataWithFixedName(string persistenceFileName, - PersistenceData persistenceData) - { - Save(persistenceFileName, persistenceData); - return persistenceFileName; - } - - - public static PersistenceData LoadPersistenceData(string logFileName, Preferences preferences) - { - string fileName = BuildPersisterFileName(logFileName, preferences); - return Load(fileName); - } - - public static PersistenceData LoadPersistenceDataOptionsOnly(string logFileName, Preferences preferences) - { - string fileName = BuildPersisterFileName(logFileName, preferences); - return LoadOptionsOnly(fileName); - } - - public static PersistenceData LoadPersistenceDataOptionsOnlyFromFixedFile(string persistenceFile) - { - return LoadOptionsOnly(persistenceFile); - } - - public static PersistenceData LoadPersistenceDataFromFixedFile(string persistenceFile) - { - return Load(persistenceFile); - } - - - /// - /// Loads the persistence options out of the given persistence file name. - /// - /// - /// - public static PersistenceData LoadOptionsOnly(string fileName) - { - PersistenceData persistenceData = new(); - XmlDocument xmlDoc = new(); - try - { - xmlDoc.Load(fileName); - } - catch (IOException) - { - return null; - } - XmlNode fileNode = xmlDoc.SelectSingleNode("logexpert/file"); - if (fileNode != null) - { - XmlElement fileElement = fileNode as XmlElement; - ReadOptions(fileElement, persistenceData); - persistenceData.fileName = fileElement.GetAttribute("fileName"); - persistenceData.encoding = ReadEncoding(fileElement); - } - return persistenceData; - } - - #endregion - - #region Private Methods - - private static string BuildPersisterFileName(string logFileName, Preferences preferences) - { - string dir; - string file; - - switch (preferences.saveLocation) - { - case SessionSaveLocation.SameDir: - default: - { - FileInfo fileInfo = new(logFileName); - dir = fileInfo.DirectoryName; - file = fileInfo.DirectoryName + Path.DirectorySeparatorChar + fileInfo.Name + ".lxp"; - break; - } - case SessionSaveLocation.DocumentsDir: - { - dir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + - Path.DirectorySeparatorChar + - "LogExpert"; - file = dir + Path.DirectorySeparatorChar + BuildSessionFileNameFromPath(logFileName); - break; - } - case SessionSaveLocation.OwnDir: - { - dir = preferences.sessionSaveDirectory; - file = dir + Path.DirectorySeparatorChar + BuildSessionFileNameFromPath(logFileName); - break; - } - case SessionSaveLocation.ApplicationStartupDir: - { - dir = Application.StartupPath + Path.DirectorySeparatorChar + "sessionfiles"; - file = dir + Path.DirectorySeparatorChar + BuildSessionFileNameFromPath(logFileName); - break; - } - } - - if (string.IsNullOrWhiteSpace(dir) == false && Directory.Exists(dir) == false) - { - try - { - Directory.CreateDirectory(dir); - } - catch (Exception e) - { - MessageBox.Show(e.Message, "LogExpert"); - } - } - return file; - } - - private static string BuildSessionFileNameFromPath(string logFileName) - { - string result = logFileName; - result = result.Replace(Path.DirectorySeparatorChar, '_'); - result = result.Replace(Path.AltDirectorySeparatorChar, '_'); - result = result.Replace(Path.VolumeSeparatorChar, '_'); - result += ".lxp"; - return result; - } - - private static void Save(string fileName, PersistenceData persistenceData) - { - XmlDocument xmlDoc = new(); - XmlElement rootElement = xmlDoc.CreateElement("logexpert"); - xmlDoc.AppendChild(rootElement); - XmlElement fileElement = xmlDoc.CreateElement("file"); - rootElement.AppendChild(fileElement); - fileElement.SetAttribute("fileName", persistenceData.fileName); - fileElement.SetAttribute("lineCount", "" + persistenceData.lineCount); - WriteBookmarks(xmlDoc, fileElement, persistenceData.bookmarkList); - WriteRowHeightList(xmlDoc, fileElement, persistenceData.rowHeightList); - WriteOptions(xmlDoc, fileElement, persistenceData); - WriteFilter(xmlDoc, fileElement, persistenceData.filterParamsList); - WriteFilterTabs(xmlDoc, fileElement, persistenceData.filterTabDataList); - WriteEncoding(xmlDoc, fileElement, persistenceData.encoding); - if (xmlDoc.HasChildNodes) - { - xmlDoc.Save(fileName); - } - } - - private static void WriteEncoding(XmlDocument xmlDoc, XmlElement rootElement, Encoding encoding) - { - if (encoding != null) - { - XmlElement encodingElement = xmlDoc.CreateElement("encoding"); - rootElement.AppendChild(encodingElement); - encodingElement.SetAttribute("name", encoding.WebName); - } - } - - private static void WriteFilterTabs(XmlDocument xmlDoc, XmlElement rootElement, List dataList) - { - if (dataList.Count > 0) - { - XmlElement filterTabsElement = xmlDoc.CreateElement("filterTabs"); - rootElement.AppendChild(filterTabsElement); - foreach (FilterTabData data in dataList) - { - PersistenceData persistenceData = data.persistenceData; - XmlElement filterTabElement = xmlDoc.CreateElement("filterTab"); - filterTabsElement.AppendChild(filterTabElement); - WriteBookmarks(xmlDoc, filterTabElement, persistenceData.bookmarkList); - WriteRowHeightList(xmlDoc, filterTabElement, persistenceData.rowHeightList); - WriteOptions(xmlDoc, filterTabElement, persistenceData); - WriteFilter(xmlDoc, filterTabElement, persistenceData.filterParamsList); - WriteFilterTabs(xmlDoc, filterTabElement, persistenceData.filterTabDataList); - XmlElement filterElement = xmlDoc.CreateElement("tabFilter"); - filterTabElement.AppendChild(filterElement); - List filterList = [data.filterParams]; - WriteFilter(xmlDoc, filterElement, filterList); - } - } - } - - private static List ReadFilterTabs(XmlElement startNode) - { - List dataList = []; - XmlNode filterTabsNode = startNode.SelectSingleNode("filterTabs"); - if (filterTabsNode != null) - { - XmlNodeList filterTabNodeList = filterTabsNode.ChildNodes; // all "filterTab" nodes - foreach (XmlNode node in filterTabNodeList) - { - PersistenceData persistenceData = ReadPersistenceDataFromNode(node); - XmlNode filterNode = node.SelectSingleNode("tabFilter"); - if (filterNode != null) - { - List filterList = ReadFilter(filterNode as XmlElement); - FilterTabData data = new(); - data.persistenceData = persistenceData; - data.filterParams = filterList[0]; // there's only 1 - dataList.Add(data); - } - } - } - return dataList; - } - - - private static void WriteFilter(XmlDocument xmlDoc, XmlElement rootElement, List filterList) - { - XmlElement filtersElement = xmlDoc.CreateElement("filters"); - rootElement.AppendChild(filtersElement); - foreach (FilterParams filterParams in filterList) - { - XmlElement filterElement = xmlDoc.CreateElement("filter"); - XmlElement paramsElement = xmlDoc.CreateElement("params"); - - MemoryStream stream = new(capacity: 200); - JsonSerializer.Serialize(stream, filterParams); - string base64Data = Convert.ToBase64String(stream.ToArray()); - paramsElement.InnerText = base64Data; - filterElement.AppendChild(paramsElement); - filtersElement.AppendChild(filterElement); - } - } - - - private static List ReadFilter(XmlElement startNode) - { - List filterList = []; - XmlNode filtersNode = startNode.SelectSingleNode("filters"); - if (filtersNode != null) - { - XmlNodeList filterNodeList = filtersNode.ChildNodes; // all "filter" nodes - foreach (XmlNode node in filterNodeList) - { - foreach (XmlNode subNode in node.ChildNodes) - { - if (subNode.Name.Equals("params")) - { - string base64Text = subNode.InnerText; - byte[] data = Convert.FromBase64String(base64Text); - MemoryStream stream = new(data); - FilterParams filterParams = JsonSerializer.Deserialize(stream); - filterParams.Init(); - filterList.Add(filterParams); - } - } - } - } - return filterList; - } - - - private static void WriteBookmarks(XmlDocument xmlDoc, XmlElement rootElement, - SortedList bookmarkList) - { - XmlElement bookmarksElement = xmlDoc.CreateElement("bookmarks"); - rootElement.AppendChild(bookmarksElement); - foreach (Entities.Bookmark bookmark in bookmarkList.Values) - { - XmlElement bookmarkElement = xmlDoc.CreateElement("bookmark"); - bookmarkElement.SetAttribute("line", "" + bookmark.LineNum); - XmlElement textElement = xmlDoc.CreateElement("text"); - textElement.InnerText = bookmark.Text; - XmlElement posXElement = xmlDoc.CreateElement("posX"); - XmlElement posYElement = xmlDoc.CreateElement("posY"); - posXElement.InnerText = "" + bookmark.OverlayOffset.Width; - posYElement.InnerText = "" + bookmark.OverlayOffset.Height; - bookmarkElement.AppendChild(textElement); - bookmarkElement.AppendChild(posXElement); - bookmarkElement.AppendChild(posYElement); - bookmarksElement.AppendChild(bookmarkElement); - } - } - - - private static PersistenceData Load(string fileName) - { - XmlDocument xmlDoc = new(); - xmlDoc.Load(fileName); - XmlNode fileNode = xmlDoc.SelectSingleNode("logexpert/file"); - PersistenceData persistenceData = new(); - if (fileNode != null) - { - persistenceData = ReadPersistenceDataFromNode(fileNode); - } - return persistenceData; - } - - private static PersistenceData ReadPersistenceDataFromNode(XmlNode node) - { - PersistenceData persistenceData = new(); - XmlElement fileElement = node as XmlElement; - persistenceData.bookmarkList = ReadBookmarks(fileElement); - persistenceData.rowHeightList = ReadRowHeightList(fileElement); - ReadOptions(fileElement, persistenceData); - persistenceData.fileName = fileElement.GetAttribute("fileName"); - string sLineCount = fileElement.GetAttribute("lineCount"); - if (sLineCount != null && sLineCount.Length > 0) - { - persistenceData.lineCount = int.Parse(sLineCount); - } - persistenceData.filterParamsList = ReadFilter(fileElement); - persistenceData.filterTabDataList = ReadFilterTabs(fileElement); - persistenceData.encoding = ReadEncoding(fileElement); - return persistenceData; - } - - - private static Encoding ReadEncoding(XmlElement fileElement) - { - XmlNode encodingNode = fileElement.SelectSingleNode("encoding"); - if (encodingNode != null) - { - XmlAttribute encAttr = encodingNode.Attributes["name"]; - try - { - return encAttr == null ? null : Encoding.GetEncoding(encAttr.Value); - } - catch (ArgumentException e) - { - _logger.Error(e); - return Encoding.Default; - } - catch (NotSupportedException e) - { - _logger.Error(e); - return Encoding.Default; - } - } - return null; - } - - - private static SortedList ReadBookmarks(XmlElement startNode) - { - SortedList bookmarkList = []; - XmlNode boomarksNode = startNode.SelectSingleNode("bookmarks"); - if (boomarksNode != null) - { - XmlNodeList bookmarkNodeList = boomarksNode.ChildNodes; // all "bookmark" nodes - foreach (XmlNode node in bookmarkNodeList) - { - string text = null; - string posX = null; - string posY = null; - string line = null; - foreach (XmlAttribute attr in node.Attributes) - { - if (attr.Name.Equals("line")) - { - line = attr.InnerText; - } - } - foreach (XmlNode subNode in node.ChildNodes) - { - if (subNode.Name.Equals("text")) - { - text = subNode.InnerText; - } - else if (subNode.Name.Equals("posX")) - { - posX = subNode.InnerText; - } - else if (subNode.Name.Equals("posY")) - { - posY = subNode.InnerText; - } - } - if (line == null || posX == null || posY == null) - { - _logger.Error("Invalid XML format for bookmark: {0}", node.InnerText); - continue; - } - int lineNum = int.Parse(line); - Entities.Bookmark bookmark = new(lineNum); - bookmark.OverlayOffset = new Size(int.Parse(posX), int.Parse(posY)); - if (text != null) - { - bookmark.Text = text; - } - bookmarkList.Add(lineNum, bookmark); - } - } - return bookmarkList; - } - - private static void WriteRowHeightList(XmlDocument xmlDoc, XmlElement rootElement, - SortedList rowHeightList) - { - XmlElement rowheightElement = xmlDoc.CreateElement("rowheights"); - rootElement.AppendChild(rowheightElement); - foreach (RowHeightEntry entry in rowHeightList.Values) - { - XmlElement entryElement = xmlDoc.CreateElement("rowheight"); - entryElement.SetAttribute("line", "" + entry.LineNum); - entryElement.SetAttribute("height", "" + entry.Height); - rowheightElement.AppendChild(entryElement); - } - } - - private static SortedList ReadRowHeightList(XmlElement startNode) - { - SortedList rowHeightList = []; - XmlNode rowHeightsNode = startNode.SelectSingleNode("rowheights"); - if (rowHeightsNode != null) - { - XmlNodeList rowHeightNodeList = rowHeightsNode.ChildNodes; // all "rowheight" nodes - foreach (XmlNode node in rowHeightNodeList) - { - string height = null; - string line = null; - foreach (XmlAttribute attr in node.Attributes) - { - if (attr.Name.Equals("line")) - { - line = attr.InnerText; - } - else if (attr.Name.Equals("height")) - { - height = attr.InnerText; - } - } - int lineNum = int.Parse(line); - int heightValue = int.Parse(height); - rowHeightList.Add(lineNum, new RowHeightEntry(lineNum, heightValue)); - } - } - return rowHeightList; - } - - - private static void WriteOptions(XmlDocument xmlDoc, XmlElement rootElement, PersistenceData persistenceData) - { - XmlElement optionsElement = xmlDoc.CreateElement("options"); - rootElement.AppendChild(optionsElement); - - XmlElement element = xmlDoc.CreateElement("multifile"); - element.SetAttribute("enabled", persistenceData.multiFile ? "1" : "0"); - element.SetAttribute("pattern", persistenceData.multiFilePattern); - element.SetAttribute("maxDays", "" + persistenceData.multiFileMaxDays); - foreach (string fileName in persistenceData.multiFileNames) - { - XmlElement entryElement = xmlDoc.CreateElement("fileEntry"); - entryElement.SetAttribute("fileName", "" + fileName); - element.AppendChild(entryElement); - } - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("currentline"); - element.SetAttribute("line", "" + persistenceData.currentLine); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("firstDisplayedLine"); - element.SetAttribute("line", "" + persistenceData.firstDisplayedLine); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("filter"); - element.SetAttribute("visible", persistenceData.filterVisible ? "1" : "0"); - element.SetAttribute("advanced", persistenceData.filterAdvanced ? "1" : "0"); - element.SetAttribute("position", "" + persistenceData.filterPosition); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("bookmarklist"); - element.SetAttribute("visible", persistenceData.bookmarkListVisible ? "1" : "0"); - element.SetAttribute("position", "" + persistenceData.bookmarkListPosition); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("followTail"); - element.SetAttribute("enabled", persistenceData.followTail ? "1" : "0"); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("tab"); - element.SetAttribute("name", persistenceData.tabName); - rootElement.AppendChild(element); - - element = xmlDoc.CreateElement("columnizer"); - element.SetAttribute("name", persistenceData.columnizerName); - rootElement.AppendChild(element); - - element = xmlDoc.CreateElement("highlightGroup"); - element.SetAttribute("name", persistenceData.highlightGroupName); - rootElement.AppendChild(element); - - element = xmlDoc.CreateElement("bookmarkCommentColumn"); - element.SetAttribute("visible", persistenceData.showBookmarkCommentColumn ? "1" : "0"); - optionsElement.AppendChild(element); - - element = xmlDoc.CreateElement("filterSaveList"); - element.SetAttribute("visible", persistenceData.filterSaveListVisible ? "1" : "0"); - optionsElement.AppendChild(element); - } - - - private static void ReadOptions(XmlElement startNode, PersistenceData persistenceData) - { - XmlNode optionsNode = startNode.SelectSingleNode("options"); - string value = GetOptionsAttribute(optionsNode, "multifile", "enabled"); - persistenceData.multiFile = value != null && value.Equals("1"); - persistenceData.multiFilePattern = GetOptionsAttribute(optionsNode, "multifile", "pattern"); - value = GetOptionsAttribute(optionsNode, "multifile", "maxDays"); - try - { - persistenceData.multiFileMaxDays = value != null ? short.Parse(value) : 0; - } - catch (Exception) - { - persistenceData.multiFileMaxDays = 0; - } - - XmlNode multiFileNode = optionsNode.SelectSingleNode("multifile"); - if (multiFileNode != null) - { - XmlNodeList multiFileNodeList = multiFileNode.ChildNodes; // all "fileEntry" nodes - foreach (XmlNode node in multiFileNodeList) - { - string fileName = null; - foreach (XmlAttribute attr in node.Attributes) - { - if (attr.Name.Equals("fileName")) - { - fileName = attr.InnerText; - } - } - persistenceData.multiFileNames.Add(fileName); - } - } - - value = GetOptionsAttribute(optionsNode, "currentline", "line"); - if (value != null) - { - persistenceData.currentLine = int.Parse(value); - } - value = GetOptionsAttribute(optionsNode, "firstDisplayedLine", "line"); - if (value != null) - { - persistenceData.firstDisplayedLine = int.Parse(value); - } - - value = GetOptionsAttribute(optionsNode, "filter", "visible"); - persistenceData.filterVisible = value != null && value.Equals("1"); - value = GetOptionsAttribute(optionsNode, "filter", "advanced"); - persistenceData.filterAdvanced = value != null && value.Equals("1"); - value = GetOptionsAttribute(optionsNode, "filter", "position"); - if (value != null) - { - persistenceData.filterPosition = int.Parse(value); - } - - value = GetOptionsAttribute(optionsNode, "bookmarklist", "visible"); - persistenceData.bookmarkListVisible = value != null && value.Equals("1"); - value = GetOptionsAttribute(optionsNode, "bookmarklist", "position"); - if (value != null) - { - persistenceData.bookmarkListPosition = int.Parse(value); - } - - value = GetOptionsAttribute(optionsNode, "followTail", "enabled"); - persistenceData.followTail = value != null && value.Equals("1"); - - value = GetOptionsAttribute(optionsNode, "bookmarkCommentColumn", "visible"); - persistenceData.showBookmarkCommentColumn = value != null && value.Equals("1"); - - value = GetOptionsAttribute(optionsNode, "filterSaveList", "visible"); - persistenceData.filterSaveListVisible = value != null && value.Equals("1"); - - XmlNode tabNode = startNode.SelectSingleNode("tab"); - if (tabNode != null) - { - persistenceData.tabName = (tabNode as XmlElement).GetAttribute("name"); - } - XmlNode columnizerNode = startNode.SelectSingleNode("columnizer"); - if (columnizerNode != null) - { - persistenceData.columnizerName = (columnizerNode as XmlElement).GetAttribute("name"); - } - XmlNode highlightGroupNode = startNode.SelectSingleNode("highlightGroup"); - if (highlightGroupNode != null) - { - persistenceData.highlightGroupName = (highlightGroupNode as XmlElement).GetAttribute("name"); - } - } - - - private static string GetOptionsAttribute(XmlNode optionsNode, string elementName, string attrName) - { - XmlNode node = optionsNode.SelectSingleNode(elementName); - if (node == null) - { - return null; - } - if (node is XmlElement) - { - string value = (node as XmlElement).GetAttribute(attrName); - return value; - } - else - { - return null; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Persister/ProjectData.cs b/src/LogExpert/Classes/Persister/ProjectData.cs deleted file mode 100644 index 18823c1e..00000000 --- a/src/LogExpert/Classes/Persister/ProjectData.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System.Collections.Generic; - -namespace LogExpert.Classes.Persister -{ - public class ProjectData - { - #region Fields - - public List memberList = []; - public string tabLayoutXml = null; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Persister/ProjectPersister.cs b/src/LogExpert/Classes/Persister/ProjectPersister.cs deleted file mode 100644 index 128b2ad1..00000000 --- a/src/LogExpert/Classes/Persister/ProjectPersister.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System.Collections.Generic; -using System.Xml; - -namespace LogExpert.Classes.Persister -{ - public static class ProjectPersister - { - #region Public methods - - public static ProjectData LoadProjectData(string projectFileName) - { - ProjectData projectData = new(); - XmlDocument xmlDoc = new(); - xmlDoc.Load(projectFileName); - XmlNodeList fileList = xmlDoc.GetElementsByTagName("member"); - foreach (XmlNode fileNode in fileList) - { - XmlElement fileElement = fileNode as XmlElement; - string fileName = fileElement.GetAttribute("fileName"); - projectData.memberList.Add(fileName); - } - XmlNodeList layoutElements = xmlDoc.GetElementsByTagName("layout"); - if (layoutElements.Count > 0) - { - projectData.tabLayoutXml = layoutElements[0].InnerXml; - } - return projectData; - } - - - public static void SaveProjectData(string projectFileName, ProjectData projectData) - { - XmlDocument xmlDoc = new(); - XmlElement rootElement = xmlDoc.CreateElement("logexpert"); - xmlDoc.AppendChild(rootElement); - XmlElement projectElement = xmlDoc.CreateElement("project"); - rootElement.AppendChild(projectElement); - XmlElement membersElement = xmlDoc.CreateElement("members"); - projectElement.AppendChild(membersElement); - SaveProjectMembers(xmlDoc, membersElement, projectData.memberList); - - if (projectData.tabLayoutXml != null) - { - XmlElement layoutElement = xmlDoc.CreateElement("layout"); - layoutElement.InnerXml = projectData.tabLayoutXml; - rootElement.AppendChild(layoutElement); - } - - xmlDoc.Save(projectFileName); - } - - #endregion - - #region Private Methods - - private static void SaveProjectMembers(XmlDocument xmlDoc, XmlNode membersNode, List memberList) - { - foreach (string fileName in memberList) - { - XmlElement memberElement = xmlDoc.CreateElement("member"); - membersNode.AppendChild(memberElement); - memberElement.SetAttribute("fileName", fileName); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/PluginRegistry.cs b/src/LogExpert/Classes/PluginRegistry.cs deleted file mode 100644 index 31cad60e..00000000 --- a/src/LogExpert/Classes/PluginRegistry.cs +++ /dev/null @@ -1,359 +0,0 @@ -using LogExpert.Classes.Columnizer; -using LogExpert.Config; -using LogExpert.Entities; -using LogExpert.Extensions; - -using NLog; - -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Windows.Forms; - -namespace LogExpert.Classes -{ - /// - /// Holds all registered plugins. - /// - /// - /// It all has started with Columnizers only. So the different types of plugins have no common super interface. I didn't change it - /// to keep existing plugin API stable. In a future version this may change. - /// - public class PluginRegistry - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - private static readonly Lazy _instance = new(() => new PluginRegistry()); - - private readonly IFileSystemCallback _fileSystemCallback = new FileSystemCallback(); - private readonly IList _pluginList = new List(); - private readonly IDictionary _registeredKeywordsDict = new Dictionary(); - - #endregion - - #region cTor - // Private constructor to prevent instantiation - private PluginRegistry() - { - LoadPlugins(); - } - - #endregion - - #region Properties - - public static PluginRegistry Instance => _instance.Value; - - public IList RegisteredColumnizers { get; private set; } - - public IList RegisteredContextMenuPlugins { get; } = new List(); - - public IList RegisteredKeywordActions { get; } = new List(); - - public IList RegisteredFileSystemPlugins { get; } = new List(); - - #endregion - - #region Public methods - #endregion - - #region Internals - - internal void LoadPlugins() - { - _logger.Info("Loading plugins..."); - - RegisteredColumnizers = - [ - //TODO: Remove these plugins and load them as any other plugin - new DefaultLogfileColumnizer(), - new TimestampColumnizer(), - new SquareBracketColumnizer(), - new ClfColumnizer(), - ]; - RegisteredFileSystemPlugins.Add(new LocalFileSystem()); - - string pluginDir = Path.Combine(Application.StartupPath, "plugins"); - //TODO: FIXME: This is a hack for the tests to pass. Need to find a better approach - if (!Directory.Exists(pluginDir)) - { - pluginDir = "."; - } - - AppDomain.CurrentDomain.AssemblyResolve += ColumnizerResolveEventHandler; - - string interfaceName = typeof(ILogLineColumnizer).FullName; - foreach (string dllName in Directory.EnumerateFiles(pluginDir, "*.dll")) - { - try - { - LoadPluginAssembly(dllName, interfaceName); - } - catch (Exception ex) when (ex is BadImageFormatException or FileLoadException) - { - // Can happen when a 32bit-only DLL is loaded on a 64bit system (or vice versa) - // or could be a not columnizer DLL (e.g. A DLL that is needed by a plugin). - _logger.Error(ex, dllName); - } - catch (ReflectionTypeLoadException ex) - { - // can happen when a dll dependency is missing - if (!ex.LoaderExceptions.IsEmpty()) - { - foreach (Exception loaderException in ex.LoaderExceptions) - { - _logger.Error(loaderException, "Plugin load failed with '{0}'", dllName); - } - } - _logger.Error(ex, "Loader exception during load of dll '{0}'", dllName); - throw; - } - catch (Exception ex) - { - _logger.Error(ex, $"General Exception for the file {dllName}, of type: {ex.GetType()}, with the message: {ex.Message}"); - throw; - } - } - - _logger.Info("Plugin loading complete."); - } - - private void LoadPluginAssembly(string dllName, string interfaceName) - { - Assembly assembly = Assembly.LoadFrom(dllName); - var types = assembly.GetTypes(); - - foreach (var type in types) - { - _logger.Info($"Type {type.FullName} in assembly {assembly.FullName} implements {interfaceName}"); - - if (type.GetInterfaces().Any(i => i.FullName == interfaceName)) - { - ConstructorInfo cti = type.GetConstructor(Type.EmptyTypes); - if (cti != null) - { - object instance = cti.Invoke([]); - RegisteredColumnizers.Add((ILogLineColumnizer)instance); - - if (instance is IColumnizerConfigurator configurator) - { - configurator.LoadConfig(ConfigManager.Settings.Preferences.PortableMode ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir); - } - - if (instance is ILogExpertPlugin plugin) - { - _pluginList.Add(plugin); - plugin.PluginLoaded(); - } - - _logger.Info("Added columnizer {0}", type.Name); - } - } - else - { - if (TryAsContextMenu(type)) - { - continue; - } - - if (TryAsKeywordAction(type)) - { - continue; - } - - if (TryAsFileSystem(type)) - { - continue; - } - } - } - } - - internal IKeywordAction FindKeywordActionPluginByName(string name) - { - _registeredKeywordsDict.TryGetValue(name, out IKeywordAction action); - return action; - } - - internal void CleanupPlugins() - { - foreach (ILogExpertPlugin plugin in _pluginList) - { - plugin.AppExiting(); - } - } - - internal IFileSystemPlugin FindFileSystemForUri(string uriString) - { - if (_logger.IsDebugEnabled) - { - _logger.Debug("Trying to find file system plugin for uri {0}", uriString); - } - - foreach (IFileSystemPlugin fs in RegisteredFileSystemPlugins) - { - if (_logger.IsDebugEnabled) - { - _logger.Debug("Checking {0}", fs.Text); - } - - if (fs.CanHandleUri(uriString)) - { - if (_logger.IsDebugEnabled) - { - _logger.Debug("Found match {0}", fs.Text); - } - - return fs; - } - } - - _logger.Error("No file system plugin found for uri {0}", uriString); - return null; - } - - #endregion - - #region Private Methods - //TODO: Can this be delted? - private bool TryAsContextMenu(Type type) - { - IContextMenuEntry me = TryInstantiate(type); - if (me != null) - { - RegisteredContextMenuPlugins.Add(me); - if (me is ILogExpertPluginConfigurator configurator) - { - configurator.LoadConfig(ConfigManager.ConfigDir); - } - - if (me is ILogExpertPlugin) - { - _pluginList.Add(me as ILogExpertPlugin); - (me as ILogExpertPlugin).PluginLoaded(); - } - - _logger.Info("Added context menu plugin {0}", type); - return true; - } - - return false; - } - - //TODO: Can this be delted? - private bool TryAsKeywordAction(Type type) - { - IKeywordAction ka = TryInstantiate(type); - if (ka != null) - { - RegisteredKeywordActions.Add(ka); - _registeredKeywordsDict.Add(ka.GetName(), ka); - if (ka is ILogExpertPluginConfigurator configurator) - { - configurator.LoadConfig(ConfigManager.ConfigDir); - } - - if (ka is ILogExpertPlugin) - { - _pluginList.Add(ka as ILogExpertPlugin); - (ka as ILogExpertPlugin).PluginLoaded(); - } - - _logger.Info("Added keyword plugin {0}", type); - return true; - } - - return false; - } - - //TODO: Can this be delted? - private bool TryAsFileSystem(Type type) - { - // file system plugins can have optional constructor with IFileSystemCallback argument - IFileSystemPlugin fs = TryInstantiate(type, _fileSystemCallback); - fs ??= TryInstantiate(type); - - if (fs != null) - { - RegisteredFileSystemPlugins.Add(fs); - if (fs is ILogExpertPluginConfigurator configurator) - { - configurator.LoadConfig(ConfigManager.ConfigDir); - } - - if (fs is ILogExpertPlugin) - { - _pluginList.Add(fs as ILogExpertPlugin); - (fs as ILogExpertPlugin).PluginLoaded(); - } - - _logger.Info("Added file system plugin {0}", type); - return true; - } - - return false; - } - - private static T TryInstantiate(Type loadedType) where T : class - { - Type t = typeof(T); - Type inter = loadedType.GetInterface(t.Name); - if (inter != null) - { - ConstructorInfo cti = loadedType.GetConstructor(Type.EmptyTypes); - if (cti != null) - { - object o = cti.Invoke([]); - return o as T; - } - } - - return default(T); - } - - private static T TryInstantiate(Type loadedType, IFileSystemCallback fsCallback) where T : class - { - Type t = typeof(T); - Type inter = loadedType.GetInterface(t.Name); - if (inter != null) - { - ConstructorInfo cti = loadedType.GetConstructor([typeof(IFileSystemCallback)]); - if (cti != null) - { - object o = cti.Invoke([fsCallback]); - return o as T; - } - } - - return default; - } - - #endregion - - #region Events handler - - private static Assembly ColumnizerResolveEventHandler(object sender, ResolveEventArgs args) - { - string fileName = new AssemblyName(args.Name).Name + ".dll"; - string mainDir = Path.Combine(Application.StartupPath, fileName); - string pluginDir = Path.Combine(Application.StartupPath, "plugins", fileName); - - if (File.Exists(mainDir)) - { - return Assembly.LoadFrom(mainDir); - } - - if (File.Exists(pluginDir)) - { - return Assembly.LoadFrom(pluginDir); - } - - return null; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/RangeFinder.cs b/src/LogExpert/Classes/RangeFinder.cs deleted file mode 100644 index bf9c456a..00000000 --- a/src/LogExpert/Classes/RangeFinder.cs +++ /dev/null @@ -1,105 +0,0 @@ -using LogExpert.Classes.Filter; -using LogExpert.Classes.ILogLineColumnizerCallback; -using LogExpert.Entities; -using NLog; - -namespace LogExpert.Classes -{ - /// - /// Delivers the range (from..to) that matches the current range filter settings starting from a given line. - /// - internal class RangeFinder - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private readonly ColumnizerCallback _callback; - private readonly FilterParams _filterParams; - - #endregion - - #region cTor - - public RangeFinder(FilterParams filterParams, ColumnizerCallback callback) - { - _filterParams = filterParams.CreateCopy2(); - _callback = callback; - } - - #endregion - - #region Public methods - - public Range FindRange(int startLine) - { - _logger.Info($"Starting range search for {_filterParams.searchText} ... {_filterParams.rangeSearchText}"); - if (_filterParams.rangeSearchText == null || _filterParams.rangeSearchText.Trim().Length == 0) - { - _logger.Info("Range search text not set. Cancelling range search."); - return null; - } - if (_filterParams.searchText == null || _filterParams.searchText.Trim().Length == 0) - { - _logger.Info("Search text not set. Cancelling range search."); - return null; - } - - _filterParams.isRangeSearch = false; - _filterParams.isInRange = false; - int lineCount = _callback.GetLineCount(); - int lineNum = startLine; - bool foundStartLine = false; - Range range = new(); - FilterParams tmpParam = _filterParams.CreateCopy2(); - tmpParam.searchText = _filterParams.rangeSearchText; - - // search backward for starting keyword - var line = _callback.GetLogLine(lineNum); - while (lineNum >= 0) - { - _callback.LineNum = lineNum; - if (Util.TestFilterCondition(_filterParams, line, _callback)) - { - foundStartLine = true; - break; - } - lineNum--; - line = _callback.GetLogLine(lineNum); - if (lineNum < 0 || Util.TestFilterCondition(tmpParam, line, _callback) - ) // do not crash on Ctrl+R when there is not start line found - { - // lower range bound found --> we are not in between a valid range - break; - } - } - if (!foundStartLine) - { - _logger.Info("Range start not found"); - return null; - } - range.StartLine = lineNum; - _filterParams.isRangeSearch = true; - _filterParams.isInRange = true; - lineNum++; - while (lineNum < lineCount) - { - line = _callback.GetLogLine(lineNum); - _callback.LineNum = lineNum; - if (!Util.TestFilterCondition(_filterParams, line, _callback)) - { - break; - } - lineNum++; - } - lineNum--; - range.EndLine = lineNum; - - _logger.Info($"Range search finished. Found {range.EndLine - range.StartLine} lines"); - - return range; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/SysoutPipe.cs b/src/LogExpert/Classes/SysoutPipe.cs deleted file mode 100644 index 990a766d..00000000 --- a/src/LogExpert/Classes/SysoutPipe.cs +++ /dev/null @@ -1,91 +0,0 @@ -using System.Diagnostics; -using System.IO; -using System.Text; -using System.Threading; -using NLog; - -namespace LogExpert.Classes -{ - internal class SysoutPipe - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private readonly StreamReader sysout; - private StreamWriter writer; - - #endregion - - #region cTor - - public SysoutPipe(StreamReader sysout) - { - this.sysout = sysout; - this.FileName = Path.GetTempFileName(); - _logger.Info("sysoutPipe created temp file: {0}", this.FileName); - FileStream fStream = new(this.FileName, FileMode.Append, FileAccess.Write, FileShare.Read); - this.writer = new StreamWriter(fStream, Encoding.Unicode); - Thread thread = new(new ThreadStart(this.ReaderThread)); - thread.IsBackground = true; - thread.Start(); - } - - #endregion - - #region Properties - - public string FileName { get; } - - #endregion - - #region Public methods - - public void ClosePipe() - { - this.writer.Close(); - this.writer = null; - } - - - public void DataReceivedEventHandler(object sender, DataReceivedEventArgs e) - { - this.writer.WriteLine(e.Data); - } - - public void ProcessExitedEventHandler(object sender, System.EventArgs e) - { - //ClosePipe(); - if (sender.GetType() == typeof(Process)) - { - ((Process) sender).Exited -= this.ProcessExitedEventHandler; - ((Process) sender).OutputDataReceived -= this.DataReceivedEventHandler; - } - } - - #endregion - - protected void ReaderThread() - { - char[] buff = new char[256]; - while (true) - { - try - { - int read = this.sysout.Read(buff, 0, 256); - if (read == 0) - { - break; - } - writer.Write(buff, 0, read); - } - catch (IOException e) - { - _logger.Error(e); - break; - } - } - ClosePipe(); - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/TimeSpreadCalculator.cs b/src/LogExpert/Classes/TimeSpreadCalculator.cs deleted file mode 100644 index 4fed6941..00000000 --- a/src/LogExpert/Classes/TimeSpreadCalculator.cs +++ /dev/null @@ -1,461 +0,0 @@ -using LogExpert.Classes.ILogLineColumnizerCallback; -using LogExpert.Controls.LogWindow; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace LogExpert.Classes -{ - internal class TimeSpreadCalculator - { - #region Fields - - private const int INACTIVITY_TIME = 2000; - - private const int MAX_CONTRAST = 1300; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private readonly EventWaitHandle _calcEvent = new ManualResetEvent(false); - private readonly ColumnizerCallback _callback; - - private readonly object _diffListLock = new(); - private readonly EventWaitHandle _lineCountEvent = new ManualResetEvent(false); - - private readonly LogWindow _logWindow; - - // for DoCalc_via_Time - private double _average; - - private int _contrast = 400; - private int _displayHeight = 0; - private bool _enabled; - private DateTime _endTimestamp; - private int _lineCount = 0; - private int _maxDiff; - private TimeSpan _maxSpan; - private bool _shouldStop; - private CancellationTokenSource cts = new(); - - private DateTime _startTimestamp; - - private bool _timeMode = true; - - // for DoCalc - private int _timePerLine; - - #endregion - - #region cTor - - public TimeSpreadCalculator(LogWindow logWindow) - { - _logWindow = logWindow; - _callback = new ColumnizerCallback(_logWindow); - - 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; - - #endregion - - #region Properties - - public bool Enabled - { - get => _enabled; - set - { - _enabled = value; - if (_enabled) - { - _calcEvent.Set(); - _lineCountEvent.Set(); - } - } - } - - public bool TimeMode - { - get => _timeMode; - set - { - _timeMode = value; - if (_enabled) - { - _calcEvent.Set(); - _lineCountEvent.Set(); - } - } - } - - public int Contrast - { - set - { - _contrast = value; - if (_contrast < 0) - { - _contrast = 0; - } - else if (_contrast > MAX_CONTRAST) - { - _contrast = MAX_CONTRAST; - } - - if (TimeMode) - { - CalcValuesViaTime(_maxDiff, _average); - } - else - { - CalcValuesViaLines(_timePerLine, _maxSpan); - } - OnCalcDone(EventArgs.Empty); - } - - get => _contrast; - } - - public List DiffList { get; set; } = []; - - #endregion - - #region Public methods - - public void Stop() - { - _shouldStop = true; - _lineCountEvent.Set(); - cts.Cancel(); - } - - public void SetLineCount(int count) - { - _lineCount = count; - if (Enabled) - { - _calcEvent.Set(); - _lineCountEvent.Set(); - } - } - - public void SetDisplayHeight(int height) - { - _displayHeight = height; - if (Enabled) - { - _calcEvent.Set(); - _lineCountEvent.Set(); - } - } - - #endregion - - #region Private Methods - - private void WorkerFx() - { - //Thread.CurrentThread.Name = "TimeSpreadCalculator Worker"; - //Thread.CurrentThread.Priority = ThreadPriority.BelowNormal; - - while (!_shouldStop) - { - // wait for wakeup - _lineCountEvent.WaitOne(); - - while (!_shouldStop) - { - // wait for unbusy moments - _logger.Debug("TimeSpreadCalculator: wait for unbusy moments"); - bool signaled = _calcEvent.WaitOne(INACTIVITY_TIME, false); - if (signaled == false) - { - _logger.Debug("TimeSpreadCalculator: unbusy. starting calc."); - if (TimeMode) - { - DoCalc_via_Time(); - } - else - { - DoCalc(); - } - break; - } - - _logger.Debug("TimeSpreadCalculator: signalled. no calc."); - _calcEvent.Reset(); - } - _lineCountEvent.Reset(); - } - } - - private void DoCalc() - { - OnStartCalc(EventArgs.Empty); - _logger.Debug("TimeSpreadCalculator.DoCalc() begin"); - if (_callback.GetLineCount() < 1) - { - OnCalcDone(EventArgs.Empty); - _logger.Debug("TimeSpreadCalculator.DoCalc() end because of line count < 1"); - return; - } - int lineNum = 0; - int lastLineNum = _callback.GetLineCount() - 1; - _startTimestamp = _logWindow.GetTimestampForLineForward(ref lineNum, false); - _endTimestamp = _logWindow.GetTimestampForLine(ref lastLineNum, false); - - int timePerLineSum = 0; - - if (_startTimestamp != DateTime.MinValue && _endTimestamp != DateTime.MinValue) - { - TimeSpan overallSpan = _endTimestamp - _startTimestamp; - int 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; - } - - _logger.Debug("TimeSpreadCalculator.DoCalc() collecting data for {0} lines with step size {1}", lastLineNum, step); - - List newDiffList = []; - List maxList = []; - lineNum++; - for (int i = lineNum; i < lastLineNum; i += step) - { - int currLineNum = i; - DateTime time = _logWindow.GetTimestampForLineForward(ref currLineNum, false); - if (time != DateTime.MinValue) - { - TimeSpan span = time - oldTime; - maxList.Add(span); - timePerLineSum += (int)(span.Ticks / TimeSpan.TicksPerMillisecond); - newDiffList.Add(new SpreadEntry(i, 0, time)); - oldTime = time; - _logger.Debug("TimeSpreadCalculator.DoCalc() time diff {0}", span); - } - } - 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); - OnCalcDone(EventArgs.Empty); - _logger.Debug("TimeSpreadCalculator.DoCalc() end"); - } - } - } - - //TODO Refactor this method - private void DoCalc_via_Time() - { - OnStartCalc(EventArgs.Empty); - _logger.Debug("TimeSpreadCalculator.DoCalc_via_Time() begin"); - if (_callback.GetLineCount() < 1) - { - OnCalcDone(EventArgs.Empty); - _logger.Debug("TimeSpreadCalculator.DoCalc() end because of line count < 1"); - return; - } - int lineNum = 0; - int lastLineNum = _callback.GetLineCount() - 1; - _startTimestamp = _logWindow.GetTimestampForLineForward(ref lineNum, false); - _endTimestamp = _logWindow.GetTimestampForLine(ref lastLineNum, false); - - if (_startTimestamp != DateTime.MinValue && _endTimestamp != DateTime.MinValue) - { - TimeSpan overallSpan = _endTimestamp - _startTimestamp; - long overallSpanMillis = overallSpan.Ticks / TimeSpan.TicksPerMillisecond; - //int timePerLine = (int)Math.Round((double)overallSpanMillis / (double)this.lineCount); - DateTime oldTime = _logWindow.GetTimestampForLineForward(ref lineNum, false); - long step; - if (overallSpanMillis > _displayHeight) - { - step = (long)Math.Round(overallSpanMillis / (double)_displayHeight); - } - else - { - step = 1; - } - - _logger.Debug("TimeSpreadCalculator.DoCalc_via_Time() time range is {0} ms", overallSpanMillis); - - lineNum = 0; - DateTime searchTimeStamp = _startTimestamp; - int oldLineNum = lineNum; - int loopCount = 0; - int lineDiffSum = 0; - int minDiff = int.MaxValue; - _maxDiff = 0; - List maxList = []; - List newDiffList = []; - while (searchTimeStamp.CompareTo(_endTimestamp) <= 0) - { - lineNum = _logWindow.FindTimestampLine_Internal(lineNum, lineNum, lastLineNum, searchTimeStamp, false); - if (lineNum < 0) - { - lineNum = -lineNum; - } - int lineDiff = lineNum - oldLineNum; - - _logger.Debug("TimeSpreadCalculator.DoCalc_via_Time() test time {0:HH:mm:ss.fff} line diff={1}", searchTimeStamp, lineDiff); - - if (lineDiff >= 0) - { - lineDiffSum += lineDiff; - newDiffList.Add(new SpreadEntry(lineNum, lineDiff, searchTimeStamp)); - - if (lineDiff < minDiff) - { - minDiff = lineDiff; - } - - if (lineDiff > _maxDiff) - { - _maxDiff = lineDiff; - } - maxList.Add(lineDiff); - loopCount++; - } - - searchTimeStamp = searchTimeStamp.AddMilliseconds(step); - oldLineNum = lineNum; - //lineNum++; - } - if (maxList.Count > 3) - { - maxList.Sort(); - _maxDiff = maxList[^3]; - } - _average = lineDiffSum / (double)loopCount; - //double average = maxList[maxList.Count / 2]; - _logger.Debug("Average diff={0} minDiff={1} maxDiff={2}", _average, minDiff, _maxDiff); - - lock (_diffListLock) - { - if (newDiffList.Count > 0) - { - newDiffList.RemoveAt(0); - } - - if (newDiffList.Count > 0) - { - newDiffList.RemoveAt(0); - } - - DiffList = newDiffList; - CalcValuesViaTime(_maxDiff, _average); - OnCalcDone(EventArgs.Empty); - _logger.Debug("TimeSpreadCalculator.DoCalc_via_Time() end"); - } - } - } - - private DateTime CalcValuesViaLines(int timePerLine, TimeSpan maxSpan) - { - DateTime oldTime = DateTime.MinValue; - if (DiffList.Count > 0) - { - oldTime = DiffList[0].Timestamp; - foreach (SpreadEntry entry in DiffList) - { - TimeSpan span = entry.Timestamp - oldTime; - double diffFromAverage = (int)(span.Ticks / TimeSpan.TicksPerMillisecond) - timePerLine; - - if (diffFromAverage < 0) - { - diffFromAverage = 0; - } - - int value = (int)(diffFromAverage / (timePerLine / TimeSpan.TicksPerMillisecond) * _contrast); - entry.Value = 255 - value; - oldTime = entry.Timestamp; - } - } - return oldTime; - } - - private void CalcValuesViaTime(int maxDiff, double average) - { - foreach (SpreadEntry entry in DiffList) - { - int lineDiff = entry.Diff; - double diffFromAverage = entry.Diff - average; - if (diffFromAverage < 0) - { - diffFromAverage = 0; - } - int value = (int)(diffFromAverage / maxDiff * _contrast); - entry.Value = 255 - value; - _logger.Debug("TimeSpreadCalculator.DoCalc() test time {0:HH:mm:ss.fff} line diff={1} value={2}", entry.Timestamp, lineDiff, value); - } - } - - private void OnCalcDone(EventArgs e) - { - CalcDone?.Invoke(this, e); - } - - private void OnStartCalc(EventArgs e) - { - StartCalc?.Invoke(this, e); - } - - #endregion - - public class SpreadEntry - { - #region Fields - - public int Diff { get; set; } - - public DateTime Timestamp { get; set; } - - public int LineNum { get; set; } - - public int Value { get; set; } - - #endregion - - #region cTor - - public SpreadEntry(int lineNum, int diff, DateTime timestamp) - { - LineNum = lineNum; - Diff = diff; - Timestamp = timestamp; - } - - #endregion - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/TimeSyncList.cs b/src/LogExpert/Classes/TimeSyncList.cs deleted file mode 100644 index 32ae2199..00000000 --- a/src/LogExpert/Classes/TimeSyncList.cs +++ /dev/null @@ -1,105 +0,0 @@ -using System; -using System.Collections.Generic; -using LogExpert.Controls.LogWindow; - -namespace LogExpert.Classes -{ - /// - /// Holds all windows which are in sync via timestamp - /// - internal class TimeSyncList - { - #region Fields - - private readonly IList logWindowList = new List(); - - #endregion - - #region Delegates - - public delegate void WindowRemovedEventHandler(object sender, EventArgs e); - - #endregion - - #region Events - - public event WindowRemovedEventHandler WindowRemoved; - - #endregion - - #region Properties - - public DateTime CurrentTimestamp { get; set; } - - public int Count - { - get { return this.logWindowList.Count; } - } - - #endregion - - #region Public methods - - public void AddWindow(LogWindow logWindow) - { - lock (this.logWindowList) - { - if (!this.logWindowList.Contains(logWindow)) - { - this.logWindowList.Add(logWindow); - } - } - } - - - public void RemoveWindow(LogWindow logWindow) - { - lock (this.logWindowList) - { - this.logWindowList.Remove(logWindow); - } - OnWindowRemoved(); - } - - - /// - /// Scrolls all LogWindows to the given timestamp - /// - /// - /// - public void NavigateToTimestamp(DateTime timestamp, LogWindow sender) - { - this.CurrentTimestamp = timestamp; - lock (this.logWindowList) - { - foreach (LogWindow logWindow in this.logWindowList) - { - if (sender != logWindow) - { - logWindow.ScrollToTimestamp(timestamp, false, false); - } - } - } - } - - - public bool Contains(LogWindow logWindow) - { - return this.logWindowList.Contains(logWindow); - } - - #endregion - - #region Private Methods - - private void OnWindowRemoved() - { - if (WindowRemoved != null) - { - WindowRemoved(this, new EventArgs()); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Util.cs b/src/LogExpert/Classes/Util.cs deleted file mode 100644 index 79d77d75..00000000 --- a/src/LogExpert/Classes/Util.cs +++ /dev/null @@ -1,612 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Drawing; -using System.Text.RegularExpressions; -using System.Windows.Forms; -using LogExpert.Classes.Filter; - -namespace LogExpert.Classes -{ - public class Util - { - #region Public methods - - public static string GetNameFromPath(string fileName) - { - int i = fileName.LastIndexOf('\\'); - if (i < 0) - { - i = fileName.LastIndexOf('/'); - } - if (i < 0) - { - i = -1; - } - return fileName.Substring(i + 1); - } - - public static string StripExtension(string fileName) - { - int i = fileName.LastIndexOf('.'); - if (i < 0) - { - i = fileName.Length - 1; - } - return fileName.Substring(0, i); - } - - public static string GetExtension(string fileName) - { - int i = fileName.LastIndexOf('.'); - if (i < 0 || i >= fileName.Length - 1) - { - return ""; - } - else - { - return fileName.Substring(i + 1); - } - } - - - public static string GetFileSizeAsText(long size) - { - if (size < 1024) - { - return "" + size + " bytes"; - } - else if (size < 1024 * 1024) - { - return "" + size / 1024 + " KB"; - } - else - { - return "" + string.Format("{0:0.00}", (double) size / 1048576.0) + " MB"; - } - } - - public static bool TestFilterCondition(FilterParams filterParams, ILogLine line, - LogExpert.ILogLineColumnizerCallback columnizerCallback) - { - if (filterParams.lastLine.Equals(line.FullLine)) - { - return filterParams.lastResult; - } - - bool match = TestFilterMatch(filterParams, line, columnizerCallback); - filterParams.lastLine = line.FullLine; - - if (filterParams.isRangeSearch) - { - if (!filterParams.isInRange) - { - if (match) - { - filterParams.isInRange = true; - } - } - else - { - if (!match) - { - match = true; - } - else - { - filterParams.isInRange = false; - } - } - } - if (filterParams.isInvert) - { - match = !match; - } - filterParams.lastResult = match; - return match; - } - - - public static int DamerauLevenshteinDistance(string src, string dest) - { - int[,] d = new int[src.Length + 1, dest.Length + 1]; - int i, j, cost; - char[] str1 = src.ToCharArray(); - char[] str2 = dest.ToCharArray(); - - for (i = 0; i <= str1.Length; i++) - { - d[i, 0] = i; - } - for (j = 0; j <= str2.Length; j++) - { - d[0, j] = j; - } - for (i = 1; i <= str1.Length; i++) - { - for (j = 1; j <= str2.Length; j++) - { - if (str1[i - 1] == str2[j - 1]) - { - cost = 0; - } - else - { - cost = 1; - } - - d[i, j] = - Math.Min(d[i - 1, j] + 1, // Deletion - Math.Min(d[i, j - 1] + 1, // Insertion - d[i - 1, j - 1] + cost)); // Substitution - - if (i > 1 && j > 1 && str1[i - 1] == str2[j - 2] && str1[i - 2] == str2[j - 1]) - { - d[i, j] = Math.Min(d[i, j], d[i - 2, j - 2] + cost); - } - } - } - return d[str1.Length, str2.Length]; - } - - - public static unsafe int YetiLevenshtein(string s1, string s2) - { - fixed (char* p1 = s1) - fixed (char* p2 = s2) - { - return YetiLevenshtein(p1, s1.Length, p2, s2.Length, 0); // substitutionCost = 1 - } - } - - public static unsafe int YetiLevenshtein(string s1, string s2, int substitionCost) - { - int xc = substitionCost - 1; - if (xc < 0 || xc > 1) - { - throw new ArgumentException("", "substitionCost"); - } - - fixed (char* p1 = s1) - fixed (char* p2 = s2) - { - return YetiLevenshtein(p1, s1.Length, p2, s2.Length, xc); - } - } - - /// - /// Cetin Sert, David Necas - /// Source Code - /// - /// - /// - /// - /// - /// - /// - public static unsafe int YetiLevenshtein(char* s1, int l1, char* s2, int l2, int xcost) - { - int i; - //int *row; /* we only need to keep one row of costs */ - int* end; - int half; - - /* strip common prefix */ - while (l1 > 0 && l2 > 0 && *s1 == *s2) - { - l1--; - l2--; - s1++; - s2++; - } - - /* strip common suffix */ - while (l1 > 0 && l2 > 0 && s1[l1 - 1] == s2[l2 - 1]) - { - l1--; - l2--; - } - - /* catch trivial cases */ - if (l1 == 0) - { - return l2; - } - if (l2 == 0) - { - return l1; - } - - /* make the inner cycle (i.e. string2) the longer one */ - if (l1 > l2) - { - int nx = l1; - char* sx = s1; - l1 = l2; - l2 = nx; - s1 = s2; - s2 = sx; - } - - //check len1 == 1 separately - if (l1 == 1) - { - //throw new NotImplementedException(); - if (xcost > 0) - //return l2 + 1 - 2*(memchr(s2, *s1, l2) != NULL); - { - return l2 + 1 - 2 * memchrRPLC(s2, *s1, l2); - } - else - //return l2 - (memchr(s2, *s1, l2) != NULL); - { - return l2 - memchrRPLC(s2, *s1, l2); - } - } - - l1++; - l2++; - half = l1 >> 1; - - /* initalize first row */ - //row = (int*)malloc(l2*sizeof(int)); - int* row = stackalloc int[l2]; - if (l2 < 0) - //if (!row) - { - return (int) -1; - } - end = row + l2 - 1; - for (i = 0; i < l2 - (xcost > 0 ? 0 : half); i++) - { - row[i] = i; - } - - /* go through the matrix and compute the costs. yes, this is an extremely - * obfuscated version, but also extremely memory-conservative and - * relatively fast. - */ - if (xcost > 0) - { - for (i = 1; i < l1; i++) - { - int* p = row + 1; - char char1 = s1[i - 1]; - char* char2p = s2; - int D = i; - int x = i; - while (p <= end) - { - if (char1 == *char2p++) - { - x = --D; - } - else - { - x++; - } - D = *p; - D++; - if (x > D) - { - x = D; - } - *p++ = x; - } - } - } - else - { - /* in this case we don't have to scan two corner triangles (of size len1/2) - * in the matrix because no best path can go throught them. note this - * breaks when len1 == len2 == 2 so the memchr() special case above is - * necessary */ - row[0] = l1 - half - 1; - for (i = 1; i < l1; i++) - { - int* p; - char char1 = s1[i - 1]; - char* char2p; - int D, x; - /* skip the upper triangle */ - if (i >= l1 - half) - { - int offset = i - (l1 - half); - int c3; - - char2p = s2 + offset; - p = row + offset; - c3 = *p++ + (char1 != *char2p++ ? 1 : 0); - x = *p; - x++; - D = x; - if (x > c3) - { - x = c3; - } - *p++ = x; - } - else - { - p = row + 1; - char2p = s2; - D = x = i; - } - /* skip the lower triangle */ - if (i <= half + 1) - { - end = row + l2 + i - half - 2; - } - /* main */ - while (p <= end) - { - int c3 = --D + (char1 != *char2p++ ? 1 : 0); - x++; - if (x > c3) - { - x = c3; - } - D = *p; - D++; - if (x > D) - { - x = D; - } - *p++ = x; - } - /* lower triangle sentinel */ - if (i <= half) - { - int c3 = --D + (char1 != *char2p ? 1 : 0); - x++; - if (x > c3) - { - x = c3; - } - *p = x; - } - } - } - - i = *end; - return i; - } - - /// - /// Returns true, if the given string is null or empty - /// - /// - /// - public static bool IsNull(string toTest) - { - return toTest == null || toTest.Length == 0; - } - - /// - /// Returns true, if the given string is null or empty or contains only spaces - /// - /// - /// - public static bool IsNullOrSpaces(string toTest) - { - return toTest == null || toTest.Trim().Length == 0; - } - - [Conditional("DEBUG")] - public static void AssertTrue(bool condition, string msg) - { - if (!condition) - { - MessageBox.Show("Assertion: " + msg); - throw new Exception(msg); - } - } - - public string GetWordFromPos(int xPos, string text, Graphics g, Font font) - { - string[] words = text.Split(new char[] {' ', '.', ':', ';'}); - int i = 0; - int index = 0; - List crList = []; - for (i = 0; i < words.Length; ++i) - { - crList.Add(new CharacterRange(index, words[i].Length)); - index += words[i].Length; - } - CharacterRange[] crArray = crList.ToArray(); - StringFormat stringFormat = new(StringFormat.GenericTypographic); - stringFormat.Trimming = StringTrimming.None; - stringFormat.FormatFlags = StringFormatFlags.NoClip; - stringFormat.SetMeasurableCharacterRanges(crArray); - RectangleF rect = new(0, 0, 3000, 20); - Region[] stringRegions = g.MeasureCharacterRanges(text, - font, rect, stringFormat); - bool found = false; - i = 0; - foreach (Region regio in stringRegions) - { - if (regio.IsVisible(xPos, 3, g)) - { - found = true; - break; - } - i++; - } - if (found) - { - return words[i]; - } - else - { - return null; - } - } - - #endregion - - #region Private Methods - - private static bool TestFilterMatch(FilterParams filterParams, ILogLine line, - LogExpert.ILogLineColumnizerCallback columnizerCallback) - { - string lowerSearchText; - string searchText; - Regex rex; - if (filterParams.isInRange) - { - lowerSearchText = filterParams.lowerRangeSearchText; - searchText = filterParams.rangeSearchText; - rex = filterParams.rangeRex; - } - else - { - lowerSearchText = filterParams.lowerSearchText; - searchText = filterParams.searchText; - rex = filterParams.rex; - } - - if (searchText == null || lowerSearchText == null || searchText.Length == 0) - { - return false; - } - - if (filterParams.columnRestrict) - { - IColumnizedLogLine columns = filterParams.currentColumnizer.SplitLine(columnizerCallback, line); - bool found = false; - foreach (int colIndex in filterParams.columnList) - { - if (colIndex < columns.ColumnValues.Length - ) // just to be sure, maybe the columnizer has changed anyhow - { - if (columns.ColumnValues[colIndex].FullValue.Trim().Length == 0) - { - if (filterParams.emptyColumnUsePrev) - { - string prevValue = (string) filterParams.lastNonEmptyCols[colIndex]; - if (prevValue != null) - { - if (TestMatchSub(filterParams, prevValue, lowerSearchText, searchText, rex, - filterParams.exactColumnMatch)) - { - found = true; - } - } - } - else if (filterParams.emptyColumnHit) - { - return true; - } - } - else - { - filterParams.lastNonEmptyCols[colIndex] = columns.ColumnValues[colIndex].FullValue; - if (TestMatchSub(filterParams, columns.ColumnValues[colIndex].FullValue, lowerSearchText, - searchText, rex, - filterParams.exactColumnMatch)) - { - found = true; - } - } - } - } - return found; - } - else - { - return TestMatchSub(filterParams, line.FullLine, lowerSearchText, searchText, rex, false); - } - } - - // - private static bool TestMatchSub(FilterParams filterParams, string line, string lowerSearchText, - string searchText, Regex rex, bool exactMatch) - { - if (filterParams.isRegex) - { - if (rex.IsMatch(line)) - { - return true; - } - } - else - { - if (!filterParams.isCaseSensitive) - { - if (exactMatch) - { - if (line.ToLower().Trim().Equals(lowerSearchText)) - { - return true; - } - } - else - { - if (line.ToLower().Contains(lowerSearchText)) - { - return true; - } - } - } - else - { - if (exactMatch) - { - if (line.Equals(searchText)) - { - return true; - } - } - else - { - if (line.Contains(searchText)) - { - return true; - } - } - } - - if (filterParams.fuzzyValue > 0) - { - int range = line.Length - searchText.Length; - if (range > 0) - { - for (int i = 0; i < range; ++i) - { - string src = line.Substring(i, searchText.Length); - if (!filterParams.isCaseSensitive) - { - src = src.ToLower(); - } - string dest = filterParams.isCaseSensitive ? searchText : lowerSearchText; - int dist = DamerauLevenshteinDistance(src, searchText); - if ((float) (searchText.Length + 1) / (float) (dist + 1) >= - 11F / (float) (filterParams.fuzzyValue + 1F)) - { - return true; - } - } - } - return false; - } - } - return false; - } - - private static unsafe int memchrRPLC(char* buffer, char c, int count) - { - char* p = buffer; - char* e = buffer + count; - while (p++ < e) - { - if (*p == c) - { - return 1; - } - } - return 0; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/Win32.cs b/src/LogExpert/Classes/Win32.cs deleted file mode 100644 index def689b1..00000000 --- a/src/LogExpert/Classes/Win32.cs +++ /dev/null @@ -1,119 +0,0 @@ -using System; -using System.Drawing; -using System.Runtime.InteropServices; - -namespace LogExpert.Classes -{ - internal static class Win32 - { - #region Fields - - public const long SM_CYVSCROLL = 20; - public const long SM_CXHSCROLL = 21; - public const long SM_CXVSCROLL = 2; - public const long SM_CYHSCROLL = 3; - - #endregion - - #region Public methods - - [DllImport("user32.dll")] - public static extern bool DestroyIcon(IntPtr hIcon); - - public static Icon LoadIconFromExe(string fileName, int index) - { - //IntPtr[] smallIcons = new IntPtr[1]; - //IntPtr[] largeIcons = new IntPtr[1]; - IntPtr smallIcons = new(); - IntPtr largeIcons = new(); - int num = (int)ExtractIconEx(fileName, index, ref largeIcons, ref smallIcons, 1); - if (num > 0 && smallIcons.ToInt32() != 0) - { - Icon icon = Icon.FromHandle(smallIcons).Clone() as Icon; - DestroyIcon(smallIcons); - return icon; - } - if (num > 0 && largeIcons.ToInt32() != 0) - { - Icon icon = Icon.FromHandle(largeIcons).Clone() as Icon; - DestroyIcon(largeIcons); - return icon; - } - return null; - } - - - public static Icon[,] ExtractIcons(string fileName) - { - IntPtr smallIcon = IntPtr.Zero; - IntPtr largeIcon = IntPtr.Zero; - int iconCount = (int)ExtractIconEx(fileName, -1, ref largeIcon, ref smallIcon, 0); - if (iconCount <= 0) - { - return null; - } - - IntPtr smallIcons = new(); - IntPtr largeIcons = new(); - Icon[,] result = new Icon[2, iconCount]; - - for (int i = 0; i < iconCount; ++i) - { - int num = (int)ExtractIconEx(fileName, i, ref largeIcons, ref smallIcons, 1); - if (smallIcons.ToInt32() != 0) - { - result[0, i] = Icon.FromHandle(smallIcons).Clone() as Icon; - DestroyIcon(smallIcons); - } - else - { - result[0, i] = null; - } - if (num > 0 && largeIcons.ToInt32() != 0) - { - result[1, i] = Icon.FromHandle(largeIcons).Clone() as Icon; - DestroyIcon(largeIcons); - } - else - { - result[1, i] = null; - } - } - return result; - } - - [DllImport("user32.dll")] - public static extern long GetSystemMetricsForDpi(long index); - - - [DllImport("user32.dll")] - public static extern long GetSystemMetrics(long index); - - [DllImport("user32.dll")] - public static extern short GetKeyState(int vKey); - - #endregion - - #region Private Methods - - /* - UINT ExtractIconEx( - LPCTSTR lpszFile, - int nIconIndex, - HICON *phiconLarge, - HICON *phiconSmall, - UINT nIcons - ); - * */ - - [DllImport("shell32.dll")] - private static extern uint ExtractIconEx(string fileName, - int iconIndex, - ref IntPtr iconsLarge, - ref IntPtr iconsSmall, - uint numIcons - ); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/xml/XmlBlockSplitter.cs b/src/LogExpert/Classes/xml/XmlBlockSplitter.cs deleted file mode 100644 index fac013f5..00000000 --- a/src/LogExpert/Classes/xml/XmlBlockSplitter.cs +++ /dev/null @@ -1,172 +0,0 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Text; -using System.Xml; -using System.Xml.Xsl; -using LogExpert.Classes.Log; - -namespace LogExpert.Classes.xml -{ - internal class XmlBlockSplitter : LogStreamReaderBase - { - #region Fields - - private static readonly string[] _splitStrings = { "\r\n", "\n", "\r" }; - - private static readonly char[] _newLineChar = { '\n' }; - - private readonly XmlLogReader _reader; - - private readonly XmlParserContext _context; - private readonly XmlReaderSettings _settings; - - private readonly Queue _lineList = new(); - - private string _stylesheet; - private XslCompiledTransform _xslt; - - #endregion - - #region cTor - - public XmlBlockSplitter(XmlLogReader reader, IXmlLogConfiguration xmlLogConfig) - { - _reader = reader; - _reader.StartTag = xmlLogConfig.XmlStartTag; - _reader.EndTag = xmlLogConfig.XmlEndTag; - - Stylesheet = xmlLogConfig.Stylesheet; - - // Create the XmlNamespaceManager. - NameTable nt = new(); - XmlNamespaceManager nsmgr = new(nt); - if (xmlLogConfig.Namespace != null) - { - nsmgr.AddNamespace(xmlLogConfig.Namespace[0], xmlLogConfig.Namespace[1]); - } - // Create the XmlParserContext. - _context = new XmlParserContext(nt, nsmgr, null, XmlSpace.None); - _settings = new XmlReaderSettings(); - _settings.ConformanceLevel = ConformanceLevel.Fragment; - } - - #endregion - - #region Properties - - public override long Position - { - get => _reader.Position; - set => _reader.Position = value; - } - - public override Encoding Encoding => _reader.Encoding; - - public override bool IsBufferComplete => _lineList.Count == 0; - - public string Stylesheet - { - get => _stylesheet; - set - { - _stylesheet = value; - if (_stylesheet != null) - { - XmlReader stylesheetReader = XmlReader.Create(new StringReader(_stylesheet)); - - _xslt = new XslCompiledTransform(); - _xslt.Load(stylesheetReader); - } - else - { - _xslt = null; - } - } - } - - #endregion - - #region Private Methods - - private void ParseXmlBlock(string block) - { - if (_stylesheet != null) - { - XmlReader xmlReader = XmlReader.Create(new StringReader(block), _settings, _context); - - xmlReader.Read(); - xmlReader.MoveToContent(); - //xmlReader.MoveToContent(); - StringWriter textWriter = new(); - - _xslt.Transform(xmlReader, null, textWriter); - string message = textWriter.ToString(); - SplitToLinesList(message); - } - else - { - SplitToLinesList(block); - //this.lineList.Add(block); // TODO: make configurable, if block has to be splitted - } - } - - private void SplitToLinesList(string message) - { - const int MAX_LEN = 3000; - string[] lines = message.Split(_splitStrings, StringSplitOptions.None); - foreach (string theLine in lines) - { - string line = theLine.Trim(_newLineChar); - while (line.Length > MAX_LEN) - { - string part = line.Substring(0, MAX_LEN); - line = line.Substring(MAX_LEN); - _lineList.Enqueue(part); - } - _lineList.Enqueue(line); - } - } - - #endregion - - #region Public Methods - - protected override void Dispose(bool disposing) - { - if (disposing) - { - _reader.Dispose(); - } - } - - public override int ReadChar() - { - return _reader.ReadChar(); - } - - public override string ReadLine() - { - if (_lineList.Count == 0) - { - string block = _reader.ReadLine(); - if (block == null) - { - return null; - } - - try - { - ParseXmlBlock(block); - } - catch (XmlException) - { - _lineList.Enqueue("[XML Parser error] " + block); - } - } - return _lineList.Dequeue(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Classes/xml/XmlLogReader.cs b/src/LogExpert/Classes/xml/XmlLogReader.cs deleted file mode 100644 index b64294e9..00000000 --- a/src/LogExpert/Classes/xml/XmlLogReader.cs +++ /dev/null @@ -1,171 +0,0 @@ -using System.Text; -using System.Threading; -using LogExpert.Classes.Log; -using LogExpert.Interface; - -namespace LogExpert.Classes.xml -{ - internal class XmlLogReader : LogStreamReaderBase - { - #region Fields - - private readonly ILogStreamReader reader; - - #endregion - - #region cTor - - public XmlLogReader(ILogStreamReader reader) - { - this.reader = reader; - } - - #endregion - - #region Properties - - public override long Position - { - get => reader.Position; - set => reader.Position = value; - } - - public override Encoding Encoding => reader.Encoding; - - public override bool IsBufferComplete => reader.IsBufferComplete; - - public string StartTag { get; set; } = " 0) - { - Thread.Sleep(100); - continue; - } - else - { - eof = true; - break; - } - } - else - { - eof = true; - break; - } - } - - char readChar = (char)readInt; - // state: - // 0 = looking for tag start - // 1 = reading into buffer as long as the read data matches the start tag - // 2 = reading into buffer while waiting for the begin of the end tag - // 3 = reading into buffer as long as data matches the end tag. stopping when tag complete - switch (state) - { - case 0: - if (readChar == StartTag[0]) - { - //_logger.logInfo("state = 1"); - state = 1; - tagIndex = 1; - builder.Append(readChar); - } - //else - //{ - // _logger.logInfo("char: " + readChar); - //} - break; - case 1: - if (readChar == StartTag[tagIndex]) - { - builder.Append(readChar); - - if (++tagIndex >= StartTag.Length) - { - //_logger.logInfo("state = 2"); - state = 2; // start Tag complete - tagIndex = 0; - } - } - else - { - // tag doesn't match anymore - //_logger.logInfo("state = 0 [" + buffer.ToString() + readChar + "]"); - state = 0; - builder.Clear(); - } - break; - case 2: - builder.Append(readChar); - - if (readChar == EndTag[0]) - { - //_logger.logInfo("state = 3"); - state = 3; - tagIndex = 1; - } - break; - case 3: - builder.Append(readChar); - - if (readChar == EndTag[tagIndex]) - { - tagIndex++; - if (tagIndex >= EndTag.Length) - { - blockComplete = true; - break; - } - } - else - { - //_logger.logInfo("state = 2"); - state = 2; - } - break; - } - } - - return blockComplete ? builder.ToString() : null; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/ColorEntry.cs b/src/LogExpert/Config/ColorEntry.cs deleted file mode 100644 index 250b1c11..00000000 --- a/src/LogExpert/Config/ColorEntry.cs +++ /dev/null @@ -1,31 +0,0 @@ -#region - -using System; -using System.Drawing; - -#endregion - -namespace LogExpert.Config -{ - [Serializable] - public class ColorEntry - { - #region cTor - - public ColorEntry(string fileName, Color color) - { - FileName = fileName; - Color = color; - } - - #endregion - - public Color Color { get; } - - public string FileName { get; } - - #region Fields - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/ColorMode.cs b/src/LogExpert/Config/ColorMode.cs deleted file mode 100644 index 3e203602..00000000 --- a/src/LogExpert/Config/ColorMode.cs +++ /dev/null @@ -1,111 +0,0 @@ -using System; -using System.Drawing; -using System.Runtime.InteropServices; - -namespace LogExpert.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.FromArgb(253, 253, 253); - private static readonly Color BrightForeColor = Color.FromArgb(0, 0, 0); - - // 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.FromArgb(255, 255, 255); - - // 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() - { - var preferences = ConfigManager.Settings.Preferences; - - if (preferences.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; - } - - #region TitleBarDarkMode - [DllImport("dwmapi.dll")] - private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attr, ref int attrValue, int attrSize); - - private const int DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19; - private const int DWMWA_USE_IMMERSIVE_DARK_MODE = 20; - - public static bool UseImmersiveDarkMode(IntPtr handle, bool enabled) - { - - var attribute = DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1; - if (IsWindows10OrGreater(18985)) - { - attribute = DWMWA_USE_IMMERSIVE_DARK_MODE; - } - - int useImmersiveDarkMode = enabled ? 1 : 0; - return DwmSetWindowAttribute(handle, (int)attribute, ref useImmersiveDarkMode, sizeof(int)) == 0; - - } - - private static bool IsWindows10OrGreater(int build = -1) - { - return Environment.OSVersion.Version.Major >= 10 && Environment.OSVersion.Version.Build >= build; - } - - #endregion TitleBarDarkMode - - } -} diff --git a/src/LogExpert/Config/ColumnizerHistoryEntry.cs b/src/LogExpert/Config/ColumnizerHistoryEntry.cs deleted file mode 100644 index dc2a3058..00000000 --- a/src/LogExpert/Config/ColumnizerHistoryEntry.cs +++ /dev/null @@ -1,30 +0,0 @@ -#region - -using System; - -#endregion - -namespace LogExpert.Config -{ - [Serializable] - public class ColumnizerHistoryEntry - { - #region cTor - - public ColumnizerHistoryEntry(string fileName, string columnizerName) - { - FileName = fileName; - ColumnizerName = columnizerName; - } - - #endregion - - #region Fields - - public string FileName { get; } - - #endregion - - public string ColumnizerName { get; } - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/ColumnizerMaskEntry.cs b/src/LogExpert/Config/ColumnizerMaskEntry.cs deleted file mode 100644 index ad897b54..00000000 --- a/src/LogExpert/Config/ColumnizerMaskEntry.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace LogExpert.Config -{ - [Serializable] - public class ColumnizerMaskEntry - { - #region Fields - - public string columnizerName; - public string mask; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/ConfigManager.cs b/src/LogExpert/Config/ConfigManager.cs index 96639027..23213246 100644 --- a/src/LogExpert/Config/ConfigManager.cs +++ b/src/LogExpert/Config/ConfigManager.cs @@ -1,437 +1,437 @@ -using LogExpert.Classes; -using LogExpert.Classes.Filter; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; +using System.Drawing; +using System.Globalization; +using System.Reflection; +using System.Text; +using System.Windows.Forms; + +using LogExpert.Core.Classes; +using LogExpert.Core.Classes.Filter; +using LogExpert.Core.Config; +using LogExpert.Core.Entities; +using LogExpert.Core.EventArguments; +using LogExpert.Core.Interface; using Newtonsoft.Json; using NLog; -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Windows.Forms; +namespace LogExpert.Config; -namespace LogExpert.Config +public class ConfigManager : IConfigManager { - public class ConfigManager - { - #region Fields + #region Fields - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - private static readonly object _monitor = new(); - private static ConfigManager _instance; - private readonly object _loadSaveLock = new(); - private Settings _settings; + private static readonly object _monitor = new(); + private static ConfigManager _instance; + private readonly object _loadSaveLock = new(); + private Settings _settings; - #endregion + #endregion - #region cTor + #region cTor - private ConfigManager() - { - _settings = Load(); - } + private ConfigManager () + { + _settings = Load(); + } - #endregion + #endregion - #region Events + #region Events - internal event ConfigChangedEventHandler ConfigChanged; + public event EventHandler ConfigChanged; - #endregion + #endregion - #region Properties + #region Properties - public static ConfigManager Instance + //TODO: Change to init + public static ConfigManager Instance + { + get { - get + lock (_monitor) { - lock (_monitor) - { - _instance ??= new ConfigManager(); - } - return _instance; + _instance ??= new ConfigManager(); } + return _instance; } + } - public static string ConfigDir => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar + "LogExpert"; + public string ConfigDir => Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + Path.DirectorySeparatorChar + "LogExpert"; //TODO: change to Path.Combine - /// - /// Application.StartupPath + portable - /// - public static string PortableModeDir => Application.StartupPath + Path.DirectorySeparatorChar + "portable"; + /// + /// Application.StartupPath + portable + /// + public string PortableModeDir => Application.StartupPath + Path.DirectorySeparatorChar + "portable"; - /// - /// portableMode.json - /// - public static string PortableModeSettingsFileName => "portableMode.json"; + /// + /// portableMode.json + /// + public string PortableModeSettingsFileName => "portableMode.json"; - public static Settings Settings => Instance._settings; + public Settings Settings => Instance._settings; - #endregion + IConfigManager IConfigManager.Instance => Instance; - #region Public methods + // Action IConfigManager.ConfigChanged { get => ((IConfigManager)_instance).ConfigChanged; set => ((IConfigManager)_instance).ConfigChanged = value; } + + //public string PortableModeSettingsFileName => ((IConfigManager)_instance).PortableModeSettingsFileName; + + #endregion + + #region Public methods + + public void Save (SettingsFlags flags) + { + Instance.Save(Settings, flags); + } + + public void Export (FileInfo fileInfo) + { + Instance.Save(fileInfo, Settings); + } + + public void Export (FileInfo fileInfo, SettingsFlags flags) + { + Instance.Save(fileInfo, Settings, flags); + } + + public void Import (FileInfo fileInfo, ExportImportFlags flags) + { + Instance._settings = Instance.Import(Instance._settings, fileInfo, flags); + Save(SettingsFlags.All); + } + + public void ImportHighlightSettings (FileInfo fileInfo, ExportImportFlags flags) + { + Instance._settings.Preferences.HighlightGroupList = Instance.Import(Instance._settings.Preferences.HighlightGroupList, fileInfo, flags); + Save(SettingsFlags.All); + } + + #endregion + + #region Private Methods + + private Settings Load () + { + _logger.Info(CultureInfo.InvariantCulture, "Loading settings"); + + string dir; + + if (!File.Exists(Path.Combine(PortableModeDir, PortableModeSettingsFileName))) + { + _logger.Info(CultureInfo.InvariantCulture, "Load settings standard mode"); + dir = ConfigDir; + } + else + { + _logger.Info("Load settings portable mode"); + dir = Application.StartupPath; + } - public static void Save(SettingsFlags flags) + if (!Directory.Exists(dir)) { - Instance.Save(Settings, flags); + _ = Directory.CreateDirectory(dir); } - public static void Export(FileInfo fileInfo) + if (!File.Exists(Path.Combine(dir, "settings.json"))) { - Instance.Save(fileInfo, Settings); + return LoadOrCreateNew(null); } - public static void Import(FileInfo fileInfo, ExportImportFlags flags) + try { - Instance._settings = Instance.Import(Instance._settings, fileInfo, flags); - Save(SettingsFlags.All); + FileInfo fileInfo = new(Path.Combine(dir, "settings.json")); + return LoadOrCreateNew(fileInfo); + } + catch (IOException ex) + { + _logger.Error($"File system error: {ex.Message}"); + } + catch (UnauthorizedAccessException ex) + { + _logger.Error($"Access denied: {ex.Message}"); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.Error($"Unexpected error: {ex.Message}"); } - #endregion + return LoadOrCreateNew(null); - #region Private Methods + } - private Settings Load() + /// + /// Loads Settings of a given file or creates new settings if the file does not exist + /// + /// file that has settings saved + /// loaded or created settings + private Settings LoadOrCreateNew (FileInfo fileInfo) + { + lock (_loadSaveLock) { - _logger.Info("Loading settings"); - - string dir; + Settings settings; - if (File.Exists(PortableModeDir + Path.DirectorySeparatorChar + PortableModeSettingsFileName) == false) + if (fileInfo == null || fileInfo.Exists == false) { - _logger.Info("Load settings standard mode"); - dir = ConfigDir; + settings = new Settings(); } else { - _logger.Info("Load settings portable mode"); - dir = Application.StartupPath; + try + { + settings = JsonConvert.DeserializeObject(File.ReadAllText($"{fileInfo.FullName}")); + } + catch (Exception e) + { + _logger.Error($"Error while deserializing config data: {e}"); + settings = new Settings(); + } } - if (!Directory.Exists(dir)) - { - Directory.CreateDirectory(dir); - } + settings.Preferences ??= new Preferences(); + + settings.Preferences.ToolEntries ??= []; + + settings.Preferences.ColumnizerMaskList ??= []; + + settings.FileHistoryList ??= []; + + settings.LastOpenFilesList ??= []; + + settings.FileColors ??= []; - if (!File.Exists(dir + Path.DirectorySeparatorChar + "settings.json")) + if (settings.Preferences.ShowTailColor == Color.Empty) { - return LoadOrCreateNew(null); + settings.Preferences.ShowTailColor = Color.FromKnownColor(KnownColor.Blue); } - try + if (settings.Preferences.TimeSpreadColor == Color.Empty) { - FileInfo fileInfo = new(dir + Path.DirectorySeparatorChar + "settings.json"); - return LoadOrCreateNew(fileInfo); + settings.Preferences.TimeSpreadColor = Color.Gray; } - catch (Exception e) + + if (settings.Preferences.BufferCount < 10) { - _logger.Error($"Error loading settings: {e}"); - return LoadOrCreateNew(null); + settings.Preferences.BufferCount = 100; } - } - - /// - /// Loads Settings of a given file or creates new settings if the file does not exist - /// - /// file that has settings saved - /// loaded or created settings - private Settings LoadOrCreateNew(FileSystemInfo fileInfo) - { - lock (_loadSaveLock) + if (settings.Preferences.LinesPerBuffer < 1) { - Settings settings; + settings.Preferences.LinesPerBuffer = 500; + } - if (fileInfo == null || fileInfo.Exists == false) - { - settings = new Settings(); - } - else - { - try - { - settings = JsonConvert.DeserializeObject(File.ReadAllText($"{fileInfo.FullName}")); - } - catch (Exception e) - { - _logger.Error($"Error while deserializing config data: {e}"); - settings = new Settings(); - } - } + settings.FilterList ??= []; - settings.Preferences ??= new Preferences(); + settings.SearchHistoryList ??= []; - settings.Preferences.toolEntries ??= []; + settings.FilterHistoryList ??= []; - settings.Preferences.columnizerMaskList ??= []; + settings.FilterRangeHistoryList ??= []; - settings.fileHistoryList ??= []; + foreach (FilterParams filterParams in settings.FilterList) + { + filterParams.Init(); + } - settings.lastOpenFilesList ??= []; + if (settings.Preferences.HighlightGroupList == null) + { + settings.Preferences.HighlightGroupList = []; + } - settings.fileColors ??= []; + settings.Preferences.HighlightMaskList ??= []; - if (settings.Preferences.showTailColor == Color.Empty) - { - settings.Preferences.showTailColor = Color.FromKnownColor(KnownColor.Blue); - } + if (settings.Preferences.PollingInterval < 20) + { + settings.Preferences.PollingInterval = 250; + } - if (settings.Preferences.timeSpreadColor == Color.Empty) - { - settings.Preferences.timeSpreadColor = Color.Gray; - } + settings.Preferences.MultiFileOptions ??= new MultiFileOptions(); - if (settings.Preferences.bufferCount < 10) - { - settings.Preferences.bufferCount = 100; - } + settings.Preferences.DefaultEncoding ??= Encoding.Default.HeaderName; - if (settings.Preferences.linesPerBuffer < 1) - { - settings.Preferences.linesPerBuffer = 500; - } + if (settings.Preferences.MaximumFilterEntriesDisplayed == 0) + { + settings.Preferences.MaximumFilterEntriesDisplayed = 20; + } - settings.filterList ??= []; + if (settings.Preferences.MaximumFilterEntries == 0) + { + settings.Preferences.MaximumFilterEntries = 30; + } - settings.searchHistoryList ??= []; + SetBoundsWithinVirtualScreen(settings); - settings.filterHistoryList ??= []; + return settings; + } + } - settings.filterRangeHistoryList ??= []; + /// + /// Saves the Settings to file, fires OnConfigChanged Event so LogTabWindow is updated + /// + /// Settings to be saved + /// Settings that "changed" + private void Save (Settings settings, SettingsFlags flags) + { + lock (_loadSaveLock) + { + _logger.Info(CultureInfo.InvariantCulture, "Saving settings"); + var dir = Settings.Preferences.PortableMode ? Application.StartupPath : ConfigDir; - foreach (FilterParams filterParams in settings.filterList) - { - filterParams.Init(); - } + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } - if (settings.hilightGroupList == null) - { - settings.hilightGroupList = []; - // migrate old non-grouped entries - HilightGroup defaultGroup = new() - { - GroupName = "[Default]", - HilightEntryList = settings.hilightEntryList - }; - - settings.hilightGroupList.Add(defaultGroup); - } + FileInfo fileInfo = new(dir + Path.DirectorySeparatorChar + "settings.json"); + Save(fileInfo, settings); - settings.Preferences.highlightMaskList ??= []; + OnConfigChanged(flags); + } + } - if (settings.Preferences.pollingInterval < 20) - { - settings.Preferences.pollingInterval = 250; - } + /// + /// Saves the file in any defined format + /// + /// FileInfo for creating the file (if exists will be overwritten) + /// Current Settings + private void Save (FileInfo fileInfo, Settings settings) + { + //Currently only fileFormat, maybe add some other formats later (YAML or XML?) + SaveAsJSON(fileInfo, settings); + } - settings.Preferences.multiFileOptions ??= new MultiFileOptions(); + private void Save (FileInfo fileInfo, Settings settings, SettingsFlags flags) + { + switch (flags) + { + case SettingsFlags.HighlightSettings: + SaveHighlightgroupsAsJSON(fileInfo, settings.Preferences.HighlightGroupList); + break; + } - settings.Preferences.defaultEncoding ??= Encoding.Default.HeaderName; + OnConfigChanged(flags); + } - if (settings.Preferences.maximumFilterEntriesDisplayed == 0) - { - settings.Preferences.maximumFilterEntriesDisplayed = 20; - } + private static void SaveAsJSON (FileInfo fileInfo, Settings settings) + { + settings.VersionBuild = Assembly.GetExecutingAssembly().GetName().Version.Build; - if (settings.Preferences.maximumFilterEntries == 0) - { - settings.Preferences.maximumFilterEntries = 30; - } + using StreamWriter sw = new(fileInfo.Create()); + JsonSerializer serializer = new(); + serializer.Serialize(sw, settings); + } - SetBoundsWithinVirtualScreen(settings); + private static void SaveHighlightgroupsAsJSON (FileInfo fileInfo, List groups) + { + using StreamWriter sw = new(fileInfo.Create()); + JsonSerializer serializer = new(); + serializer.Serialize(sw, groups); + } - ConvertSettings(settings); + private List Import (List currentGroups, FileInfo fileInfo, ExportImportFlags flags) + { + List newGroups; - return settings; - } + try + { + newGroups = JsonConvert.DeserializeObject>(File.ReadAllText($"{fileInfo.FullName}")); + } + catch (Exception e) + { + _logger.Error($"Error while deserializing config data: {e}"); + newGroups = []; } - /// - /// Saves the Settings to file, fires OnConfigChanged Event so LogTabWindow is updated - /// - /// Settings to be saved - /// Settings that "changed" - private void Save(Settings settings, SettingsFlags flags) + if (flags.HasFlag(ExportImportFlags.KeepExisting)) { - lock (_loadSaveLock) - { - _logger.Info("Saving settings"); - lock (this) - { - string dir = Settings.Preferences.PortableMode ? Application.StartupPath : ConfigDir; + currentGroups.AddRange(newGroups); + } + else + { + currentGroups.Clear(); + currentGroups.AddRange(newGroups); + } - if (!Directory.Exists(dir)) - { - Directory.CreateDirectory(dir); - } + return currentGroups; + } - FileInfo fileInfo = new(dir + Path.DirectorySeparatorChar + "settings.json"); - Save(fileInfo, settings); - } + /// + /// Imports all or some of the settings/prefs stored in the input stream. + /// This will overwrite appropriate parts of the current (own) settings with the imported ones. + /// + /// + /// + /// Flags to indicate which parts shall be imported + private Settings Import (Settings currentSettings, FileInfo fileInfo, ExportImportFlags flags) + { + var importSettings = LoadOrCreateNew(fileInfo); + var ownSettings = ObjectClone.Clone(currentSettings); + Settings newSettings; - OnConfigChanged(flags); - } + // at first check for 'Other' as this are the most options. + if ((flags & ExportImportFlags.Other) == ExportImportFlags.Other) + { + newSettings = ownSettings; + newSettings.Preferences = ObjectClone.Clone(importSettings.Preferences); + newSettings.Preferences.ColumnizerMaskList = ownSettings.Preferences.ColumnizerMaskList; + newSettings.Preferences.HighlightMaskList = ownSettings.Preferences.HighlightMaskList; + newSettings.Preferences.HighlightGroupList = ownSettings.Preferences.HighlightGroupList; + newSettings.Preferences.ToolEntries = ownSettings.Preferences.ToolEntries; } - - /// - /// Saves the file in any defined format - /// - /// FileInfo for creating the file (if exists will be overwritten) - /// Current Settings - private void Save(FileInfo fileInfo, Settings settings) + else { - //Currently only fileFormat, maybe add some other formats later (YAML or XML?) - SaveAsJSON(fileInfo, settings); + newSettings = ownSettings; } - private void SaveAsJSON(FileInfo fileInfo, Settings settings) + if ((flags & ExportImportFlags.ColumnizerMasks) == ExportImportFlags.ColumnizerMasks) { - settings.versionBuild = Assembly.GetExecutingAssembly().GetName().Version.Build; - - using StreamWriter sw = new(fileInfo.Create()); - JsonSerializer serializer = new(); - serializer.Serialize(sw, settings); + newSettings.Preferences.ColumnizerMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.ColumnizerMaskList, importSettings.Preferences.ColumnizerMaskList); } - - /// - /// Convert settings loaded from previous versions. - /// - /// - private void ConvertSettings(Settings settings) + if ((flags & ExportImportFlags.HighlightMasks) == ExportImportFlags.HighlightMasks) { - //int oldBuildNumber = settings.versionBuild; - - //// All Versions before 3583 - //if (oldBuildNumber < 3584) - //{ - // // External tools - // List newList = []; - // foreach (ToolEntry tool in settings.preferences.toolEntries) - // { - // // set favourite to true only when name is empty, because there are always version released without this conversion fx - // // remove empty tool entries (there were always 3 entries before, which can be empty if not used) - // if (Util.IsNull(tool.name)) - // { - // if (!Util.IsNull(tool.cmd)) - // { - // tool.name = tool.cmd; - // tool.isFavourite = true; - // newList.Add(tool); - // } - // } - // else - // { - // newList.Add(tool); - // } - // if (Util.IsNull(tool.iconFile)) - // { - // tool.iconFile = tool.cmd; - // tool.iconIndex = 0; - // } - // } - // settings.preferences.toolEntries = newList; - //} - - //if (oldBuildNumber < 3584) - //{ - // // Set the color for the FilterList entries to default (black) - // foreach (FilterParams filterParam in settings.filterList) - // { - // filterParam.color = Color.FromKnownColor(KnownColor.Black); - // } - //} + newSettings.Preferences.HighlightMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.HighlightMaskList, importSettings.Preferences.HighlightMaskList); } - - - /// - /// Imports all or some of the settings/prefs stored in the input stream. - /// This will overwrite appropriate parts of the current (own) settings with the imported ones. - /// - /// - /// - /// Flags to indicate which parts shall be imported - private Settings Import(Settings currentSettings, FileInfo fileInfo, ExportImportFlags flags) + if ((flags & ExportImportFlags.HighlightSettings) == ExportImportFlags.HighlightSettings) { - Settings importSettings = LoadOrCreateNew(fileInfo); - Settings ownSettings = ObjectClone.Clone(currentSettings); - Settings newSettings; - - // at first check for 'Other' as this are the most options. - if ((flags & ExportImportFlags.Other) == ExportImportFlags.Other) - { - newSettings = ownSettings; - newSettings.Preferences = ObjectClone.Clone(importSettings.Preferences); - newSettings.Preferences.columnizerMaskList = ownSettings.Preferences.columnizerMaskList; - newSettings.Preferences.highlightMaskList = ownSettings.Preferences.highlightMaskList; - newSettings.hilightGroupList = ownSettings.hilightGroupList; - newSettings.Preferences.toolEntries = ownSettings.Preferences.toolEntries; - } - else - { - newSettings = ownSettings; - } - - if ((flags & ExportImportFlags.ColumnizerMasks) == ExportImportFlags.ColumnizerMasks) - { - newSettings.Preferences.columnizerMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.columnizerMaskList, importSettings.Preferences.columnizerMaskList); - } - if ((flags & ExportImportFlags.HighlightMasks) == ExportImportFlags.HighlightMasks) - { - newSettings.Preferences.highlightMaskList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.highlightMaskList, importSettings.Preferences.highlightMaskList); - } - if ((flags & ExportImportFlags.HighlightSettings) == ExportImportFlags.HighlightSettings) - { - newSettings.hilightGroupList = ReplaceOrKeepExisting(flags, ownSettings.hilightGroupList, importSettings.hilightGroupList); - } - if ((flags & ExportImportFlags.ToolEntries) == ExportImportFlags.ToolEntries) - { - newSettings.Preferences.toolEntries = ReplaceOrKeepExisting(flags, ownSettings.Preferences.toolEntries, importSettings.Preferences.toolEntries); - } - - return newSettings; + newSettings.Preferences.HighlightGroupList = ReplaceOrKeepExisting(flags, ownSettings.Preferences.HighlightGroupList, importSettings.Preferences.HighlightGroupList); } - - private static List ReplaceOrKeepExisting(ExportImportFlags flags, List existingList, List newList) + if ((flags & ExportImportFlags.ToolEntries) == ExportImportFlags.ToolEntries) { - if ((flags & ExportImportFlags.KeepExisting) == ExportImportFlags.KeepExisting) - { - return existingList.Union(newList).ToList(); - } - - return newList; + newSettings.Preferences.ToolEntries = ReplaceOrKeepExisting(flags, ownSettings.Preferences.ToolEntries, importSettings.Preferences.ToolEntries); } - // Checking if the appBounds values are outside the current virtual screen. - // If so, the appBounds values are set to 0. - private void SetBoundsWithinVirtualScreen(Settings settings) + return newSettings; + } + + private static List ReplaceOrKeepExisting (ExportImportFlags flags, List existingList, List newList) + { + if ((flags & ExportImportFlags.KeepExisting) == ExportImportFlags.KeepExisting) { - var vs = SystemInformation.VirtualScreen; - if (vs.X + vs.Width < settings.appBounds.X + settings.appBounds.Width || - vs.Y + vs.Height < settings.appBounds.Y + settings.appBounds.Height) - { - settings.appBounds = new Rectangle(); - } + return existingList.Union(newList).ToList(); } - #endregion - protected void OnConfigChanged(SettingsFlags flags) - { - ConfigChangedEventHandler handler = ConfigChanged; + return newList; + } - if (handler != null) - { - _logger.Info("Fire config changed event"); - handler(this, new ConfigChangedEventArgs(flags)); - } + // Checking if the appBounds values are outside the current virtual screen. + // If so, the appBounds values are set to 0. + private void SetBoundsWithinVirtualScreen (Settings settings) + { + var vs = SystemInformation.VirtualScreen; + if (vs.X + vs.Width < settings.AppBounds.X + settings.AppBounds.Width || + vs.Y + vs.Height < settings.AppBounds.Y + settings.AppBounds.Height) + { + settings.AppBounds = new Rectangle(); } + } + #endregion - internal delegate void ConfigChangedEventHandler(object sender, ConfigChangedEventArgs e); + protected void OnConfigChanged (SettingsFlags flags) + { + ConfigChanged?.Invoke(this, new ConfigChangedEventArgs(flags)); } } \ No newline at end of file diff --git a/src/LogExpert/Config/ExportImportFlags.cs b/src/LogExpert/Config/ExportImportFlags.cs deleted file mode 100644 index 7bdae090..00000000 --- a/src/LogExpert/Config/ExportImportFlags.cs +++ /dev/null @@ -1,18 +0,0 @@ -using System; - -namespace LogExpert.Config -{ - [Flags] - public enum ExportImportFlags : long - { - None = 0, - HighlightSettings = 1, - ColumnizerMasks = 2, - HighlightMasks = 4, - ToolEntries = 8, - Other = 16, - KeepExisting = 32, - All = HighlightSettings | ColumnizerMasks | HighlightMasks | ToolEntries | Other, - AllKeepExisting = All | KeepExisting - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/HighlightMaskEntry.cs b/src/LogExpert/Config/HighlightMaskEntry.cs deleted file mode 100644 index 73fe3217..00000000 --- a/src/LogExpert/Config/HighlightMaskEntry.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System; - -namespace LogExpert.Config -{ - [Serializable] - public class HighlightMaskEntry - { - #region Fields - - public string highlightGroupName; - public string mask; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/MultiFileOption.cs b/src/LogExpert/Config/MultiFileOption.cs deleted file mode 100644 index 249307fd..00000000 --- a/src/LogExpert/Config/MultiFileOption.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System; - -namespace LogExpert.Config -{ - [Serializable] - public enum MultiFileOption - { - SingleFiles, - MultiFile, - Ask - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/Preferences.cs b/src/LogExpert/Config/Preferences.cs deleted file mode 100644 index f93647da..00000000 --- a/src/LogExpert/Config/Preferences.cs +++ /dev/null @@ -1,110 +0,0 @@ -using LogExpert.Dialogs; -using LogExpert.Entities; - -using System; -using System.Collections.Generic; -using System.Drawing; - -namespace LogExpert.Config -{ - [Serializable] - public class Preferences - { - #region Fields - - public bool allowOnlyOneInstance; - - public bool askForClose = false; - - public bool darkMode = false; - - public int bufferCount = 100; - - public List columnizerMaskList = []; - - public string defaultEncoding; - - public bool filterSync = true; - - public bool filterTail = true; - - public bool followTail = true; - - public string fontName = "Courier New"; - - public float fontSize = 9; - - public List highlightMaskList = []; - - public bool isAutoHideFilterList = false; - - public bool isFilterOnLoad; - - public int lastColumnWidth = 2000; - - public int linesPerBuffer = 500; - - public int maximumFilterEntries = 30; - - public int maximumFilterEntriesDisplayed = 20; - - public bool maskPrio; - - public bool autoPick; - - public MultiFileOption multiFileOption; - - public MultiFileOptions multiFileOptions; - - public bool multiThreadFilter = true; - - public bool openLastFiles = true; - - public int pollingInterval = 250; - - public bool reverseAlpha = false; - - public bool PortableMode { get; set; } - - /// - /// Save Directory of the last logfile - /// - public string sessionSaveDirectory = null; - - public bool saveFilters = true; - - public SessionSaveLocation saveLocation = SessionSaveLocation.DocumentsDir; - - public bool saveSessions = true; - - public bool setLastColumnWidth; - - public bool showBubbles = true; - - public bool showColumnFinder; - - public Color showTailColor = Color.FromKnownColor(KnownColor.Blue); - - public bool showTailState = true; - - public bool showTimeSpread = false; - - public Color timeSpreadColor = Color.FromKnownColor(KnownColor.Gray); - - public bool timeSpreadTimeMode; - - public bool timestampControl = true; - - public DateTimeDragControl.DragOrientations timestampControlDragOrientation = DateTimeDragControl.DragOrientations.Horizontal; - - public List toolEntries = []; - - public bool useLegacyReader; - - public bool ShowErrorMessageAllowOnlyOneInstances { get; set; } - - public int MaxLineLength { get; set; } = 20000; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/RegexHistory.cs b/src/LogExpert/Config/RegexHistory.cs deleted file mode 100644 index 2cbcde4f..00000000 --- a/src/LogExpert/Config/RegexHistory.cs +++ /dev/null @@ -1,16 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace LogExpert.Config -{ - [Serializable] - public class RegexHistory - { - #region Fields - - public List expressionHistoryList = []; - public List testtextHistoryList = []; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/SessionSaveLocation.cs b/src/LogExpert/Config/SessionSaveLocation.cs deleted file mode 100644 index 540147b8..00000000 --- a/src/LogExpert/Config/SessionSaveLocation.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -namespace LogExpert.Config -{ - [Serializable] - public enum SessionSaveLocation - { - //Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + Path.DirectorySeparatorChar + "LogExpert" - /// - /// - /// - DocumentsDir, - //same directory as the logfile - SameDir, - //uses configured folder to save the session files - /// - /// - /// - OwnDir, - /// - /// - /// - ApplicationStartupDir, - LoadedSessionFile - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/Settings.cs b/src/LogExpert/Config/Settings.cs deleted file mode 100644 index d21d88a3..00000000 --- a/src/LogExpert/Config/Settings.cs +++ /dev/null @@ -1,62 +0,0 @@ -using LogExpert.Classes.Filter; -using LogExpert.Classes.Highlight; -using LogExpert.Entities; - -using System; -using System.Collections.Generic; -using System.Drawing; - -namespace LogExpert.Config -{ - [Serializable] - public class Settings - { - #region Fields - - public bool alwaysOnTop; - - public Rectangle appBounds; - - public Rectangle appBoundsFullscreen; - - public IList columnizerHistoryList = []; - - public List fileColors = []; - - public List fileHistoryList = []; - - public List filterHistoryList = []; - - public List filterList = []; - - public FilterParams filterParams = new(); - - public List filterRangeHistoryList = []; - - public bool hideLineColumn; - - public List hilightEntryList = []; // legacy. is automatically converted to highlight groups on settings load - - public List hilightGroupList = []; // should be in Preferences but is here for mistake. Maybe I migrate it some day. - - public bool isMaximized; - - public string lastDirectory; - - public List lastOpenFilesList = []; - - public Preferences Preferences { get; set; } = new(); - - public RegexHistory regexHistory = new(); - - public List searchHistoryList = []; - - public SearchParams searchParams = new(); - - public IList uriHistoryList = []; - - public int versionBuild; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/SettingsFlags.cs b/src/LogExpert/Config/SettingsFlags.cs deleted file mode 100644 index a86a63b4..00000000 --- a/src/LogExpert/Config/SettingsFlags.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System; - -namespace LogExpert.Config -{ - [Flags] - public enum SettingsFlags : long - { - None = 0, - WindowPosition = 1, - FileHistory = 2, - HighlightSettings = 4, - FilterList = 8, - RegexHistory = 16, - ToolSettings = 32, - GuiOrColors = 64, - FilterHistory = 128, - - All = WindowPosition | FileHistory | HighlightSettings | - FilterList | RegexHistory | ToolSettings | GuiOrColors | - FilterHistory, - - Settings = All & ~WindowPosition & ~FileHistory, - } -} \ No newline at end of file diff --git a/src/LogExpert/Config/ToolEntry.cs b/src/LogExpert/Config/ToolEntry.cs deleted file mode 100644 index 64ef026e..00000000 --- a/src/LogExpert/Config/ToolEntry.cs +++ /dev/null @@ -1,47 +0,0 @@ -using System; -using LogExpert.Classes; - -namespace LogExpert.Config -{ - [Serializable] - public class ToolEntry - { - #region Fields - - public string args = ""; - public string cmd = ""; - public string columnizerName = ""; - public string iconFile; - public int iconIndex; - public bool isFavourite; - public string name; - public bool sysout = false; - public string workingDir = ""; - - #endregion - - #region Public methods - - public override string ToString() - { - return Util.IsNull(this.name) ? this.cmd : this.name; - } - - public ToolEntry Clone() - { - ToolEntry clone = new(); - clone.cmd = this.cmd; - clone.args = this.args; - clone.name = this.name; - clone.sysout = this.sysout; - clone.columnizerName = this.columnizerName; - clone.isFavourite = this.isFavourite; - clone.iconFile = this.iconFile; - clone.iconIndex = this.iconIndex; - clone.workingDir = this.workingDir; - return clone; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Controls/KnobControl.Designer.cs b/src/LogExpert/Controls/KnobControl.Designer.cs deleted file mode 100644 index 4b897228..00000000 --- a/src/LogExpert/Controls/KnobControl.Designer.cs +++ /dev/null @@ -1,43 +0,0 @@ -namespace LogExpert.Controls -{ - partial class KnobControl - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Component Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.SuspendLayout(); - // - // KnobControl - // - this.Name = "KnobControl"; - this.Size = new System.Drawing.Size(21, 21); - this.ResumeLayout(false); - - } - - #endregion - } -} diff --git a/src/LogExpert/Controls/KnobControl.cs b/src/LogExpert/Controls/KnobControl.cs deleted file mode 100644 index 3a9846b1..00000000 --- a/src/LogExpert/Controls/KnobControl.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using NLog; - -namespace LogExpert.Controls -{ - public partial class KnobControl : UserControl - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - - private readonly StringFormat stringFormat = new(); - - private bool isShiftPressed = false; - - private int oldValue = 0; - private int startMouseY = 0; - private int value; - - #endregion - - #region cTor - - public KnobControl() - { - InitializeComponent(); - stringFormat.LineAlignment = StringAlignment.Far; - stringFormat.Alignment = StringAlignment.Center; - } - - #endregion - - #region Delegates - - public delegate void ValueChangedEventHandler(object sender, EventArgs e); - - #endregion - - #region Events - - public event ValueChangedEventHandler ValueChanged; - - #endregion - - #region Properties - - public int MinValue { get; set; } - - public int MaxValue { get; set; } - - public int Value - { - get { return this.value; } - set - { - this.value = value; - Refresh(); - } - } - - - public int Range - { - get { return this.MaxValue - this.MinValue; } - } - - public int DragSensitivity { get; set; } = 3; - - #endregion - - #region Overrides - - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - - Color foregroundColor = this.Enabled ? Color.Black : Color.Gray; - - Pen blackPen = new(foregroundColor, 1); - Pen greyPen = new(Color.Gray, 1); - - Rectangle rect = this.ClientRectangle; - int height = this.Font.Height + 3; - if (height > rect.Height) - { - height = rect.Height + 3; - } - rect.Inflate(-1, -height / 2); - rect.Offset(0, -height / 2); - e.Graphics.DrawEllipse(greyPen, rect); - - //rect = this.ClientRectangle; - rect.Inflate(-2, -2); - - float startAngle = 135.0F + 270F * ((float) this.value / (float) this.Range); - float sweepAngle = 0.1F; - e.Graphics.DrawPie(blackPen, rect, startAngle, sweepAngle); - - Brush brush = new SolidBrush(foregroundColor); - RectangleF rectF = new(0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height); - e.Graphics.DrawString("" + this.value, this.Font, brush, rectF, this.stringFormat); - - blackPen.Dispose(); - greyPen.Dispose(); - brush.Dispose(); - } - - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - if (e.Button == MouseButtons.Left) - { - Capture = true; - startMouseY = e.Y; - this.oldValue = this.Value; - } - if (e.Button == MouseButtons.Right) - { - Capture = false; - this.Value = this.oldValue; - this.Invalidate(); - } - } - - protected override void OnMouseUp(MouseEventArgs e) - { - base.OnMouseUp(e); - Capture = false; - this.oldValue = this.Value; - OnValueChanged(new EventArgs()); - } - - protected override void OnMouseMove(MouseEventArgs e) - { - base.OnMouseMove(e); - if (!Capture) - { - return; - } - - int sense = this.isShiftPressed ? this.DragSensitivity * 2 : this.DragSensitivity; - - int diff = this.startMouseY - e.Y; - _logger.Debug("KnobDiff: {0}", diff); - int range = this.MaxValue - this.MinValue; - this.value = this.oldValue + diff / sense; - if (this.value < this.MinValue) - { - this.value = this.MinValue; - } - if (this.value > this.MaxValue) - { - this.value = this.MaxValue; - } - this.Invalidate(); - } - - protected override void OnKeyDown(KeyEventArgs e) - { - this.isShiftPressed = e.Shift; - base.OnKeyDown(e); - } - - protected override void OnKeyUp(KeyEventArgs e) - { - this.isShiftPressed = e.Shift; - base.OnKeyUp(e); - } - - #endregion - - protected void OnValueChanged(EventArgs e) - { - if (ValueChanged != null) - { - ValueChanged(this, e); - } - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Controls/LogTabControl.cs b/src/LogExpert/Controls/LogTabControl.cs deleted file mode 100644 index 8f19e2c2..00000000 --- a/src/LogExpert/Controls/LogTabControl.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Controls -{ - internal class LogTabControl : TabControl - { - #region Fields - - private BufferedGraphics myBuffer; - - #endregion - - #region cTor - - public LogTabControl() - : base() - { - //SetStyle(ControlStyles.AllPaintingInWmPaint, true); - //SetStyle(ControlStyles.UserPaint, true); - //SetStyle(ControlStyles.DoubleBuffer, true); - } - - #endregion - - #region Overrides - - protected override void OnPaint(PaintEventArgs e) - { - BufferedGraphicsContext currentContext; - currentContext = BufferedGraphicsManager.Current; - myBuffer = currentContext.Allocate(this.CreateGraphics(), this.DisplayRectangle); - - PaintEventArgs args = new(myBuffer.Graphics, e.ClipRectangle); - - base.OnPaint(args); - - myBuffer.Render(e.Graphics); - myBuffer.Dispose(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Controls/LogTabPage.cs b/src/LogExpert/Controls/LogTabPage.cs index f679937f..9308bf8f 100644 --- a/src/LogExpert/Controls/LogTabPage.cs +++ b/src/LogExpert/Controls/LogTabPage.cs @@ -1,55 +1,57 @@ +using LogExpert.Core.Classes; +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; using System; using System.Threading; using System.Windows.Forms; -using LogExpert.Classes; -using LogExpert.Entities; namespace LogExpert.Controls { + //TODO: Not in use! internal class LogTabPage : TabPage { #region Fields private const int DIFF_MAX = 100; - private int diffSum = 0; - private readonly object diffSumLock = new(); - private readonly Thread ledThread; - private bool shouldStop = false; + private int _diffSum = 0; + private readonly object _diffSumLock = new(); + private readonly Thread _ledThread; + private bool _shouldStop = false; #endregion #region cTor - public LogTabPage(LogWindow.LogWindow logWindow, string title) - : base("MMi" + (title == null ? Util.GetNameFromPath(logWindow.FileName) : title)) + public LogTabPage(ILogWindow logWindow, string title) + : base("MMi" + (title ?? Util.GetNameFromPath(logWindow.FileName))) { - this.TabTitle = title; - if (this.TabTitle == null) + TabTitle = title; + TabTitle ??= Util.GetNameFromPath(logWindow.FileName); + LogWindow = logWindow; + LogWindow.FileSizeChanged += FileSizeChanged; + LogWindow.TailFollowed += TailFollowed; + _ledThread = new Thread(new ThreadStart(LedThreadProc)) { - this.TabTitle = Util.GetNameFromPath(logWindow.FileName); - } - this.LogWindow = logWindow; - this.LogWindow.FileSizeChanged += FileSizeChanged; - this.LogWindow.TailFollowed += TailFollowed; - this.ledThread = new Thread(new ThreadStart(this.LedThreadProc)); - this.ledThread.IsBackground = true; - this.ledThread.Start(); + IsBackground = true + }; + + _ledThread.Start(); } #endregion #region Properties - public LogWindow.LogWindow LogWindow { get; } + public ILogWindow LogWindow { get; } public int LineDiff { get { - lock (this.diffSumLock) + lock (_diffSumLock) { - return this.diffSum; + return _diffSum; } } } @@ -66,9 +68,9 @@ public int LineDiff public void Delete() { - this.shouldStop = true; - this.ledThread.Interrupt(); - this.ledThread.Join(); + _shouldStop = true; + _ledThread.Interrupt(); + _ledThread.Join(); } #endregion @@ -77,7 +79,7 @@ public void Delete() private void LedThreadProc() { - while (!this.shouldStop) + while (!_shouldStop) { try { @@ -87,19 +89,17 @@ private void LedThreadProc() { return; } - lock (this.diffSumLock) + lock (_diffSumLock) { - if (this.diffSum > 0) + if (_diffSum > 0) { - this.diffSum -= 10; - if (this.diffSum < 0) + _diffSum -= 10; + if (_diffSum < 0) { - this.diffSum = 0; - } - if (Parent != null) - { - Parent.Invalidate(); // redraw LEDs + _diffSum = 0; } + + Parent?.Invalidate(); // redraw LEDs } } } @@ -117,12 +117,12 @@ private void FileSizeChanged(object sender, LogEventArgs e) diff = DIFF_MAX; return; } - lock (this.diffSumLock) + lock (_diffSumLock) { - this.diffSum = this.diffSum + diff; - if (this.diffSum > DIFF_MAX) + _diffSum += diff; + if (_diffSum > DIFF_MAX) { - this.diffSum = DIFF_MAX; + _diffSum = DIFF_MAX; } } Dirty = true; @@ -131,7 +131,7 @@ private void FileSizeChanged(object sender, LogEventArgs e) private void TailFollowed(object sender, EventArgs e) { - if (this.IsActiveTab) + if (IsActiveTab) { Dirty = false; Parent.Invalidate(); diff --git a/src/LogExpert/Controls/LogTabWindow/LogTabWindow.cs b/src/LogExpert/Controls/LogTabWindow/LogTabWindow.cs deleted file mode 100644 index fdac7b84..00000000 --- a/src/LogExpert/Controls/LogTabWindow/LogTabWindow.cs +++ /dev/null @@ -1,358 +0,0 @@ -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; -using LogExpert.Extensions.Forms; -using LogExpert.Interface; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Reflection; -using System.Text; -using System.Threading; -using System.Windows.Forms; -//using System.Linq; - -namespace LogExpert.Controls.LogTabWindow -{ - internal partial class LogTabWindow : Form - { - #region Fields - - private const int MAX_COLUMNIZER_HISTORY = 40; - private const int MAX_COLOR_HISTORY = 40; - private const int DIFF_MAX = 100; - private const int MAX_FILE_HISTORY = 10; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - private readonly Icon _deadIcon; - - private readonly Color _defaultTabColor = Color.FromArgb(255, 192, 192, 192); - private readonly Brush _dirtyLedBrush; - - private readonly int _instanceNumber; - private readonly Brush[] _ledBrushes = new Brush[5]; - private readonly Icon[,,,] _ledIcons = new Icon[6, 2, 4, 2]; - - private readonly Rectangle[] _leds = new Rectangle[5]; - - private readonly IList _logWindowList = new List(); - private readonly Brush _offLedBrush; - private readonly bool _showInstanceNumbers; - - private readonly string[] _startupFileNames; - - private readonly EventWaitHandle _statusLineEventHandle = new AutoResetEvent(false); - private readonly EventWaitHandle _statusLineEventWakeupHandle = new ManualResetEvent(false); - private readonly Brush _syncLedBrush; - private readonly StringFormat _tabStringFormat = new(); - private readonly Brush[] _tailLedBrush = new Brush[3]; - - private BookmarkWindow _bookmarkWindow; - - private LogWindow.LogWindow _currentLogWindow; - private bool _firstBookmarkWindowShow = true; - - private Thread _ledThread; - - //Settings settings; - - private bool _shouldStop; - - private bool _skipEvents; - - private bool _wasMaximized; - - #endregion - - #region cTor - - public LogTabWindow(string[] fileNames, int instanceNumber, bool showInstanceNumbers) - { - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - InitializeComponent(); - - //Fix MainMenu and externalToolsToolStrip.Location, if the location has unintentionally been changed in the designer - mainMenuStrip.Location = new Point(0, 0); - externalToolsToolStrip.Location = new Point(0, 54); - - ChangeTheme(Controls); - - _startupFileNames = fileNames; - _instanceNumber = instanceNumber; - _showInstanceNumbers = showInstanceNumbers; - - Load += OnLogTabWindowLoad; - - ConfigManager.Instance.ConfigChanged += OnConfigChanged; - HilightGroupList = ConfigManager.Settings.hilightGroupList; - - Rectangle led = new(0, 0, 8, 2); - - for (int i = 0; i < _leds.Length; ++i) - { - _leds[i] = led; - led.Offset(0, led.Height + 0); - } - - int grayAlpha = 50; - - _ledBrushes[0] = new SolidBrush(Color.FromArgb(255, 220, 0, 0)); - _ledBrushes[1] = new SolidBrush(Color.FromArgb(255, 220, 220, 0)); - _ledBrushes[2] = new SolidBrush(Color.FromArgb(255, 0, 220, 0)); - _ledBrushes[3] = new SolidBrush(Color.FromArgb(255, 0, 220, 0)); - _ledBrushes[4] = new SolidBrush(Color.FromArgb(255, 0, 220, 0)); - - _offLedBrush = new SolidBrush(Color.FromArgb(grayAlpha, 160, 160, 160)); - - _dirtyLedBrush = new SolidBrush(Color.FromArgb(255, 220, 0, 00)); - - _tailLedBrush[0] = new SolidBrush(Color.FromArgb(255, 50, 100, 250)); // Follow tail: blue-ish - _tailLedBrush[1] = new SolidBrush(Color.FromArgb(grayAlpha, 160, 160, 160)); // Don't follow tail: gray - _tailLedBrush[2] = new SolidBrush(Color.FromArgb(255, 220, 220, 0)); // Stop follow tail (trigger): yellow-ish - - _syncLedBrush = new SolidBrush(Color.FromArgb(255, 250, 145, 30)); - - CreateIcons(); - - _tabStringFormat.LineAlignment = StringAlignment.Center; - _tabStringFormat.Alignment = StringAlignment.Near; - - ToolStripControlHost host = new(checkBoxFollowTail); - - host.Padding = new Padding(20, 0, 0, 0); - host.BackColor = Color.FromKnownColor(KnownColor.Transparent); - - int index = buttonToolStrip.Items.IndexOfKey("toolStripButtonTail"); - - toolStripEncodingASCIIItem.Text = Encoding.ASCII.HeaderName; - toolStripEncodingANSIItem.Text = Encoding.Default.HeaderName; - toolStripEncodingISO88591Item.Text = Encoding.GetEncoding("iso-8859-1").HeaderName; - toolStripEncodingUTF8Item.Text = Encoding.UTF8.HeaderName; - toolStripEncodingUTF16Item.Text = Encoding.Unicode.HeaderName; - - if (index != -1) - { - buttonToolStrip.Items.RemoveAt(index); - buttonToolStrip.Items.Insert(index, host); - } - - dragControlDateTime.Visible = false; - loadProgessBar.Visible = false; - - // get a reference to the current assembly - Assembly a = Assembly.GetExecutingAssembly(); - - // get a list of resource names from the manifest - string[] resNames = a.GetManifestResourceNames(); - - Bitmap bmp = Properties.Resources.Deceased; - _deadIcon = Icon.FromHandle(bmp.GetHicon()); - bmp.Dispose(); - Closing += OnLogTabWindowClosing; - - InitToolWindows(); - } - - #endregion - - #region ColorTheme - public void ChangeTheme(Control.ControlCollection container) - { - ColorMode.LoadColorMode(); - ColorMode.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.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = ColorMode.TabsBackgroundStripColor; - dockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = ColorMode.TabsBackgroundStripColor; - - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = ColorMode.TabsBackgroundStripColor; - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = ColorMode.TabsBackgroundStripColor; - - // Tabs - dockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = ColorMode.ActiveTabColor; - dockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = ColorMode.ActiveTabColor; - dockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor = ColorMode.ForeColor; - - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = ColorMode.ActiveTabColor; - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = ColorMode.ActiveTabColor; - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor = ColorMode.ForeColor; - - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = ColorMode.InactiveTabColor; - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = ColorMode.InactiveTabColor; - dockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor = ColorMode.ForeColor; - #endregion Tabs - } - #endregion - - #region Delegates - - private delegate void AddFileTabsDelegate(string[] fileNames); - - private delegate void ExceptionFx(); - - private delegate void FileNotFoundDelegate(LogWindow.LogWindow logWin); - - private delegate void FileRespawnedDelegate(LogWindow.LogWindow logWin); - - public delegate void HighlightSettingsChangedEventHandler(object sender, EventArgs e); - - private delegate void LoadMultiFilesDelegate(string[] fileName, EncodingOptions encodingOptions); - - private delegate void SetColumnizerFx(ILogLineColumnizer columnizer); - - private delegate void SetTabIconDelegate(LogWindow.LogWindow logWindow, Icon icon); - - #endregion - - #region Events - - public event HighlightSettingsChangedEventHandler HighlightSettingsChanged; - - #endregion - - #region Properties - - public LogWindow.LogWindow CurrentLogWindow - { - get => _currentLogWindow; - set => ChangeCurrentLogWindow(value); - } - - public SearchParams SearchParams { get; private set; } = new SearchParams(); - - public Preferences Preferences => ConfigManager.Settings.Preferences; - - public List HilightGroupList { get; private set; } = []; - - //public Settings Settings - //{ - // get { return ConfigManager.Settings; } - //} - - public ILogExpertProxy LogExpertProxy { get; set; } - - internal static StaticLogTabWindowData StaticData { get; set; } = new StaticLogTabWindowData(); - - #endregion - - #region Internals - - internal HilightGroup FindHighlightGroup(string groupName) - { - lock (HilightGroupList) - { - foreach (HilightGroup group in HilightGroupList) - { - if (group.GroupName.Equals(groupName)) - { - return group; - } - } - return null; - } - } - - #endregion - - private class LogWindowData - { - #region Fields - - // public MdiTabControl.TabPage tabPage; - public Color color = Color.FromKnownColor(KnownColor.Gray); - - public int diffSum; - public bool dirty; - public int syncMode; // 0 = off, 1 = timeSynced - public int tailState; // tailState: 0,1,2 = on/off/off by Trigger - public ToolTip toolTip; - - #endregion - } - - // Data shared over all LogTabWindow instances - internal class StaticLogTabWindowData - { - #region Properties - - public LogTabWindow CurrentLockedMainWindow { get; set; } - - #endregion - } - } -} diff --git a/src/LogExpert/Controls/LogTabWindow/LogTabWindowEventHandlers.cs b/src/LogExpert/Controls/LogTabWindow/LogTabWindowEventHandlers.cs deleted file mode 100644 index a8cc552b..00000000 --- a/src/LogExpert/Controls/LogTabWindow/LogTabWindowEventHandlers.cs +++ /dev/null @@ -1,1019 +0,0 @@ -using LogExpert.Classes; -using LogExpert.Classes.Persister; -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.Text; -using System.Threading; -using System.Windows.Forms; - -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.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) - { - List tmpList = ObjectClone.Clone(ConfigManager.Settings.lastOpenFilesList); - - foreach (string name in tmpList) - { - if (string.IsNullOrEmpty(name) == false) - { - AddFileTab(name, false, null, false, null); - } - } - } - if (_startupFileNames != null) - { - LoadFiles(_startupFileNames, false); - } - _ledThread = new Thread(LedThreadProc); - _ledThread.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 = new List(); - ConfigManager.Settings.alwaysOnTop = TopMost && ConfigManager.Settings.Preferences.allowOnlyOneInstance; - SaveLastOpenFilesList(); - - foreach (LogWindow.LogWindow logWindow in _logWindowList) - { - deleteLogWindowList.Add(logWindow); - } - - foreach (LogWindow.LogWindow logWindow in deleteLogWindowList) - { - 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) - { - LogWindow.LogWindow 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.Instance.RegisteredColumnizers, CurrentLogWindow.CurrentColumnizer, CurrentLogWindow.ColumnizerCallbackObject); - form.Owner = this; - form.TopMost = TopMost; - DialogResult res = form.ShowDialog(); - - if (res == DialogResult.OK) - { - if (form.ApplyToAll) - { - lock (_logWindowList) - { - foreach (LogWindow.LogWindow 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 (LogWindow.LogWindow 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); - DialogResult res = dlg.ShowDialog(); - if (res == DialogResult.OK) - { - int 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 - string[] formats = e.Data.GetFormats(); - string s = "Dragging something over LogExpert. Formats: "; - foreach (string format in formats) - { - s += format; - s += " , "; - } - s = s.Substring(0, s.Length - 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 - string[] formats = e.Data.GetFormats(); - string s = "Dropped formats: "; - foreach (string format in formats) - { - s += format; - s += " , "; - } - s = s[..^3]; - _logger.Debug(s); -#endif - - if (e.Data.GetDataPresent(DataFormats.FileDrop)) - { - object o = e.Data.GetData(DataFormats.FileDrop); - if (o is string[] names) - { - LoadFiles(names, (e.KeyState & 4) == 4); // (shift pressed?) - e.Effect = DragDropEffects.Copy; - } - } - } - - 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); - } - } - - private void OnAboutToolStripMenuItemClick(object sender, EventArgs e) - { - AboutBox aboutBox = new(); - aboutBox.TopMost = TopMost; - aboutBox.ShowDialog(); - } - - private void OnFilterToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ToggleFilterPanel(); - } - - private void OnMultiFileToolStripMenuItemClick(object sender, EventArgs e) - { - ToggleMultiFile(); - fileToolStripMenuItem.HideDropDown(); - } - - 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(); - } - - 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); - } - } - - private void OnAlwaysOnTopToolStripMenuItemClick(object sender, EventArgs e) - { - TopMost = alwaysOnTopToolStripMenuItem.Checked; - } - - private void OnFileSizeChanged(object sender, LogEventArgs e) - { - if (sender.GetType().IsAssignableFrom(typeof(LogWindow.LogWindow))) - { - int 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; - } - Icon 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 (LogWindow.LogWindow logWindow in _logWindowList) - { - if (logWindow != e.LogWindow) - { - logWindow.HandleChangedFilterList(); - } - } - } - ConfigManager.Save(SettingsFlags.FilterList); - } - - private void OnLogWindowCurrentHighlightGroupChanged(object sender, CurrentHighlightGroupChangedEventArgs e) - { - OnHighlightSettingsChanged(); - ConfigManager.Settings.hilightGroupList = HilightGroupList; - 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) - { - LogWindowData data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; - data.dirty = false; - Icon icon = GetIcon(data.diffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); - } - } - } - - private void OnLogWindowSyncModeChanged(object sender, SyncModeEventArgs e) - { - if (!Disposing) - { - LogWindowData data = ((LogWindow.LogWindow)sender).Tag as LogWindowData; - data.syncMode = e.IsTimeSynced ? 1 : 0; - Icon icon = GetIcon(data.diffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), (LogWindow.LogWindow)sender, icon); - } - else - { - _logger.Warn("Received SyncModeChanged event while disposing. Event ignored."); - } - } - - private void OnToggleBookmarkToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ToggleBookmark(); - } - - private void OnJumpToNextToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.JumpNextBookmark(); - } - - private void OnJumpToPrevToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.JumpPrevBookmark(); - } - - private void OnASCIIToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.ASCII); - } - - private void OnANSIToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.Default); - } - - private void OnUTF8ToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(new UTF8Encoding(false)); - } - - private void OnUTF16ToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.Unicode); - } - - private void OnISO88591ToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ChangeEncoding(Encoding.GetEncoding("iso-8859-1")); - } - - private void OnReloadToolStripMenuItemClick(object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - LogWindowData data = CurrentLogWindow.Tag as LogWindowData; - Icon icon = GetIcon(0, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), CurrentLogWindow, icon); - CurrentLogWindow.Reload(); - } - } - - private void OnSettingsToolStripMenuItemClick(object sender, EventArgs e) - { - OpenSettings(0); - } - - private void OnDateTimeDragControlValueDragged(object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - //this.CurrentLogWindow.ScrollToTimestamp(this.dateTimeDragControl.DateTime); - } - } - - private void OnDateTimeDragControlValueChanged(object sender, EventArgs e) - { - CurrentLogWindow?.ScrollToTimestamp(dragControlDateTime.DateTime, true, true); - } - - private void OnLogTabWindowDeactivate(object sender, EventArgs e) - { - CurrentLogWindow?.AppFocusLost(); - } - - private void OnLogTabWindowActivated(object sender, EventArgs e) - { - CurrentLogWindow?.AppFocusGained(); - } - - 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); - } - } - - private void OnToolStripButtonOpenClick(object sender, EventArgs e) - { - OpenFileDialog(); - } - - private void OnToolStripButtonSearchClick(object sender, EventArgs e) - { - OpenSearchDialog(); - } - - private void OnToolStripButtonFilterClick(object sender, EventArgs e) - { - CurrentLogWindow?.ToggleFilterPanel(); - } - - private void OnToolStripButtonBookmarkClick(object sender, EventArgs e) - { - CurrentLogWindow?.ToggleBookmark(); - } - - private void OnToolStripButtonUpClick(object sender, EventArgs e) - { - CurrentLogWindow?.JumpPrevBookmark(); - } - - private void OnToolStripButtonDownClick(object sender, EventArgs e) - { - CurrentLogWindow?.JumpNextBookmark(); - } - - 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 (LogWindow.LogWindow logWin in _logWindowList) - { - logWin.ShowLineColumn(!ConfigManager.Settings.hideLineColumn); - } - } - _bookmarkWindow.LineColumnVisible = ConfigManager.Settings.hideLineColumn; - } - - // ================================================================== - // Tab context menu stuff - // ================================================================== - - private void OnCloseThisTabToolStripMenuItemClick(object sender, EventArgs e) - { - (dockPanel.ActiveContent as LogWindow.LogWindow).Close(); - } - - private void OnCloseOtherTabsToolStripMenuItemClick(object sender, EventArgs e) - { - IList closeList = new List(); - lock (_logWindowList) - { - foreach (DockContent content in dockPanel.Contents) - { - if (content != dockPanel.ActiveContent && content is LogWindow.LogWindow) - { - closeList.Add(content as Form); - } - } - } - foreach (Form form in closeList) - { - form.Close(); - } - } - - private void OnCloseAllTabsToolStripMenuItemClick(object sender, EventArgs e) - { - CloseAllTabs(); - } - - private void OnTabColorToolStripMenuItemClick(object sender, EventArgs e) - { - LogWindow.LogWindow logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; - - LogWindowData data = logWindow.Tag as LogWindowData; - - if (data == null) - { - return; - } - - ColorDialog dlg = new(); - dlg.Color = data.color; - if (dlg.ShowDialog() == DialogResult.OK) - { - data.color = dlg.Color; - SetTabColor(logWindow, data.color); - } - List delList = []; - - foreach (ColorEntry entry in ConfigManager.Settings.fileColors) - { - if (entry.FileName.ToLower().Equals(logWindow.FileName.ToLower())) - { - delList.Add(entry); - } - } - - foreach (ColorEntry 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); - } - } - - private void OnLogTabWindowSizeChanged(object sender, EventArgs e) - { - if (WindowState != FormWindowState.Minimized) - { - _wasMaximized = WindowState == FormWindowState.Maximized; - } - } - - private void OnSaveProjectToolStripMenuItemClick(object sender, EventArgs e) - { - SaveFileDialog dlg = new(); - dlg.DefaultExt = "lxj"; - dlg.Filter = @"LogExpert session (*.lxj)|*.lxj"; - - if (dlg.ShowDialog() == DialogResult.OK) - { - string fileName = dlg.FileName; - List fileNames = []; - - lock (_logWindowList) - { - foreach (DockContent content in dockPanel.Contents) - { - LogWindow.LogWindow logWindow = content as LogWindow.LogWindow; - string persistenceFileName = logWindow?.SavePersistenceData(true); - if (persistenceFileName != null) - { - fileNames.Add(persistenceFileName); - } - } - } - - ProjectData projectData = new(); - projectData.memberList = fileNames; - projectData.tabLayoutXml = SaveLayout(); - ProjectPersister.SaveProjectData(fileName, projectData); - } - } - - private void OnLoadProjectToolStripMenuItemClick(object sender, EventArgs e) - { - OpenFileDialog dlg = new(); - dlg.DefaultExt = "lxj"; - dlg.Filter = @"LogExpert sessions (*.lxj)|*.lxj"; - - if (dlg.ShowDialog() == DialogResult.OK) - { - string projectFileName = dlg.FileName; - LoadProject(projectFileName, true); - } - } - - private void OnToolStripButtonBubblesClick(object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - CurrentLogWindow.ShowBookmarkBubbles = toolStripButtonBubbles.Checked; - } - } - - private void OnCopyPathToClipboardToolStripMenuItemClick(object sender, EventArgs e) - { - LogWindow.LogWindow logWindow = dockPanel.ActiveContent as LogWindow.LogWindow; - Clipboard.SetText(logWindow.Title); - } - - private void OnFindInExplorerToolStripMenuItemClick(object sender, EventArgs e) - { - LogWindow.LogWindow 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 OnExportBookmarksToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ExportBookmarkList(); - } - - private void OnHighlightGroupsComboBoxDropDownClosed(object sender, EventArgs e) - { - ApplySelectedHighlightGroup(); - } - - private void OnHighlightGroupsComboBoxSelectedIndexChanged(object sender, EventArgs e) - { - ApplySelectedHighlightGroup(); - } - - 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); - } - } - - private void OnDumpLogBufferInfoToolStripMenuItemClick(object sender, EventArgs e) - { -#if DEBUG - CurrentLogWindow?.DumpBufferInfo(); -#endif - } - - 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(); - } - - private void OnToolsToolStripMenuItemDropDownItemClicked(object sender, ToolStripItemClickedEventArgs e) - { - if (e.ClickedItem.Tag is ToolEntry tag) - { - ToolButtonClick(tag); - } - } - - private void OnExternalToolsToolStripItemClicked(object sender, ToolStripItemClickedEventArgs e) - { - ToolButtonClick(e.ClickedItem.Tag as ToolEntry); - } - - 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); - thread.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; - } - - private void OnDisableWordHighlightModeToolStripMenuItemClick(object sender, EventArgs e) - { - DebugOptions.disableWordHighlight = disableWordHighlightModeToolStripMenuItem.Checked; - CurrentLogWindow?.RefreshAllGrids(); - } - - private void OnMultiFileMaskToolStripMenuItemClick(object sender, EventArgs e) - { - CurrentLogWindow?.ChangeMultifileMask(); - } - - private void OnMultiFileEnabledStripMenuItemClick(object sender, EventArgs e) - { - ToggleMultiFile(); - } - - private void OnLockInstanceToolStripMenuItemClick(object sender, EventArgs e) - { - StaticData.CurrentLockedMainWindow = lockInstanceToolStripMenuItem.Checked ? null : this; - } - - private void OnOptionToolStripMenuItemDropDownOpening(object sender, EventArgs e) - { - lockInstanceToolStripMenuItem.Enabled = !ConfigManager.Settings.Preferences.allowOnlyOneInstance; - lockInstanceToolStripMenuItem.Checked = StaticData.CurrentLockedMainWindow == this; - } - - private void OnFileToolStripMenuItemDropDownOpening(object sender, EventArgs e) - { - newFromClipboardToolStripMenuItem.Enabled = Clipboard.ContainsText(); - } - - private void OnNewFromClipboardToolStripMenuItemClick(object sender, EventArgs e) - { - PasteFromClipboard(); - } - - private void OnOpenURIToolStripMenuItemClick(object sender, EventArgs e) - { - OpenUriDialog dlg = new(); - dlg.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(new[] { dlg.Uri }, false); - } - } - } - - private void OnColumnFinderToolStripMenuItemClick(object sender, EventArgs e) - { - if (CurrentLogWindow != null && !_skipEvents) - { - CurrentLogWindow.ToggleColumnFinder(columnFinderToolStripMenuItem.Checked, true); - } - } - - private void OnDockPanelActiveContentChanged(object sender, EventArgs e) - { - if (dockPanel.ActiveContent is LogWindow.LogWindow window) - { - CurrentLogWindow = window; - CurrentLogWindow.LogWindowActivated(); - ConnectToolWindows(CurrentLogWindow); - } - } - - private void OnTabRenameToolStripMenuItemClick(object sender, EventArgs e) - { - if (CurrentLogWindow != null) - { - TabRenameDlg dlg = new(); - dlg.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/Controls/LogTabWindow/LogTabWindowPrivate.cs b/src/LogExpert/Controls/LogTabWindow/LogTabWindowPrivate.cs deleted file mode 100644 index c3cfac92..00000000 --- a/src/LogExpert/Controls/LogTabWindow/LogTabWindowPrivate.cs +++ /dev/null @@ -1,1329 +0,0 @@ -using LogExpert.Classes; -using LogExpert.Classes.Columnizer; -using LogExpert.Classes.Persister; -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Drawing; -using System.IO; -using System.Runtime.InteropServices; -using System.Security; -using System.Text; -using System.Threading; -using System.Windows.Forms; - -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.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. - /// - private void PasteFromClipboard() - { - if (Clipboard.ContainsText()) - { - string text = Clipboard.GetText(); - string 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(); - } - - string title = "Clipboard"; - LogWindow.LogWindow logWindow = AddTempFileTab(fileName, title); - LogWindowData data = logWindow.Tag as LogWindowData; - if (data != null) - { - SetTooltipText(logWindow, "Pasted on " + DateTime.Now); - } - } - } - - private void InitToolWindows() - { - InitBookmarkWindow(); - } - - private void DestroyToolWindows() - { - DestroyBookmarkWindow(); - } - - private void InitBookmarkWindow() - { - _bookmarkWindow = new BookmarkWindow(); - _bookmarkWindow.HideOnClose = true; - _bookmarkWindow.ShowHint = DockState.DockBottom; - _bookmarkWindow.PreferencesChanged(ConfigManager.Settings.Preferences, false, SettingsFlags.All); - _bookmarkWindow.VisibleChanged += OnBookmarkWindowVisibleChanged; - _firstBookmarkWindowShow = true; - } - - 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); - } - } - } - } - - 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("Encoding " + ConfigManager.Settings.Preferences.defaultEncoding + " is not a valid encoding"); - encodingOptions.DefaultEncoding = null; - } - } - } - - private void AddFileTabs(string[] fileNames) - { - foreach (string fileName in fileNames) - { - if (!string.IsNullOrEmpty(fileName)) - { - if (fileName.EndsWith(".lxj")) - { - LoadProject(fileName, false); - } - else - { - AddFileTab(fileName, false, null, false, null); - } - } - } - - Activate(); - } - - 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(); - data.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; - } - - 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; - - LogWindowData data = logWindow.Tag as LogWindowData; - //data.tabPage.MouseClick -= tabPage_MouseClick; - //data.tabPage.TabDoubleClick -= tabPage_TabDoubleClick; - //data.tabPage.ContextMenuStrip = null; - //data.tabPage = null; - } - - private void AddToFileHistory(string fileName) - { - bool FindName(string s) - { - return s.ToLower().Equals(fileName.ToLower()); - } - - int 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(); - } - - private LogWindow.LogWindow FindWindowForFile(string fileName) - { - lock (_logWindowList) - { - foreach (LogWindow.LogWindow logWindow in _logWindowList) - { - if (logWindow.FileName.ToLower().Equals(fileName.ToLower())) - { - 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")) - { - PersistenceData persistenceData = Persister.LoadOptionsOnly(fileName); - if (persistenceData == null) - { - return fileName; - } - - if (!string.IsNullOrEmpty(persistenceData.fileName)) - { - IFileSystemPlugin fs = 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 - string dir = Path.GetDirectoryName(fileName); - return Path.Combine(dir, persistenceData.fileName); - } - } - - return fileName; - } - - private void FillHistoryMenu() - { - ToolStripDropDown strip = new ToolStripDropDownMenu(); - - foreach (string file in ConfigManager.Settings.fileHistoryList) - { - ToolStripItem item = new ToolStripMenuItem(file); - strip.Items.Add(item); - } - - strip.ItemClicked += OnHistoryItemClicked; - strip.MouseUp += OnStripMouseUp; - lastUsedToolStripMenuItem.DropDown = strip; - } - - private void RemoveLogWindow(LogWindow.LogWindow logWindow) - { - lock (_logWindowList) - { - _logWindowList.Remove(logWindow); - } - - DisconnectEventHandlers(logWindow); - } - - private void RemoveAndDisposeLogWindow(LogWindow.LogWindow logWindow, bool dontAsk) - { - if (CurrentLogWindow == logWindow) - { - ChangeCurrentLogWindow(null); - } - - lock (_logWindowList) - { - _logWindowList.Remove(logWindow); - } - - logWindow.Close(dontAsk); - } - - private void ShowHighlightSettingsDialog() - { - HighlightDialog dlg = new() - { - KeywordActionList = PluginRegistry.Instance.RegisteredKeywordActions, - Owner = this, - TopMost = TopMost, - HighlightGroupList = HilightGroupList, - PreSelectedGroupName = groupsComboBoxHighlightGroups.Text - }; - - DialogResult res = dlg.ShowDialog(); - - if (res == DialogResult.OK) - { - HilightGroupList = dlg.HighlightGroupList; - FillHighlightComboBox(); - ConfigManager.Settings.hilightGroupList = HilightGroupList; - ConfigManager.Save(SettingsFlags.HighlightSettings); - OnHighlightSettingsChanged(); - } - } - - private void FillHighlightComboBox() - { - string currentGroupName = groupsComboBoxHighlightGroups.Text; - groupsComboBoxHighlightGroups.Items.Clear(); - foreach (HilightGroup group in HilightGroupList) - { - groupsComboBoxHighlightGroups.Items.Add(group.GroupName); - if (group.GroupName.Equals(currentGroupName)) - { - groupsComboBoxHighlightGroups.Text = group.GroupName; - } - } - } - - 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); - } - } - } - - 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; - } - - MultiFileOption option = ConfigManager.Settings.Preferences.multiFileOption; - if (option == MultiFileOption.Ask) - { - MultiLoadRequestDialog dlg = new(); - DialogResult res = dlg.ShowDialog(); - - if (res == DialogResult.Yes) - { - option = MultiFileOption.SingleFiles; - } - else if (res == DialogResult.No) - { - option = MultiFileOption.MultiFile; - } - else - { - return; - } - } - else - { - if (invertLogic) - { - if (option == MultiFileOption.SingleFiles) - { - option = MultiFileOption.MultiFile; - } - else - { - option = MultiFileOption.SingleFiles; - } - } - } - - if (option == MultiFileOption.SingleFiles) - { - AddFileTabs(names); - } - else - { - AddMultiFileTab(names); - } - } - - private void SetColumnizerHistoryEntry(string fileName, ILogLineColumnizer columnizer) - { - ColumnizerHistoryEntry 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 (ColumnizerHistoryEntry entry in ConfigManager.Settings.columnizerHistoryList) - { - if (entry.FileName.Equals(fileName)) - { - return entry; - } - } - - return null; - } - - private void ToggleMultiFile() - { - if (CurrentLogWindow != null) - { - CurrentLogWindow.SwitchMultiFile(!CurrentLogWindow.IsMultiFile); - multiFileToolStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; - multiFileEnabledStripMenuItem.Checked = CurrentLogWindow.IsMultiFile; - } - } - - private void ChangeCurrentLogWindow(LogWindow.LogWindow newLogWindow) - { - if (newLogWindow == _currentLogWindow) - { - return; // do nothing if wishing to set the same window - } - - LogWindow.LogWindow oldLogWindow = _currentLogWindow; - _currentLogWindow = newLogWindow; - string 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; - - if (newLogWindow.IsTempFile) - { - Text = titleName + @" - " + newLogWindow.TempTitleName; - } - else - { - Text = 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); - } - - 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; - } - - 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)); - } - } - - 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(delegate { statusStrip.Refresh(); })); - } - else - { - statusStrip.Refresh(); - } - } - } - - // tailState: 0,1,2 = on/off/off by Trigger - // syncMode: 0 = normal (no), 1 = time synced - private Icon CreateLedIcon(int level, bool dirty, int tailState, int syncMode) - { - Rectangle 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); - Graphics gfx = Graphics.FromImage(bmp); - - int offsetFromTop = 4; - - for (int i = 0; i < _leds.Length; ++i) - { - Rectangle ledRect = _leds[i]; - ledRect.Offset(0, offsetFromTop); - - if (level >= _leds.Length - i) - { - gfx.FillRectangle(_ledBrushes[i], ledRect); - } - else - { - gfx.FillRectangle(_offLedBrush, ledRect); - } - } - - int ledSize = 3; - int ledGap = 1; - Rectangle 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 - IntPtr iconHandle = bmp.GetHicon(); - Icon icon = Icon.FromHandle(iconHandle).Clone() as Icon; - Win32.DestroyIcon(iconHandle); - - gfx.Dispose(); - bmp.Dispose(); - return icon; - } - - private void CreateIcons() - { - for (int syncMode = 0; syncMode <= 1; syncMode++) // LED indicating time synced tabs - { - for (int tailMode = 0; tailMode < 4; tailMode++) - { - for (int i = 0; i < 6; ++i) - { - _ledIcons[i, 0, tailMode, syncMode] = CreateLedIcon(i, false, tailMode, syncMode); - } - - for (int i = 0; i < 6; ++i) - { - _ledIcons[i, 1, tailMode, syncMode] = CreateLedIcon(i, true, tailMode, syncMode); - } - } - } - } - - private void FileNotFound(LogWindow.LogWindow logWin) - { - LogWindowData data = logWin.Tag as LogWindowData; - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, _deadIcon); - dragControlDateTime.Visible = false; - } - - private void FileRespawned(LogWindow.LogWindow logWin) - { - LogWindowData data = logWin.Tag as LogWindowData; - Icon icon = GetIcon(0, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); - } - - private void ShowLedPeak(LogWindow.LogWindow logWin) - { - LogWindowData data = logWin.Tag as LogWindowData; - lock (data) - { - data.diffSum = DIFF_MAX; - } - - Icon icon = GetIcon(data.diffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWin, icon); - } - - private int GetLevelFromDiff(int diff) - { - if (diff > 60) - { - diff = 60; - } - - int level = diff / 10; - if (diff > 0 && level == 0) - { - level = 2; - } - else if (level == 0) - { - level = 1; - } - - return level - 1; - } - - private void LedThreadProc() - { - Thread.CurrentThread.Name = "LED Thread"; - while (!_shouldStop) - { - try - { - Thread.Sleep(200); - } - catch - { - return; - } - - lock (_logWindowList) - { - foreach (LogWindow.LogWindow logWindow in _logWindowList) - { - LogWindowData data = logWindow.Tag as LogWindowData; - if (data.diffSum > 0) - { - data.diffSum -= 10; - if (data.diffSum < 0) - { - data.diffSum = 0; - } - - Icon icon = GetIcon(data.diffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); - } - } - } - } - } - - 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) - { - Icon icon = - _ledIcons[ - GetLevelFromDiff(diff), data.dirty ? 1 : 0, Preferences.showTailState ? data.tailState : 3, - data.syncMode - ]; - return icon; - } - - 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; - } - - private void OpenSettings(int tabToOpen) - { - SettingsDialog dlg = new(ConfigManager.Settings.Preferences, this, tabToOpen); - dlg.TopMost = TopMost; - - if (DialogResult.OK == dlg.ShowDialog()) - { - ConfigManager.Settings.Preferences = dlg.Preferences; - ConfigManager.Save(SettingsFlags.Settings); - NotifyWindowsForChangedPrefs(SettingsFlags.Settings); - } - } - - private void NotifyWindowsForChangedPrefs(SettingsFlags flags) - { - _logger.Info("The preferences have changed"); - ApplySettings(ConfigManager.Settings, flags); - - lock (_logWindowList) - { - foreach (LogWindow.LogWindow logWindow in _logWindowList) - { - logWindow.PreferencesChanged(ConfigManager.Settings.Preferences, false, flags); - } - } - - _bookmarkWindow.PreferencesChanged(ConfigManager.Settings.Preferences, false, flags); - - HilightGroupList = ConfigManager.Settings.hilightGroupList; - if ((flags & SettingsFlags.HighlightSettings) == SettingsFlags.HighlightSettings) - { - OnHighlightSettingsChanged(); - } - } - - 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(); - } - } - - private void SetTabIcons(Preferences preferences) - { - _tailLedBrush[0] = new SolidBrush(preferences.showTailColor); - CreateIcons(); - lock (_logWindowList) - { - foreach (LogWindow.LogWindow logWindow in _logWindowList) - { - LogWindowData data = logWindow.Tag as LogWindowData; - Icon icon = GetIcon(data.diffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); - } - } - } - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - private static extern bool DestroyIcon(IntPtr handle); - - private void SetToolIcon(ToolEntry entry, ToolStripItem item) - { - Icon icon = Win32.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; - } - - DestroyIcon(icon.Handle); - icon.Dispose(); - } - - if (!string.IsNullOrEmpty(entry.cmd)) - { - item.ToolTipText = entry.name; - } - } - - private void ToolButtonClick(ToolEntry toolEntry) - { - if (string.IsNullOrEmpty(toolEntry.cmd)) - { - //TODO TabIndex => To Enum - OpenSettings(2); - return; - } - - if (CurrentLogWindow != null) - { - ILogLine line = CurrentLogWindow.GetCurrentLine(); - ILogFileInfo info = CurrentLogWindow.GetCurrentFileInfo(); - if (line != null && info != null) - { - ArgParser parser = new(toolEntry.args); - string argLine = parser.BuildArgs(line, CurrentLogWindow.GetRealLineNum() + 1, info, this); - if (argLine != null) - { - StartTool(toolEntry.cmd, argLine, toolEntry.sysout, toolEntry.columnizerName, - toolEntry.workingDir); - } - } - } - } - - 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) - { - ILogLineColumnizer columnizer = ColumnizerPicker.DecideColumnizerByName(columnizerName, - PluginRegistry.Instance.RegisteredColumnizers); - - _logger.Info("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); - - LogWindow.LogWindow 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("Starting external tool: {0} {1}", cmd, args); - - try - { - startInfo.UseShellExecute = false; - process.Start(); - } - catch (Exception e) - { - _logger.Error(e); - MessageBox.Show(e.Message); - } - } - } - - private void CloseAllTabs() - { - IList closeList = new List(); - lock (_logWindowList) - { - foreach (DockContent content in dockPanel.Contents) - { - if (content is LogWindow.LogWindow window) - { - closeList.Add(window); - } - } - } - - foreach (Form form in closeList) - { - form.Close(); - } - } - - 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) - // ); - } - - private void LoadProject(string projectFileName, bool restoreLayout) - { - ProjectData projectData = ProjectPersister.LoadProjectData(projectFileName); - bool 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 (string 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); - } - } - } - - private void ApplySelectedHighlightGroup() - { - string groupName = groupsComboBoxHighlightGroups.Text; - CurrentLogWindow?.SetCurrentHighlightGroup(groupName); - } - - 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(); - int num = 0; - externalToolsToolStrip.SuspendLayout(); - foreach (ToolEntry 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); - menuItem.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: {0:N0}", GC.GetTotalMemory(false)); - GC.Collect(); - _logger.Info("GC done. Used mem after: {0:N0}", GC.GetTotalMemory(true)); - } - - private void DumpGCInfo() - { - _logger.Info("-------- GC info -----------\r\nUsed mem: {0:N0}", GC.GetTotalMemory(false)); - for (int i = 0; i < GC.MaxGeneration; ++i) - { - _logger.Info("Generation {0} collect count: {1}", i, GC.CollectionCount(i)); - } - - _logger.Info("----------------------------"); - } - - 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); - string resultXml = r.ReadToEnd(); - - r.Close(); - - return resultXml; - } - - 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); - } - - private IDockContent DeserializeDockContent(string persistString) - { - if (persistString.Equals(WindowTypes.BookmarkWindow.ToString())) - { - return _bookmarkWindow; - } - - if (persistString.StartsWith(WindowTypes.LogWindow.ToString())) - { - string fileName = persistString.Substring(WindowTypes.LogWindow.ToString().Length + 1); - LogWindow.LogWindow win = FindWindowForFile(fileName); - if (win != null) - { - return win; - } - - _logger.Warn("Layout data contains non-existing LogWindow for {0}", fileName); - } - - return null; - } - - private void OnHighlightSettingsChanged() - { - HighlightSettingsChanged?.Invoke(this, EventArgs.Empty); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Controls/LogTabWindow/LogTabWindowPublic.cs b/src/LogExpert/Controls/LogTabWindow/LogTabWindowPublic.cs deleted file mode 100644 index ec5d385a..00000000 --- a/src/LogExpert/Controls/LogTabWindow/LogTabWindowPublic.cs +++ /dev/null @@ -1,357 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Runtime.InteropServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using System.Windows.Forms; -using LogExpert.Classes; -using LogExpert.Classes.Columnizer; -using LogExpert.Classes.Filter; -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.Controls.LogTabWindow -{ - internal partial class LogTabWindow - { - #region Public methods - - public LogWindow.LogWindow AddTempFileTab(string fileName, string title) - { - return AddFileTab(fileName, true, title, false, null); - } - - public LogWindow.LogWindow AddFilterTab(FilterPipe pipe, string title, ILogLineColumnizer preProcessColumnizer) - { - LogWindow.LogWindow 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; - LogWindowData data = logWin.Tag as LogWindowData; - data.toolTip = tip; - } - - return logWin; - } - - public LogWindow.LogWindow AddFileTabDeferred(string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer) - { - return AddFileTab(givenFileName, isTempFile, title, forcePersistenceLoading, preProcessColumnizer, true); - } - - public LogWindow.LogWindow AddFileTab(string givenFileName, bool isTempFile, string title, bool forcePersistenceLoading, ILogLineColumnizer preProcessColumnizer, bool doNotAddToDockPanel = false) - { - string logFileName = FindFilenameForSettings(givenFileName); - LogWindow.LogWindow 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); - - logWindow.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); - } - - LogWindowData data = logWindow.Tag as LogWindowData; - data.color = _defaultTabColor; - SetTabColor(logWindow, _defaultTabColor); - //data.tabPage.BorderColor = this.defaultTabBorderColor; - if (!isTempFile) - { - foreach (ColorEntry colorEntry in ConfigManager.Settings.fileColors) - { - if (colorEntry.FileName.ToLower().Equals(logFileName.ToLower())) - { - data.color = colorEntry.Color; - SetTabColor(logWindow, colorEntry.Color); - break; - } - } - } - - if (!isTempFile) - { - SetTooltipText(logWindow, logFileName); - } - - if (givenFileName.EndsWith(".lxp")) - { - logWindow.ForcedPersistenceFileName = givenFileName; - } - - // this.BeginInvoke(new LoadFileDelegate(logWindow.LoadFile), new object[] { logFileName, encoding }); - Task.Run(() => logWindow.LoadFile(logFileName, encodingOptions)); - return logWindow; - } - - public LogWindow.LogWindow AddMultiFileTab(string[] fileNames) - { - if (fileNames.Length < 1) - { - return null; - } - - LogWindow.LogWindow logWindow = new(this, fileNames[fileNames.Length - 1], false, false); - AddLogWindow(logWindow, fileNames[fileNames.Length - 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; - } - - public void LoadFiles(string[] fileNames) - { - Invoke(new AddFileTabsDelegate(AddFileTabs), [fileNames]); - } - - public void OpenSearchDialog() - { - if (CurrentLogWindow == null) - { - return; - } - - SearchDialog dlg = new(); - AddOwnedForm(dlg); - dlg.TopMost = TopMost; - SearchParams.historyList = ConfigManager.Settings.searchHistoryList; - dlg.SearchParams = SearchParams; - DialogResult 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) - { - ColumnizerHistoryEntry entry = FindColumnizerHistoryEntry(fileName); - if (entry != null) - { - foreach (ILogLineColumnizer columnizer in PluginRegistry.Instance.RegisteredColumnizers) - { - if (columnizer.GetName().Equals(entry.ColumnizerName)) - { - return columnizer; - } - } - - ConfigManager.Settings.columnizerHistoryList.Remove(entry); // no valid name -> remove entry - } - - return null; - } - - public void SwitchTab(bool shiftPressed) - { - int 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 (LogWindow.LogWindow logWindow in _logWindowList) - { - if (logWindow != senderWindow) - { - if (logWindow.ScrollToTimestamp(timestamp, false, false)) - { - ShowLedPeak(logWindow); - } - } - } - } - } - - public ILogLineColumnizer FindColumnizerByFileMask(string fileName) - { - foreach (ColumnizerMaskEntry entry in ConfigManager.Settings.Preferences.columnizerMaskList) - { - if (entry.mask != null) - { - try - { - if (Regex.IsMatch(fileName, entry.mask)) - { - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(entry.columnizerName, PluginRegistry.Instance.RegisteredColumnizers); - return columnizer; - } - } - catch (ArgumentException e) - { - _logger.Error(e, "RegEx-error while finding columnizer: "); - // occurs on invalid regex patterns - } - } - } - - return null; - } - - public HilightGroup FindHighlightGroupByFileMask(string fileName) - { - foreach (HighlightMaskEntry entry in ConfigManager.Settings.Preferences.highlightMaskList) - { - if (entry.mask != null) - { - try - { - if (Regex.IsMatch(fileName, entry.mask)) - { - HilightGroup 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(LogWindow.LogWindow logWindow) - { - logWindow.Activate(); - } - - public void SetForeground() - { - SetForegroundWindow(Handle); - if (WindowState == FormWindowState.Minimized) - { - if (_wasMaximized) - { - WindowState = FormWindowState.Maximized; - } - else - { - WindowState = FormWindowState.Normal; - } - } - } - - [DllImport("User32.dll")] - public static extern int SetForegroundWindow(IntPtr hWnd); - - // called from LogWindow when follow tail was changed - public void FollowTailChanged(LogWindow.LogWindow logWindow, bool isEnabled, bool offByTrigger) - { - LogWindowData data = logWindow.Tag as LogWindowData; - if (data == null) - { - return; - } - - if (isEnabled) - { - data.tailState = 0; - } - else - { - data.tailState = offByTrigger ? 2 : 1; - } - - if (Preferences.showTailState) - { - Icon icon = GetIcon(data.diffSum, data); - BeginInvoke(new SetTabIconDelegate(SetTabIcon), logWindow, icon); - } - } - - public void NotifySettingsChanged(object cookie, SettingsFlags flags) - { - if (cookie != this) - { - NotifyWindowsForChangedPrefs(flags); - } - } - - public IList GetListOfOpenFiles() - { - IList list = new List(); - lock (_logWindowList) - { - foreach (LogWindow.LogWindow logWindow in _logWindowList) - { - list.Add(new WindowFileEntry(logWindow)); - } - } - - return list; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Controls/LogWindow/LogWindow.cs b/src/LogExpert/Controls/LogWindow/LogWindow.cs deleted file mode 100644 index 7cb5c3ca..00000000 --- a/src/LogExpert/Controls/LogWindow/LogWindow.cs +++ /dev/null @@ -1,657 +0,0 @@ -using LogExpert.Classes; -using LogExpert.Classes.Bookmark; -using LogExpert.Classes.Filter; -using LogExpert.Classes.Highlight; -using LogExpert.Classes.ILogLineColumnizerCallback; -using LogExpert.Classes.Log; -using LogExpert.Classes.Persister; -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; -using LogExpert.Extensions.Forms; -using LogExpert.Interface; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Forms; - -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.Controls.LogWindow -{ - internal partial class LogWindow : DockContent, ILogPaintContext, ILogView - { - #region Fields - - private const int SPREAD_MAX = 99; - private const int PROGRESS_BAR_MODULO = 1000; - private const int FILTER_ADVANCED_SPLITTER_DISTANCE = 150; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - private readonly Image _advancedButtonImage; - - private readonly object _bookmarkLock = new(); - private readonly BookmarkDataProvider _bookmarkProvider = new(); - - private readonly IList _cancelHandlerList = new List(); - - private readonly object _currentColumnizerLock = new(); - - private readonly object _currentHighlightGroupLock = new(); - - private readonly EventWaitHandle _externaLoadingFinishedEvent = new ManualResetEvent(false); - - private readonly IList _filterPipeList = new List(); - private readonly Dictionary _freezeStateMap = []; - private readonly GuiStateArgs _guiStateArgs = new(); - - private readonly List _lineHashList = []; - - private readonly EventWaitHandle _loadingFinishedEvent = new ManualResetEvent(false); - - private readonly EventWaitHandle _logEventArgsEvent = new ManualResetEvent(false); - - private readonly List _logEventArgsList = []; - private readonly Task _logEventHandlerTask; - //private readonly Thread _logEventHandlerThread; - private readonly Image _panelCloseButtonImage; - - private readonly Image _panelOpenButtonImage; - private readonly LogTabWindow.LogTabWindow _parentLogTabWin; - - private readonly ProgressEventArgs _progressEventArgs = new(); - private readonly object _reloadLock = new(); - private readonly Image _searchButtonImage; - private readonly StatusLineEventArgs _statusEventArgs = new(); - - private readonly object _tempHighlightEntryListLock = new(); - - private readonly Task _timeShiftSyncTask; - private readonly CancellationTokenSource cts = new(); - - //private readonly Thread _timeShiftSyncThread; - private readonly EventWaitHandle _timeShiftSyncTimerEvent = new ManualResetEvent(false); - private readonly EventWaitHandle _timeShiftSyncWakeupEvent = new ManualResetEvent(false); - - private readonly TimeSpreadCalculator _timeSpreadCalc; - - private readonly object _timeSyncListLock = new(); - - private ColumnCache _columnCache = new(); - - private ILogLineColumnizer _currentColumnizer; - - //List currentHilightEntryList = new List(); - private HilightGroup _currentHighlightGroup = new(); - - private SearchParams _currentSearchParams; - - private string[] _fileNames; - private List _filterHitList = []; - private FilterParams _filterParams = new(); - private int _filterPipeNameCounter = 0; - private List _filterResultList = []; - - private EventWaitHandle _filterUpdateEvent = new ManualResetEvent(false); - - private ILogLineColumnizer _forcedColumnizer; - private ILogLineColumnizer _forcedColumnizerForLoading; - private bool _isDeadFile; - private bool _isErrorShowing; - private bool _isLoadError; - private bool _isLoading; - private bool _isMultiFile; - private bool _isSearching; - private bool _isTimestampDisplaySyncing; - private List _lastFilterLinesList = []; - - private int _lineHeight = 0; - - internal LogfileReader _logFileReader; - private MultiFileOptions _multiFileOptions = new(); - private bool _noSelectionUpdates; - private PatternArgs _patternArgs = new(); - private PatternWindow _patternWindow; - - private ReloadMemento _reloadMemento; - private int _reloadOverloadCounter = 0; - private SortedList _rowHeightList = []; - private int _selectedCol = 0; // set by context menu event for column headers only - private bool _shouldCallTimeSync; - private bool _shouldCancel; - private bool _shouldTimestampDisplaySyncingCancel; - private bool _showAdvanced; - private List _tempHighlightEntryList = []; - private int _timeShiftSyncLine = 0; - - private bool _waitingForClose; - - #endregion - - #region cTor - - public LogWindow(LogTabWindow.LogTabWindow parent, string fileName, bool isTempFile, bool forcePersistenceLoading) - { - SuspendLayout(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - InitializeComponent(); - - CreateDefaultViewStyle(); - - columnNamesLabel.Text = ""; // no filtering on columns by default - - _parentLogTabWin = parent; - IsTempFile = isTempFile; - //Thread.CurrentThread.Name = "LogWindowThread"; - ColumnizerCallbackObject = new ColumnizerCallback(this); - - FileName = fileName; - ForcePersistenceLoading = forcePersistenceLoading; - - dataGridView.CellValueNeeded += OnDataGridViewCellValueNeeded; - dataGridView.CellPainting += OnDataGridView_CellPainting; - - filterGridView.CellValueNeeded += OnFilterGridViewCellValueNeeded; - filterGridView.CellPainting += OnFilterGridViewCellPainting; - filterListBox.DrawMode = DrawMode.OwnerDrawVariable; - filterListBox.MeasureItem += MeasureItem; - - Closing += OnLogWindowClosing; - Disposed += OnLogWindowDisposed; - Load += OnLogWindowLoad; - - _timeSpreadCalc = new TimeSpreadCalculator(this); - timeSpreadingControl.TimeSpreadCalc = _timeSpreadCalc; - timeSpreadingControl.LineSelected += OnTimeSpreadingControlLineSelected; - tableLayoutPanel1.ColumnStyles[1].SizeType = SizeType.Absolute; - tableLayoutPanel1.ColumnStyles[1].Width = 20; - tableLayoutPanel1.ColumnStyles[0].SizeType = SizeType.Percent; - tableLayoutPanel1.ColumnStyles[0].Width = 100; - - _parentLogTabWin.HighlightSettingsChanged += OnParentHighlightSettingsChanged; - SetColumnizer(PluginRegistry.Instance.RegisteredColumnizers[0]); - - _patternArgs.maxMisses = 5; - _patternArgs.minWeight = 1; - _patternArgs.maxDiffInBlock = 5; - _patternArgs.fuzzy = 5; - - //InitPatternWindow(); - - //this.toolwinTabControl.TabPages.Add(this.patternWindow); - //this.toolwinTabControl.TabPages.Add(this.bookmarkWindow); - - _filterParams = new FilterParams(); - foreach (string item in ConfigManager.Settings.filterHistoryList) - { - filterComboBox.Items.Add(item); - } - - filterComboBox.DropDownHeight = filterComboBox.ItemHeight * ConfigManager.Settings.Preferences.maximumFilterEntriesDisplayed; - AutoResizeFilterBox(); - - filterRegexCheckBox.Checked = _filterParams.isRegex; - filterCaseSensitiveCheckBox.Checked = _filterParams.isCaseSensitive; - filterTailCheckBox.Checked = _filterParams.isFilterTail; - - splitContainerLogWindow.Panel2Collapsed = true; - advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; - - _timeShiftSyncTask = new Task(SyncTimestampDisplayWorker, cts.Token); - _timeShiftSyncTask.Start(); - //_timeShiftSyncThread = new Thread(SyncTimestampDisplayWorker); - //_timeShiftSyncThread.IsBackground = true; - //_timeShiftSyncThread.Start(); - - _logEventHandlerTask = new Task(LogEventWorker, cts.Token); - _logEventHandlerTask.Start(); - //_logEventHandlerThread = new Thread(LogEventWorker); - //_logEventHandlerThread.IsBackground = true; - //_logEventHandlerThread.Start(); - - //this.filterUpdateThread = new Thread(new ThreadStart(this.FilterUpdateWorker)); - //this.filterUpdateThread.Start(); - - _advancedButtonImage = advancedButton.Image; - _searchButtonImage = filterSearchButton.Image; - filterSearchButton.Image = null; - - dataGridView.EditModeMenuStrip = editModeContextMenuStrip; - markEditModeToolStripMenuItem.Enabled = true; - - _panelOpenButtonImage = Properties.Resources.Arrow_menu_open; - _panelCloseButtonImage = Properties.Resources.Arrow_menu_close; - - Settings settings = ConfigManager.Settings; - - if (settings.appBounds.Right > 0) - { - Bounds = settings.appBounds; - } - - _waitingForClose = false; - dataGridView.Enabled = false; - dataGridView.ColumnDividerDoubleClick += OnDataGridViewColumnDividerDoubleClick; - ShowAdvancedFilterPanel(false); - filterKnobBackSpread.MinValue = 0; - filterKnobBackSpread.MaxValue = SPREAD_MAX; - filterKnobBackSpread.ValueChanged += OnFilterKnobControlValueChanged; - filterKnobForeSpread.MinValue = 0; - filterKnobForeSpread.MaxValue = SPREAD_MAX; - filterKnobForeSpread.ValueChanged += OnFilterKnobControlValueChanged; - fuzzyKnobControl.MinValue = 0; - fuzzyKnobControl.MaxValue = 10; - //PreferencesChanged(settings.preferences, true); - AdjustHighlightSplitterWidth(); - ToggleHighlightPanel(false); // hidden - - _bookmarkProvider.BookmarkAdded += OnBookmarkProviderBookmarkAdded; - _bookmarkProvider.BookmarkRemoved += OnBookmarkProviderBookmarkRemoved; - _bookmarkProvider.AllBookmarksRemoved += OnBookmarkProviderAllBookmarksRemoved; - - ResumeLayout(); - - 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 - - // 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++) - { - var item = filterContextMenuStrip.Items[y]; - item.ForeColor = ColorMode.ForeColor; - item.BackColor = ColorMode.MenuBackgroundColor; - } - - #endregion DataGridView - - filterComboBox.BackColor = ColorMode.DockBackgroundColor; - } - - #endregion - - #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 FileSizeChangedEventHandler(object sender, LogEventArgs 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 - - #region Events - - public event FileSizeChangedEventHandler FileSizeChanged; - - public event ProgressBarEventHandler ProgressBarUpdate; - - public event StatusLineEventHandler StatusLineEvent; - - public event GuiStateEventHandler GuiStateUpdate; - - public event TailFollowedEventHandler TailFollowed; - - public event FileNotFoundEventHandler FileNotFound; - - public event FileRespawnedEventHandler FileRespawned; - - public event FilterListChangedEventHandler FilterListChanged; - - public event CurrentHighlightGroupChangedEventHandler CurrentHighlightGroupChanged; - - public event BookmarkAddedEventHandler BookmarkAdded; - - public event BookmarkRemovedEventHandler BookmarkRemoved; - - public event BookmarkTextChangedEventHandler BookmarkTextChanged; - - public event ColumnizerChangedEventHandler ColumnizerChanged; - - public event SyncModeChangedEventHandler SyncModeChanged; - - #endregion - - #region Properties - - public Color BookmarkColor { get; set; } = Color.FromArgb(165, 200, 225); - - public ILogLineColumnizer CurrentColumnizer - { - get => _currentColumnizer; - private set - { - lock (_currentColumnizerLock) - { - _currentColumnizer = value; - _logger.Debug($"Setting columnizer {_currentColumnizer.GetName()} "); - } - } - } - - public bool ShowBookmarkBubbles - { - get => _guiStateArgs.ShowBookmarkBubbles; - set - { - _guiStateArgs.ShowBookmarkBubbles = dataGridView.PaintWithOverlays = value; - dataGridView.Refresh(); - } - } - - public string FileName { get; private set; } - - public string SessionFileName { get; set; } = null; - - public bool IsMultiFile - { - get => _isMultiFile; - private set => _guiStateArgs.IsMultiFileActive = _isMultiFile = value; - } - - public bool IsTempFile { get; } - - public string TempTitleName { get; set; } = ""; - - internal FilterPipe FilterPipe { get; set; } = null; - - public string Title - { - get - { - if (IsTempFile) - { - return TempTitleName; - } - - return FileName; - } - } - - public ColumnizerCallback ColumnizerCallbackObject { get; } - - public bool ForcePersistenceLoading { get; set; } - - public string ForcedPersistenceFileName { get; set; } = null; - - public Preferences Preferences => ConfigManager.Settings.Preferences; - - public string GivenFileName { get; set; } = null; - - public TimeSyncList TimeSyncList { get; private set; } - - public bool IsTimeSynced => TimeSyncList != null; - - protected EncodingOptions EncodingOptions { get; set; } - - public IBookmarkData BookmarkData => _bookmarkProvider; - - public Font MonospacedFont { get; private set; } - - public Font NormalFont { get; private set; } - - public Font BoldFont { get; private set; } - - #endregion - - #region Public methods - - public ILogLine GetLogLine(int lineNum) - { - return _logFileReader.GetLogLine(lineNum); - } - - public Bookmark GetBookmarkForLine(int lineNum) - { - return _bookmarkProvider.GetBookmarkForLine(lineNum); - } - - #endregion - - #region Internals - - internal IColumnizedLogLine GetColumnsForLine(int lineNumber) - { - return _columnCache.GetColumnsForLine(_logFileReader, lineNumber, CurrentColumnizer, ColumnizerCallbackObject); - - //string line = this.logFileReader.GetLogLine(lineNumber); - //if (line != null) - //{ - // string[] cols; - // this.columnizerCallback.LineNum = lineNumber; - // cols = this.CurrentColumnizer.SplitLine(this.columnizerCallback, line); - // return cols; - //} - //else - //{ - // return null; - //} - } - - internal void RefreshAllGrids() - { - dataGridView.Refresh(); - filterGridView.Refresh(); - } - - internal void ChangeMultifileMask() - { - MultiFileMaskDialog dlg = new(this, FileName); - dlg.Owner = this; - dlg.MaxDays = _multiFileOptions.MaxDayTry; - dlg.FileNamePattern = _multiFileOptions.FormatPattern; - if (dlg.ShowDialog() == DialogResult.OK) - { - _multiFileOptions.FormatPattern = dlg.FileNamePattern; - _multiFileOptions.MaxDayTry = dlg.MaxDays; - if (IsMultiFile) - { - Reload(); - } - } - } - - internal void ToggleColumnFinder(bool show, bool setFocus) - { - _guiStateArgs.ColumnFinderVisible = show; - if (show) - { - columnComboBox.AutoCompleteMode = AutoCompleteMode.Suggest; - columnComboBox.AutoCompleteSource = AutoCompleteSource.CustomSource; - columnComboBox.AutoCompleteCustomSource = [.. CurrentColumnizer.GetColumnNames()]; - if (setFocus) - { - columnComboBox.Focus(); - } - } - else - { - dataGridView.Focus(); - } - - tableLayoutPanel1.RowStyles[0].Height = show ? 28 : 0; - } - - #endregion - - #region Overrides - - protected override string GetPersistString() - { - return "LogWindow#" + FileName; - } - - #endregion - - private void OnButtonSizeChanged(object sender, EventArgs e) - { - if (sender is Button button && button.Image != null) - { - button.ImageAlign = ContentAlignment.MiddleCenter; - button.Image = new Bitmap(button.Image, new Size(button.Size.Height, button.Size.Height)); - } - } - - // used for external wait fx WaitForLoadFinished() - - private delegate void SelectLineFx(int line, bool triggerSyncCall); - - private Action, List, List> FilterFxAction; - //private delegate void FilterFx(FilterParams filterParams, List filterResultLines, List lastFilterResultLines, List filterHitList); - - private delegate void UpdateProgressBarFx(int lineNum); - - private delegate void SetColumnizerFx(ILogLineColumnizer columnizer); - - private delegate void WriteFilterToTabFinishedFx(FilterPipe pipe, string namePrefix, PersistenceData persistenceData); - - private delegate void SetBookmarkFx(int lineNum, string comment); - - private delegate void FunctionWith1BoolParam(bool arg); - - private delegate void PatternStatisticFx(PatternArgs patternArgs); - - private delegate void ActionPluginExecuteFx(string keyword, string param, ILogExpertCallback callback, ILogLineColumnizer columnizer); - - private delegate void PositionAfterReloadFx(ReloadMemento reloadMemento); - - private delegate void AutoResizeColumnsFx(DataGridView gridView); - - private delegate bool BoolReturnDelegate(); - - // =================== ILogLineColumnizerCallback ============================ - -#if DEBUG - internal void DumpBufferInfo() - { - int currentLineNum = dataGridView.CurrentCellAddress.Y; - _logFileReader.LogBufferInfoForLine(currentLineNum); - } - - internal void DumpBufferDiagnostic() - { - _logFileReader.LogBufferDiagnostic(); - } -#endif - } -} \ No newline at end of file diff --git a/src/LogExpert/Controls/LogWindow/LogWindow.resx b/src/LogExpert/Controls/LogWindow/LogWindow.resx deleted file mode 100644 index df7aeccf..00000000 --- a/src/LogExpert/Controls/LogWindow/LogWindow.resx +++ /dev/null @@ -1,173 +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 - - - 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/Controls/LogWindow/LogWindowEventHandlers.cs b/src/LogExpert/Controls/LogWindow/LogWindowEventHandlers.cs deleted file mode 100644 index 4892ab3c..00000000 --- a/src/LogExpert/Controls/LogWindow/LogWindowEventHandlers.cs +++ /dev/null @@ -1,1630 +0,0 @@ -#region - -using LogExpert.Classes; -using LogExpert.Classes.Filter; -using LogExpert.Classes.Highlight; -using LogExpert.Classes.ILogLineColumnizerCallback; -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; -using LogExpert.Extensions; -using LogExpert.Interface; - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Windows.Forms; - -#endregion - -namespace LogExpert.Controls.LogWindow -{ - internal partial class LogWindow - { - 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(BackgroundProcessCancelHandler handler) - { - lock (_cancelHandlerList) - { - _cancelHandlerList.Add(handler); - } - } - - protected void OnDeRegisterCancelHandler(BackgroundProcessCancelHandler handler) - { - lock (_cancelHandlerList) - { - _cancelHandlerList.Remove(handler); - } - } - - private void OnLogWindowLoad(object sender, EventArgs e) - { - PreferencesChanged(_parentLogTabWin.Preferences, true, SettingsFlags.GuiOrColors); - } - - private void OnLogWindowDisposed(object sender, EventArgs e) - { - _waitingForClose = true; - _parentLogTabWin.HighlightSettingsChanged -= OnParentHighlightSettingsChanged; - _logFileReader?.DeleteAllContent(); - - FreeFromTimeSync(); - } - - private void OnLogFileReaderLoadingStarted(object sender, LoadFileEventArgs e) - { - Invoke(LoadingStarted, e); - } - - private void OnLogFileReaderFinishedLoading(object sender, EventArgs e) - { - //Thread.CurrentThread.Name = "FinishedLoading event thread"; - _logger.Info("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("Refreshing filter view because of reload."); - Invoke(new MethodInvoker(FilterSearch)); // call on proper thread - } - - HandleChangedFilterList(); - } - - _reloadMemento = null; - } - - private void OnLogFileReaderFileNotFound(object sender, EventArgs e) - { - if (!IsDisposed && !Disposing) - { - _logger.Info("Handling file not found event."); - _isDeadFile = true; - BeginInvoke(new MethodInvoker(LogfileDead)); - } - } - - private void OnLogFileReaderRespawned(object sender, EventArgs e) - { - BeginInvoke(new MethodInvoker(LogfileRespawned)); - } - - 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(); - } - - private void OnDataGridViewColumnDividerDoubleClick(object sender, DataGridViewColumnDividerDoubleClickEventArgs e) - { - e.Handled = true; - AutoResizeColumns(dataGridView); - } - - /** - * Event handler for the Load event from LogfileReader - */ - private void OnLogFileReaderLoadFile(object sender, LoadFileEventArgs e) - { - if (e.NewFile) - { - _logger.Info("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("Reloading invoked."); - } - else if (_isLoading) - { - BeginInvoke(UpdateProgress, e); - } - } - - private void OnFileSizeChanged(object sender, LogEventArgs e) - { - //OnFileSizeChanged(e); // now done in UpdateGrid() - _logger.Info("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(); - } - } - - private void OnDataGridViewCellValueNeeded(object sender, DataGridViewCellValueEventArgs e) - { - int 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 (int i = startCount; i < CurrentColumnizer.GetColumnCount(); i++) - { - var colName = CurrentColumnizer.GetColumnNames()[i]; - dataGridView.Columns.Add(PaintHelper.CreateTitleColumn(colName)); - } - } - } - - private void OnDataGridViewCellValuePushed(object sender, DataGridViewCellValueEventArgs e) - { - if (!CurrentColumnizer.IsTimeshiftImplemented()) - { - return; - } - - ILogLine line = _logFileReader.GetLogLine(e.RowIndex); - int offset = CurrentColumnizer.GetTimeOffset(); - CurrentColumnizer.SetTimeOffset(0); - ColumnizerCallbackObject.LineNum = e.RowIndex; - IColumnizedLogLine cols = CurrentColumnizer.SplitLine(ColumnizerCallbackObject, line); - CurrentColumnizer.SetTimeOffset(offset); - if (cols.ColumnValues.Length <= e.ColumnIndex - 2) - { - return; - } - - string oldValue = cols.ColumnValues[e.ColumnIndex - 2].FullValue; - string 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); - string span = timeSpan.ToString(); - int index = span.LastIndexOf('.'); - if (index > 0) - { - span = span.Substring(0, index + 4); - } - - SetTimeshiftValue(span); - SendGuiStateUpdate(); - } - - private void OnDataGridViewRowHeightInfoNeeded(object sender, DataGridViewRowHeightInfoNeededEventArgs e) - { - e.Height = GetRowHeight(e.RowIndex); - } - - 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); - } - - private void OnEditControlKeyUp(object sender, KeyEventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - private void OnEditControlKeyPress(object sender, KeyPressEventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - private void OnEditControlClick(object sender, EventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - private void OnEditControlKeyDown(object sender, KeyEventArgs e) - { - UpdateEditColumnDisplay((DataGridViewTextBoxEditingControl)sender); - } - - private void OnDataGridViewPaint(object sender, PaintEventArgs e) - { - if (ShowBookmarkBubbles) - { - AddBookmarkOverlays(); - } - } - - // ====================================================================================== - // Filter Grid stuff - // ====================================================================================== - - private void OnFilterSearchButtonClick(object sender, EventArgs e) - { - FilterSearch(); - } - - private void OnFilterGridViewCellPainting(object sender, DataGridViewCellPaintingEventArgs e) - { - DataGridView gridView = (DataGridView)sender; - - if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) - { - e.Handled = false; - return; - } - - int lineNum = _filterResultList[e.RowIndex]; - ILogLine line = _logFileReader.GetLogLineWithWait(lineNum).Result; - if (line != null) - { - HilightEntry entry = FindFirstNoWordMatchHilightEntry(line); - e.Graphics.SetClip(e.CellBounds); - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) - { - Color backColor = e.CellStyle.SelectionBackColor; - Brush brush; - if (gridView.Focused) - { - brush = new SolidBrush(e.CellStyle.SelectionBackColor); - } - else - { - Color color = Color.FromArgb(255, 170, 170, 170); - brush = new SolidBrush(color); - } - - e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); - } - else - { - Color 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.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); - Brush brush = new SolidBrush(BookmarkColor); - e.Graphics.FillRectangle(brush, r); - brush.Dispose(); - Bookmark bookmark = _bookmarkProvider.GetBookmarkForLine(lineNum); - if (bookmark.Text.Length > 0) - { - StringFormat format = new(); - format.LineAlignment = StringAlignment.Center; - format.Alignment = StringAlignment.Center; - Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - Font font = new("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(); - } - } - } - - e.Paint(e.CellBounds, DataGridViewPaintParts.Border); - e.Handled = true; - } - } - - private void OnFilterGridViewCellValueNeeded(object sender, DataGridViewCellValueEventArgs e) - { - if (e.RowIndex < 0 || e.ColumnIndex < 0 || _filterResultList.Count <= e.RowIndex) - { - e.Value = ""; - return; - } - - int lineNum = _filterResultList[e.RowIndex]; - e.Value = GetCellValue(lineNum, e.ColumnIndex); - } - - private void OnFilterGridViewRowHeightInfoNeeded(object sender, DataGridViewRowHeightInfoNeededEventArgs e) - { - e.Height = _lineHeight; - } - - private void OnFilterComboBoxKeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Enter) - { - FilterSearch(); - } - } - - private void OnFilterGridViewColumnDividerDoubleClick(object sender, - DataGridViewColumnDividerDoubleClickEventArgs e) - { - e.Handled = true; - AutoResizeColumnsFx fx = AutoResizeColumns; - BeginInvoke(fx, filterGridView); - } - - private void OnFilterGridViewCellDoubleClick(object sender, DataGridViewCellEventArgs e) - { - if (e.ColumnIndex == 0) - { - ToggleBookmark(); - return; - } - - if (filterGridView.CurrentRow != null && e.RowIndex >= 0) - { - int lineNum = _filterResultList[filterGridView.CurrentRow.Index]; - SelectAndEnsureVisible(lineNum, true); - } - } - - private void OnRangeCheckBoxCheckedChanged(object sender, EventArgs e) - { - filterRangeComboBox.Enabled = rangeCheckBox.Checked; - CheckForFilterDirty(); - } - - 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(); - } - } - - private void OnFilterGridViewKeyDown(object sender, KeyEventArgs e) - { - switch (e.KeyCode) - { - case Keys.Enter: - { - if (filterGridView.CurrentCellAddress.Y >= 0 && filterGridView.CurrentCellAddress.Y < _filterResultList.Count) - { - int 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; - } - } - - 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; - } - - private void OnDataGridViewPreviewKeyDown(object sender, PreviewKeyDownEventArgs e) - { - if (e.KeyCode == Keys.Tab && e.Control) - { - e.IsInputKey = true; - } - } - - private void OnDataGridViewCellContentDoubleClick(object sender, DataGridViewCellEventArgs e) - { - if (dataGridView.CurrentCell != null) - { - dataGridView.BeginEdit(false); - } - } - - private void OnSyncFilterCheckBoxCheckedChanged(object sender, EventArgs e) - { - if (syncFilterCheckBox.Checked) - { - SyncFilterGridPos(); - } - } - - private void OnDataGridViewLeave(object sender, EventArgs e) - { - InvalidateCurrentRow(dataGridView); - } - - private void OnDataGridViewEnter(object sender, EventArgs e) - { - InvalidateCurrentRow(dataGridView); - } - - private void OnFilterGridViewEnter(object sender, EventArgs e) - { - InvalidateCurrentRow(filterGridView); - } - - private void OnFilterGridViewLeave(object sender, EventArgs e) - { - InvalidateCurrentRow(filterGridView); - } - - 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(); - } - - private void OnSelectionChangedTriggerSignal(object sender, EventArgs e) - { - int selCount = 0; - try - { - _logger.Debug("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); - } - } - - private void OnFilterKnobControlValueChanged(object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - 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; - } - } - } - } - - private void OnAdvancedButtonClick(object sender, EventArgs e) - { - _showAdvanced = !_showAdvanced; - ShowAdvancedFilterPanel(_showAdvanced); - } - - private void OnFilterSplitContainerMouseDown(object sender, MouseEventArgs e) - { - ((SplitContainer)sender).IsSplitterFixed = true; - } - - private void OnFilterSplitContainerMouseUp(object sender, MouseEventArgs e) - { - ((SplitContainer)sender).IsSplitterFixed = false; - } - - private void OnFilterSplitContainerMouseMove(object sender, MouseEventArgs e) - { - SplitContainer 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; - } - } - } - - private void OnFilterSplitContainerMouseDoubleClick(object sender, MouseEventArgs e) - { - AutoResizeFilterBox(); - } - - #region Context Menu - - private void OnDataGridContextMenuStripOpening(object sender, CancelEventArgs e) - { - int lineNum = -1; - if (dataGridView.CurrentRow != null) - { - lineNum = dataGridView.CurrentRow.Index; - } - - if (lineNum == -1) - { - return; - } - - int 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 - int index = dataGridContextMenuStrip.Items.IndexOf(pluginSeparator); - - if (index > 0) - { - for (int i = index + 1; i < dataGridContextMenuStrip.Items.Count;) - { - dataGridContextMenuStrip.Items.RemoveAt(i); - } - } - - // Add plugin entries - bool isAdded = false; - if (PluginRegistry.Instance.RegisteredContextMenuPlugins.Count > 0) - { - //string line = this.logFileReader.GetLogLine(lineNum); - IList lines = GetSelectedContent(); - foreach (IContextMenuEntry entry in PluginRegistry.Instance.RegisteredContextMenuPlugins) - { - LogExpertCallback callback = new(this); - ContextMenuPluginEventArgs evArgs = new(entry, lines, CurrentColumnizer, callback); - EventHandler ev = OnHandlePluginContextMenu; - //MenuItem item = this.dataGridView.ContextMenu.MenuItems.Add(entry.GetMenuText(line, this.CurrentColumnizer, callback), ev); - string menuText = entry.GetMenuText(lines, CurrentColumnizer, callback); - if (menuText != null) - { - bool disabled = menuText.StartsWith('_'); - if (disabled) - { - menuText = menuText[1..]; - } - - ToolStripItem item = dataGridContextMenuStrip.Items.Add(menuText, null, ev); - item.Tag = evArgs; - 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()) - { - IList 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) - { - if (fileEntry.LogWindow != this) - { - ToolStripMenuItem 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; - } - - private void OnHandlePluginContextMenu(object sender, EventArgs args) - { - if (sender is ToolStripItem item) - { - ContextMenuPluginEventArgs menuArgs = item.Tag as ContextMenuPluginEventArgs; - menuArgs.Entry.MenuSelected(menuArgs.LogLines, menuArgs.Columnizer, menuArgs.Callback); - } - } - - private void OnHandleSyncContextMenu(object sender, EventArgs args) - { - if (sender is ToolStripItem item) - { - WindowFileEntry entry = item.Tag as WindowFileEntry; - - if (TimeSyncList != null && TimeSyncList.Contains(entry.LogWindow)) - { - FreeSlaveFromTimesync(entry.LogWindow); - } - else - //AddSlaveToTimesync(entry.LogWindow); - { - AddOtherWindowToTimesync(entry.LogWindow); - } - } - } - - private void OnCopyToolStripMenuItemClick(object sender, EventArgs e) - { - CopyMarkedLinesToClipboard(); - } - - private void OnCopyToTabToolStripMenuItemClick(object sender, EventArgs e) - { - CopyMarkedLinesToTab(); - } - - private void OnScrollAllTabsToTimestampToolStripMenuItemClick(object sender, EventArgs e) - { - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - int currentLine = dataGridView.CurrentCellAddress.Y; - if (currentLine > 0 && currentLine < dataGridView.RowCount) - { - int lineNum = currentLine; - DateTime timeStamp = GetTimestampForLine(ref lineNum, false); - if (timeStamp.Equals(DateTime.MinValue)) // means: invalid - { - return; - } - - _parentLogTabWin.ScrollAllTabsToTimestamp(timeStamp, this); - } - } - } - - private void OnLocateLineInOriginalFileToolStripMenuItemClick(object sender, EventArgs e) - { - if (dataGridView.CurrentRow != null && FilterPipe != null) - { - int 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(); - } - - private void OnMarkEditModeToolStripMenuItemClick(object sender, EventArgs e) - { - StartEditMode(); - } - - private void OnLogWindowSizeChanged(object sender, EventArgs e) - { - //AdjustMinimumGridWith(); - AdjustHighlightSplitterWidth(); - } - - #region BookMarkList - - 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(); - } - - 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 - - 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; - // } - //} - - private void OnFilterGridViewCellContextMenuStripNeeded(object sender, DataGridViewCellContextMenuStripNeededEventArgs e) - { - if (e.ContextMenuStrip == columnContextMenuStrip) - { - _selectedCol = e.ColumnIndex; - } - } - - private void OnColumnContextMenuStripOpening(object sender, CancelEventArgs e) - { - Control ctl = columnContextMenuStrip.SourceControl; - DataGridView gridView = ctl as DataGridView; - bool frozen = false; - if (_freezeStateMap.ContainsKey(ctl)) - { - frozen = _freezeStateMap[ctl]; - } - - freezeLeftColumnsUntilHereToolStripMenuItem.Checked = frozen; - - if (frozen) - { - freezeLeftColumnsUntilHereToolStripMenuItem.Text = "Frozen"; - } - else - { - if (ctl is DataGridView) - { - freezeLeftColumnsUntilHereToolStripMenuItem.Text = $"Freeze left columns until here ({gridView.Columns[_selectedCol].HeaderText})"; - } - } - - - DataGridViewColumn 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); - 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); - - moveLeftToolStripMenuItem.Enabled = colLeft != null && colLeft.Frozen == col.Frozen; - } - - DataGridViewColumn 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) - { - ToolStripMenuItem item = allColumnsToolStripMenuItem.DropDownItems.Add(column.HeaderText, null, ev) as ToolStripMenuItem; - item.Tag = column; - item.Enabled = !column.Frozen; - } - } - } - - private void OnHandleColumnItemContextMenu(object sender, EventArgs args) - { - if (sender is ToolStripItem item) - { - DataGridViewColumn column = item.Tag as DataGridViewColumn; - column.Visible = true; - column.DataGridView.FirstDisplayedScrollingColumnIndex = column.Index; - } - } - - private void OnFreezeLeftColumnsUntilHereToolStripMenuItemClick(object sender, EventArgs e) - { - Control ctl = columnContextMenuStrip.SourceControl; - bool frozen = false; - - if (_freezeStateMap.ContainsKey(ctl)) - { - frozen = _freezeStateMap[ctl]; - } - - frozen = !frozen; - _freezeStateMap[ctl] = frozen; - - DataGridViewColumn senderCol = sender as DataGridViewColumn; - if (ctl is DataGridView gridView) - { - ApplyFrozenState(gridView); - } - } - - private void OnMoveToLastColumnToolStripMenuItemClick(object sender, EventArgs e) - { - DataGridView gridView = columnContextMenuStrip.SourceControl as DataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; - if (col != null) - { - col.DisplayIndex = gridView.Columns.Count - 1; - } - } - - private void OnMoveLeftToolStripMenuItemClick(object sender, EventArgs e) - { - DataGridView gridView = columnContextMenuStrip.SourceControl as DataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; - if (col != null && col.DisplayIndex > 0) - { - col.DisplayIndex -= 1; - } - } - - private void OnMoveRightToolStripMenuItemClick(object sender, EventArgs e) - { - DataGridView gridView = columnContextMenuStrip.SourceControl as DataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; - if (col != null && col.DisplayIndex < gridView.Columns.Count - 1) - { - col.DisplayIndex = col.DisplayIndex + 1; - } - } - - private void OnHideColumnToolStripMenuItemClick(object sender, EventArgs e) - { - DataGridView gridView = columnContextMenuStrip.SourceControl as DataGridView; - DataGridViewColumn col = gridView.Columns[_selectedCol]; - col.Visible = false; - } - - private void OnRestoreColumnsToolStripMenuItemClick(object sender, EventArgs e) - { - DataGridView gridView = columnContextMenuStrip.SourceControl as DataGridView; - foreach (DataGridViewColumn col in gridView.Columns) - { - col.Visible = true; - } - } - - private void OnTimeSpreadingControlLineSelected(object sender, SelectLineEventArgs e) - { - SelectLine(e.Line, false, true); - } - - private void OnBookmarkCommentToolStripMenuItemClick(object sender, EventArgs e) - { - AddBookmarkAndEditComment(); - } - - private void OnHighlightSelectionInLogFileToolStripMenuItemClick(object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - var he = new HilightEntry() - { - 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(); - } - } - - private void OnHighlightSelectionInLogFilewordModeToolStripMenuItemClick(object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - HilightEntry 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(); - } - } - - private void OnEditModeCopyToolStripMenuItemClick(object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - if (Util.IsNull(ctl.SelectedText) == false) - { - Clipboard.SetText(ctl.SelectedText); - } - } - } - - private void OnRemoveAllToolStripMenuItemClick(object sender, EventArgs e) - { - RemoveTempHighlights(); - } - - private void OnMakePermanentToolStripMenuItemClick(object sender, EventArgs e) - { - lock (_tempHighlightEntryListLock) - { - lock (_currentHighlightGroupLock) - { - _currentHighlightGroup.HilightEntryList.AddRange(_tempHighlightEntryList); - RemoveTempHighlights(); - OnCurrentHighlightListChanged(); - } - } - } - - private void OnMarkCurrentFilterRangeToolStripMenuItemClick(object sender, EventArgs e) - { - MarkCurrentFilterRange(); - } - - private void OnFilterForSelectionToolStripMenuItemClick(object sender, EventArgs e) - { - if (dataGridView.EditingControl is DataGridViewTextBoxEditingControl ctl) - { - splitContainerLogWindow.Panel2Collapsed = false; - ResetFilterControls(); - FilterSearch(ctl.SelectedText); - } - } - - 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; - } - - private void OnDataGridViewCellDoubleClick(object sender, DataGridViewCellEventArgs e) - { - if (e.ColumnIndex == 0) - { - ToggleBookmark(); - } - } - - private void OnDataGridViewOverlayDoubleClicked(object sender, OverlayEventArgs e) - { - BookmarkComment(e.BookmarkOverlay.Bookmark); - } - - private void OnFilterRegexCheckBoxMouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - RegexHelperDialog dlg = new(); - dlg.Owner = this; - dlg.CaseSensitive = filterCaseSensitiveCheckBox.Checked; - dlg.Pattern = filterComboBox.Text; - DialogResult res = dlg.ShowDialog(); - - if (res == DialogResult.OK) - { - filterCaseSensitiveCheckBox.Checked = dlg.CaseSensitive; - filterComboBox.Text = dlg.Pattern; - } - } - } - - #endregion - - #region Filter-Highlight - - private void OnToggleHighlightPanelButtonClick(object sender, EventArgs e) - { - ToggleHighlightPanel(highlightSplitContainer.Panel2Collapsed); - } - - private void OnSaveFilterButtonClick(object sender, EventArgs e) - { - FilterParams newParams = _filterParams.CreateCopy(); - newParams.color = Color.FromKnownColor(KnownColor.Black); - ConfigManager.Settings.filterList.Add(newParams); - OnFilterListChanged(this); - } - - private void OnDeleteFilterButtonClick(object sender, EventArgs e) - { - int index = filterListBox.SelectedIndex; - if (index >= 0) - { - FilterParams filterParams = (FilterParams)filterListBox.Items[index]; - ConfigManager.Settings.filterList.Remove(filterParams); - OnFilterListChanged(this); - if (filterListBox.Items.Count > 0) - { - filterListBox.SelectedIndex = filterListBox.Items.Count - 1; - } - } - } - - private void OnFilterUpButtonClick(object sender, EventArgs e) - { - int i = filterListBox.SelectedIndex; - if (i > 0) - { - FilterParams filterParams = (FilterParams)filterListBox.Items[i]; - ConfigManager.Settings.filterList.RemoveAt(i); - i--; - ConfigManager.Settings.filterList.Insert(i, filterParams); - OnFilterListChanged(this); - filterListBox.SelectedIndex = i; - } - } - - private void OnFilterDownButtonClick(object sender, EventArgs e) - { - int i = filterListBox.SelectedIndex; - if (i < 0) - { - return; - } - - if (i < filterListBox.Items.Count - 1) - { - FilterParams filterParams = (FilterParams)filterListBox.Items[i]; - ConfigManager.Settings.filterList.RemoveAt(i); - i++; - ConfigManager.Settings.filterList.Insert(i, filterParams); - OnFilterListChanged(this); - filterListBox.SelectedIndex = i; - } - } - - private void OnFilterListBoxMouseDoubleClick(object sender, MouseEventArgs e) - { - if (filterListBox.SelectedIndex >= 0) - { - FilterParams filterParams = (FilterParams)filterListBox.Items[filterListBox.SelectedIndex]; - FilterParams newParams = filterParams.CreateCopy(); - //newParams.historyList = ConfigManager.Settings.filterHistoryList; - this._filterParams = newParams; - ReInitFilterParams(this._filterParams); - ApplyFilterParams(); - CheckForAdvancedButtonDirty(); - CheckForFilterDirty(); - filterSearchButton.Image = _searchButtonImage; - saveFilterButton.Enabled = false; - if (hideFilterListOnLoadCheckBox.Checked) - { - ToggleHighlightPanel(false); - } - - if (filterOnLoadCheckBox.Checked) - { - FilterSearch(); - } - } - } - - private void OnFilterListBoxDrawItem(object sender, DrawItemEventArgs e) - { - e.DrawBackground(); - if (e.Index >= 0) - { - FilterParams 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(); - } - } - - // Color for filter list entry - private void OnColorToolStripMenuItemClick(object sender, EventArgs e) - { - int i = filterListBox.SelectedIndex; - if (i < filterListBox.Items.Count && i >= 0) - { - FilterParams filterParams = (FilterParams)filterListBox.Items[i]; - ColorDialog dlg = new(); - dlg.CustomColors = new[] { filterParams.color.ToArgb() }; - dlg.Color = filterParams.color; - if (dlg.ShowDialog() == DialogResult.OK) - { - filterParams.color = dlg.Color; - filterListBox.Refresh(); - } - } - } - - private void OnFilterCaseSensitiveCheckBoxCheckedChanged(object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - private void OnFilterRegexCheckBoxCheckedChanged(object sender, EventArgs e) - { - fuzzyKnobControl.Enabled = !filterRegexCheckBox.Checked; - fuzzyLabel.Enabled = !filterRegexCheckBox.Checked; - CheckForFilterDirty(); - } - - private void OnInvertFilterCheckBoxCheckedChanged(object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - private void OnFilterRangeComboBoxTextChanged(object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - private void OnFuzzyKnobControlValueChanged(object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - private void OnFilterComboBoxTextChanged(object sender, EventArgs e) - { - CheckForFilterDirty(); - } - - private void OnSetBookmarksOnSelectedLinesToolStripMenuItemClick(object sender, EventArgs e) - { - SetBookmarksForSelectedFilterLines(); - } - - private void OnParentHighlightSettingsChanged(object sender, EventArgs e) - { - string groupName = _guiStateArgs.HighlightGroupName; - SetCurrentHighlightGroup(groupName); - } - - private void OnFilterOnLoadCheckBoxMouseClick(object sender, MouseEventArgs e) - { - HandleChangedFilterOnLoadSetting(); - } - - private void OnFilterOnLoadCheckBoxKeyPress(object sender, KeyPressEventArgs e) - { - HandleChangedFilterOnLoadSetting(); - } - - private void OnHideFilterListOnLoadCheckBoxMouseClick(object sender, MouseEventArgs e) - { - HandleChangedFilterOnLoadSetting(); - } - - private void OnFilterToTabToolStripMenuItemClick(object sender, EventArgs e) - { - FilterToTab(); - } - - private void OnTimeSyncListWindowRemoved(object sender, EventArgs e) - { - TimeSyncList 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(); - } - - private void OnSplitContainerSplitterMoved(object sender, SplitterEventArgs e) - { - advancedFilterSplitContainer.SplitterDistance = FILTER_ADVANCED_SPLITTER_DISTANCE; - } - - private void OnMarkFilterHitsInLogViewToolStripMenuItemClick(object sender, EventArgs e) - { - SearchParams p = new(); - p.searchText = _filterParams.searchText; - p.isRegex = _filterParams.isRegex; - p.isCaseSensitive = _filterParams.isCaseSensitive; - AddSearchHitHighlightEntry(p); - } - - private void OnColumnComboBoxSelectionChangeCommitted(object sender, EventArgs e) - { - SelectColumn(); - } - - private void OnColumnComboBoxKeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Enter) - { - SelectColumn(); - dataGridView.Focus(); - } - } - - 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; - } - } - - private void OnBookmarkProviderBookmarkRemoved(object sender, EventArgs e) - { - if (!_isLoading) - { - dataGridView.Refresh(); - filterGridView.Refresh(); - } - } - - 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(); - } - - private void OnDataGridViewRowUnshared(object sender, DataGridViewRowEventArgs e) - { - if (_logger.IsTraceEnabled) - { - _logger.Trace($"Row unshared line {e.Row.Cells[1].Value}"); - } - } - - #endregion - - #endregion - - #endregion - - private void MeasureItem(object sender, MeasureItemEventArgs e) - { - e.ItemHeight = filterListBox.Font.Height; - } - } -} diff --git a/src/LogExpert/Controls/LogWindow/LogWindowPrivate.cs b/src/LogExpert/Controls/LogWindow/LogWindowPrivate.cs deleted file mode 100644 index cfbb7b65..00000000 --- a/src/LogExpert/Controls/LogWindow/LogWindowPrivate.cs +++ /dev/null @@ -1,3743 +0,0 @@ -using LogExpert.Classes; -using LogExpert.Classes.Columnizer; -using LogExpert.Classes.Filter; -using LogExpert.Classes.Highlight; -using LogExpert.Classes.ILogLineColumnizerCallback; -using LogExpert.Classes.Persister; -using LogExpert.Config; -using LogExpert.Dialogs; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; -using LogExpert.Interface; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Globalization; -using System.IO; -using System.Linq; -//using System.Runtime.Remoting.Messaging; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using System.Windows.Forms; - -namespace LogExpert.Controls.LogWindow -{ - internal partial class LogWindow - { - #region Private Methods - - 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 - } - - private void UnRegisterLogFileReaderEvents() - { - if (_logFileReader != null) - { - _logFileReader.LoadFile -= OnLogFileReaderLoadFile; - _logFileReader.LoadingFinished -= OnLogFileReaderFinishedLoading; - _logFileReader.LoadingStarted -= OnLogFileReaderLoadingStarted; - _logFileReader.FileNotFound -= OnLogFileReaderFileNotFound; - _logFileReader.Respawned -= OnLogFileReaderRespawned; - _logFileReader.FileSizeChanged -= OnFileSizeChanged; - } - } - - 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; - 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; - dataGridViewCellStyleFilterGrid.WrapMode = DataGridViewTriState.False; - filterGridView.DefaultCellStyle = dataGridViewCellStyleFilterGrid; - } - - private bool LoadPersistenceOptions() - { - if (InvokeRequired) - { - return (bool)Invoke(new BoolReturnDelegate(LoadPersistenceOptions)); - } - - if (!Preferences.saveSessions && ForcedPersistenceFileName == null) - { - return false; - } - - try - { - PersistenceData persistenceData; - if (ForcedPersistenceFileName == null) - { - persistenceData = Persister.LoadPersistenceDataOptionsOnly(FileName, Preferences); - } - else - { - persistenceData = - Persister.LoadPersistenceDataOptionsOnlyFromFixedFile(ForcedPersistenceFileName); - } - - if (persistenceData == null) - { - _logger.Info($"No persistence data for {FileName} found."); - return false; - } - - IsMultiFile = persistenceData.multiFile; - _multiFileOptions = new MultiFileOptions(); - _multiFileOptions.FormatPattern = persistenceData.multiFilePattern; - _multiFileOptions.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("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; - } - } - - private void SetDefaultsFromPrefs() - { - filterTailCheckBox.Checked = Preferences.filterTail; - syncFilterCheckBox.Checked = Preferences.filterSync; - FollowTailChanged(Preferences.followTail, false); - _multiFileOptions = ObjectClone.Clone(Preferences.multiFileOptions); - } - - 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 - { - PersistenceData persistenceData; - - if (ForcedPersistenceFileName == null) - { - persistenceData = Persister.LoadPersistenceData(FileName, Preferences); - } - else - { - persistenceData = 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 {0} is outdated. It was discarded.", FileName); - LoadPersistenceOptions(); - return; - } - - _bookmarkProvider.BookmarkList = 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: "); - } - } - - 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 (FilterTabData data in persistenceData.filterTabDataList) - { - FilterParams persistFilterParams = data.filterParams; - ReInitFilterParams(persistFilterParams); - List filterResultList = []; - //List lastFilterResultList = new List(); - List filterHitList = []; - Filter(persistFilterParams, filterResultList, _lastFilterLinesList, filterHitList); - FilterPipe pipe = new(persistFilterParams.CreateCopy(), 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("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("EnterLoadFileStatus end"); - } - - 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; - } - } - - private void LogfileDead() - { - _logger.Info("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); - } - - private void LogfileRespawned() - { - _logger.Info("LogfileDead(): Reloading file because it has been respawned."); - _isDeadFile = false; - dataGridView.Enabled = true; - StatusLineText(""); - OnFileRespawned(EventArgs.Empty); - Reload(); - } - - private void SetGuiAfterLoading() - { - if (Text.Length == 0) - { - if (IsTempFile) - { - Text = TempTitleName; - } - else - { - Text = 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) - { - columnizer = ColumnizerPicker.CloneColumnizer(columnizer); - } - } - else - { - // Default Columnizers - columnizer = ColumnizerPicker.CloneColumnizer(ColumnizerPicker.FindColumnizer(FileName, _logFileReader)); - } - } - - 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(); - } - - Settings settings = ConfigManager.Settings; - ShowLineColumn(!settings.hideLineColumn); - } - - ShowTimeSpread(Preferences.showTimeSpread && CurrentColumnizer.IsTimeshiftImplemented()); - locateLineInOriginalFileToolStripMenuItem.Enabled = FilterPipe != null; - } - - private ILogLineColumnizer FindColumnizer() - { - ILogLineColumnizer columnizer; - if (Preferences.maskPrio) - { - columnizer = _parentLogTabWin.FindColumnizerByFileMask(Util.GetNameFromPath(FileName)) ?? _parentLogTabWin.GetColumnizerHistoryEntry(FileName); - } - else - { - columnizer = _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 = {0}", _reloadOverloadCounter); - if (_reloadOverloadCounter <= 1) - { - SavePersistenceData(false); - _loadingFinishedEvent.Reset(); - _externaLoadingFinishedEvent.Reset(); - Thread reloadFinishedThread = new(ReloadFinishedThreadFx); - reloadFinishedThread.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("Preventing reload because of recursive calls."); - } - - _reloadOverloadCounter--; - } - } - - private void ReloadFinishedThreadFx() - { - _logger.Info("Waiting for loading to be complete."); - _loadingFinishedEvent.WaitOne(); - _logger.Info("Refreshing filter view because of reload."); - Invoke(new MethodInvoker(FilterSearch)); - LoadFilterPipes(); - } - - private void UpdateProgress(LoadFileEventArgs e) - { - try - { - if (e.ReadPos >= e.FileSize) - { - //_logger.Warn("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("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(); - - PreferencesChanged(_parentLogTabWin.Preferences, true, SettingsFlags.All); - //LoadPersistenceData(); - } - - private void LogEventWorker() - { - Thread.CurrentThread.Name = "LogEventWorker"; - while (true) - { - _logger.Debug("Waiting for signal"); - _logEventArgsEvent.WaitOne(); - _logger.Debug("Wakeup signal received."); - while (true) - { - LogEventArgs e; - int lastLineCount = 0; - lock (_logEventArgsList) - { - _logger.Info("{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) - { - int oldRowCount = dataGridView.RowCount; - int 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) - { - int 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("UpdateGrid(): new RowCount={0}", dataGridView.RowCount); - - if (e.IsRollover) - { - // Multifile rollover - // keep selection and view range, if no follow tail mode - if (!_guiStateArgs.FollowTail) - { - int currentLineNum = dataGridView.CurrentCellAddress.Y; - currentLineNum -= e.RolloverOffset; - if (currentLineNum < 0) - { - currentLineNum = 0; - } - - _logger.Debug("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) - { - bool noLed = true; - bool suppressLed; - bool setBookmark; - bool stopTail; - string bookmarkComment; - - if (filterTailCheckBox.Checked || _filterPipeList.Count > 0) - { - int filterStart = e.PrevLineCount; - if (e.IsRollover) - { - ShiftFilterLines(e.RolloverOffset); - filterStart -= e.RolloverOffset; - } - - bool firstStopTail = true; - ColumnizerCallback callback = new(this); - bool filterLineAdded = false; - for (int i = filterStart; i < e.LineCount; ++i) - { - ILogLine line = _logFileReader.GetLogLine(i); - if (line == null) - { - return; - } - - if (filterTailCheckBox.Checked) - { - callback.LineNum = 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); - - IList 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) - { - bool 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 - { - bool firstStopTail = true; - int startLine = e.PrevLineCount; - if (e.IsRollover) - { - ShiftFilterLines(e.RolloverOffset); - startLine -= e.RolloverOffset; - } - - for (int i = startLine; i < e.LineCount; ++i) - { - ILogLine line = _logFileReader.GetLogLine(i); - if (line != null) - { - IList 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) - { - bool 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 (HilightEntry entry in matchingList) - { - if (entry.IsActionEntry && entry.ActionEntry.PluginName != null) - { - IKeywordAction plugin = - 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) - { - if (columnizer != null) - { - CurrentColumnizer = _forcedColumnizerForLoading = columnizer; - } - else - { - CurrentColumnizer = _forcedColumnizerForLoading = - ColumnizerPicker.FindColumnizer(FileName, _logFileReader); - } - } - - private void SetColumnizer(ILogLineColumnizer columnizer) - { - columnizer = ColumnizerPicker.FindReplacementForAutoColumnizer(FileName, _logFileReader, columnizer); - - int 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("SetColumnizerInternal(): {0}", columnizer.GetName()); - - ILogLineColumnizer oldColumnizer = CurrentColumnizer; - bool oldColumnizerIsXmlType = CurrentColumnizer is ILogLineXmlColumnizer; - bool oldColumnizerIsPreProcess = CurrentColumnizer is IPreProcessColumnizer; - bool mustReload = false; - - // Check if the filtered columns disappeared, if so must refresh the UI - if (_filterParams.columnRestrict) - { - string[] newColumns = columnizer != null ? columnizer.GetColumnNames() : Array.Empty(); - bool colChanged = false; - - if (dataGridView.ColumnCount - 2 == newColumns.Length) // two first columns are 'marker' and 'line number' - { - for (int 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); - } - } - - Type oldColType = _filterParams.currentColumnizer?.GetType(); - Type 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(); - } - - Settings settings = ConfigManager.Settings; - ShowLineColumn(!settings.hideLineColumn); - ShowTimeSpread(Preferences.showTimeSpread && columnizer.IsTimeshiftImplemented()); - } - - if (!columnizer.IsTimeshiftImplemented() && IsTimeSynced) - { - FreeFromTimeSync(); - } - - columnComboBox.Items.Clear(); - - foreach (string columnName in columnizer.GetColumnNames()) - { - columnComboBox.Items.Add(columnName); - } - - columnComboBox.SelectedIndex = 0; - - OnColumnizerChanged(CurrentColumnizer); - } - - private void AutoResizeColumns(DataGridView 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, DataGridView gridView, bool noBackgroundFill, - HilightEntry groundEntry) - { - PaintHighlightedCell(e, gridView, noBackgroundFill, groundEntry); - } - - private void PaintHighlightedCell(DataGridViewCellPaintingEventArgs e, DataGridView gridView, - bool noBackgroundFill, - HilightEntry groundEntry) - { - var column = e.Value as IColumn; - - column ??= Column.EmptyColumn; - - IList 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 HilightEntry - { - SearchText = column.DisplayValue, - ForegroundColor = groundEntry?.ForegroundColor ?? Color.FromKnownColor(KnownColor.Black), - BackgroundColor = groundEntry?.BackgroundColor ?? Color.Empty, - IsWordMatch = true - }; - - HilightMatchEntry hme = new() - { - StartPos = 0, - Length = column.DisplayValue.Length, - HilightEntry = he - }; - - if (groundEntry != null) - { - hme.HilightEntry.IsBold = groundEntry.IsBold; - } - - matchList = MergeHighlightMatchEntries(matchList, hme); - - int 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; - 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; - } - - TextFormatFlags 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); - - Point wordPos = valBounds.Location; - Size proposedSize = new(valBounds.Width, valBounds.Height); - - Rectangle r = gridView.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true); - e.Graphics.SetClip(e.CellBounds); - - foreach (HilightMatchEntry matchEntry in matchList) - { - Font font = matchEntry != null && matchEntry.HilightEntry.IsBold ? BoldFont : NormalFont; - Brush bgBrush = matchEntry.HilightEntry.BackgroundColor != Color.Empty - ? new SolidBrush(matchEntry.HilightEntry.BackgroundColor) - : null; - string matchWord = column.DisplayValue.Substring(matchEntry.StartPos, matchEntry.Length); - Size wordSize = TextRenderer.MeasureText(e.Graphics, matchWord, font, proposedSize, flags); - wordSize.Height = e.CellBounds.Height; - Rectangle wordRect = new(wordPos, wordSize); - - Color foreColor = matchEntry.HilightEntry.ForegroundColor; - if ((e.State & DataGridViewElementStates.Selected) != DataGridViewElementStates.Selected) - { - if (!noBackgroundFill && bgBrush != null && !matchEntry.HilightEntry.NoBackground) - { - e.Graphics.FillRectangle(bgBrush, wordRect); - } - } - - if (foreColor == Color.Black) - { - foreColor = ColorMode.ForeColor; - } - - 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 HilightMatchEntry objects. The list spans over the whole cell and contains color infos for every substring. - private IList MergeHighlightMatchEntries(IList matchList, - HilightMatchEntry groundEntry) - { - // Fill an area with lenth of whole text with a default hilight entry - HilightEntry[] entryArray = new HilightEntry[groundEntry.Length]; - for (int i = 0; i < entryArray.Length; ++i) - { - entryArray[i] = groundEntry.HilightEntry; - } - - // "overpaint" with all matching word match enries - // Non-word-mode matches will not overpaint because they use the groundEntry - foreach (HilightMatchEntry me in matchList) - { - int endPos = me.StartPos + me.Length; - for (int i = me.StartPos; i < endPos; ++i) - { - if (me.HilightEntry.IsWordMatch) - { - entryArray[i] = me.HilightEntry; - } - 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) - { - HilightEntry currentEntry = entryArray[0]; - int lastStartPos = 0; - int pos = 0; - - for (; pos < entryArray.Length; ++pos) - { - if (entryArray[pos] != currentEntry) - { - HilightMatchEntry me = new() - { - StartPos = lastStartPos, - Length = pos - lastStartPos, - HilightEntry = currentEntry - }; - - mergedList.Add(me); - currentEntry = entryArray[pos]; - lastStartPos = pos; - } - } - - HilightMatchEntry me2 = new() - { - StartPos = lastStartPos, - Length = pos - lastStartPos, - HilightEntry = currentEntry - }; - - mergedList.Add(me2); - } - - return mergedList; - } - - /// - /// Returns the first HilightEntry that matches the given line - /// - private HilightEntry FindHilightEntry(ITextValue line) - { - return FindHighlightEntry(line, false); - } - - private HilightEntry FindFirstNoWordMatchHilightEntry(ITextValue line) - { - return FindHighlightEntry(line, true); - } - - private bool CheckHighlightEntryMatch(HilightEntry 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)) - { - return true; - } - } - else - { - if (column.Text.ToLower().Contains(entry.SearchText.ToLower())) - { - 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 (HilightEntry entry in _currentHighlightGroup.HilightEntryList) - { - if (CheckHighlightEntryMatch(entry, line)) - { - resultList.Add(entry); - } - } - } - } - - return resultList; - } - - private void GetHighlightEntryMatches(ITextValue line, IList hilightEntryList, IList resultList) - { - foreach (HilightEntry entry in hilightEntryList) - { - if (entry.IsWordMatch) - { - MatchCollection matches = entry.Regex.Matches(line.Text); - foreach (Match match in matches) - { - HilightMatchEntry me = new(); - me.HilightEntry = entry; - me.StartPos = match.Index; - me.Length = match.Length; - resultList.Add(me); - } - } - else - { - if (CheckHighlightEntryMatch(entry, line)) - { - HilightMatchEntry me = new(); - me.HilightEntry = entry; - me.StartPos = 0; - me.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 (HilightEntry 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(); - } - - private void SyncTimestampDisplay() - { - if (CurrentColumnizer.IsTimeshiftImplemented()) - { - if (dataGridView.CurrentRow != null) - { - SyncTimestampDisplay(dataGridView.CurrentRow.Index); - } - } - } - - private void SyncTimestampDisplay(int lineNum) - { - _timeShiftSyncLine = lineNum; - _timeShiftSyncTimerEvent.Set(); - _timeShiftSyncWakeupEvent.Set(); - } - - 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) - { - bool signaled = _timeShiftSyncTimerEvent.WaitOne(WAIT_TIME, true); - _timeShiftSyncTimerEvent.Reset(); - if (!signaled) - { - break; - } - } - - // timeout with no new Trigger -> update display - int lineNum = _timeShiftSyncLine; - if (lineNum >= 0 && lineNum < dataGridView.RowCount) - { - int refLine = lineNum; - DateTime timeStamp = GetTimestampForLine(ref refLine, true); - if (!timeStamp.Equals(DateTime.MinValue) && !_shouldTimestampDisplaySyncingCancel) - { - _guiStateArgs.Timestamp = timeStamp; - SendGuiStateUpdate(); - if (_shouldCallTimeSync) - { - refLine = lineNum; - DateTime exactTimeStamp = GetTimestampForLine(ref refLine, false); - SyncOtherWindows(exactTimeStamp); - _shouldCallTimeSync = false; - } - } - } - - // show time difference between 2 selected lines - if (dataGridView.SelectedRows.Count == 2) - { - int row1 = dataGridView.SelectedRows[0].Index; - int row2 = dataGridView.SelectedRows[1].Index; - if (row1 > row2) - { - (row2, row1) = (row1, row2); - } - - int refLine = row1; - DateTime timeStamp1 = GetTimestampForLine(ref refLine, false); - refLine = row2; - DateTime 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); - } - } - } - } - - private void SyncFilterGridPos() - { - try - { - if (_filterResultList.Count > 0) - { - int 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(); - } - - private int Search(SearchParams searchParams) - { - if (searchParams.searchText == null) - { - return -1; - } - - int lineNum = searchParams.isFromTop && !searchParams.isFindNext ? 0 : searchParams.currentLine; - string lowerSearchText = searchParams.searchText.ToLower(); - int count = 0; - bool 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"); - } - } - - ILogLine 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(lowerSearchText, StringComparison.CurrentCultureIgnoreCase)) - { - return lineNum; - } - } - else - { - if (line.FullLine.Contains(searchParams.searchText)) - { - 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(); - } - - private void SelectLine(int line, bool triggerSyncCall, bool shouldScroll) - { - try - { - _shouldCallTimeSync = triggerSyncCall; - bool wasCancelled = _shouldCancel; - _shouldCancel = false; - _isSearching = false; - StatusLineText(""); - _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: "); - } - } - - 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("Edit control in logWindow was null"); - } - } - } - } - - private void UpdateEditColumnDisplay(DataGridViewTextBoxEditingControl editControl) - { - // prevents key events after edit mode has ended - if (dataGridView.EditingControl != null) - { - int pos = editControl.SelectionStart + editControl.SelectionLength; - StatusLineText(" " + pos); - _logger.Debug("SelStart: {0}, SelLen: {1}", editControl.SelectionStart, editControl.SelectionLength); - } - } - - private void SelectPrevHighlightLine() - { - int lineNum = dataGridView.CurrentCellAddress.Y; - while (lineNum > 0) - { - lineNum--; - ILogLine line = _logFileReader.GetLogLine(lineNum); - if (line != null) - { - HilightEntry entry = FindHilightEntry(line); - if (entry != null) - { - SelectLine(lineNum, false, true); - break; - } - } - } - } - - private void SelectNextHighlightLine() - { - int lineNum = dataGridView.CurrentCellAddress.Y; - while (lineNum < _logFileReader.LineCount) - { - lineNum++; - ILogLine line = _logFileReader.GetLogLine(lineNum); - if (line != null) - { - HilightEntry entry = FindHilightEntry(line); - if (entry != null) - { - SelectLine(lineNum, false, true); - break; - } - } - } - } - - private int FindNextBookmarkIndex(int lineNum) - { - if (lineNum >= dataGridView.RowCount) - { - lineNum = 0; - } - else - { - lineNum++; - } - - return _bookmarkProvider.FindNextBookmarkIndex(lineNum); - } - - 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 (RowHeightEntry entry in _rowHeightList.Values) - { - int line = entry.LineNum - offset; - if (line >= 0) - { - entry.LineNum = line; - newList.Add(line, entry); - } - } - - _rowHeightList = newList; - } - - private void ShiftFilterPipes(int offset) - { - lock (_filterPipeList) - { - foreach (FilterPipe pipe in _filterPipeList) - { - pipe.ShiftLineNums(offset); - } - } - } - - private void LoadFilterPipes() - { - lock (_filterPipeList) - { - foreach (FilterPipe pipe in _filterPipeList) - { - pipe.RecreateTempFile(); - } - } - - if (_filterPipeList.Count > 0) - { - for (int i = 0; i < dataGridView.RowCount; ++i) - { - ProcessFilterPipes(i); - } - } - } - - private void DisconnectFilterPipes() - { - lock (_filterPipeList) - { - foreach (FilterPipe pipe in _filterPipeList) - { - pipe.ClearLineList(); - } - } - } - - 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; - } - - 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 = ""; - } - - private void FilterSearch() - { - if (filterComboBox.Text.Length == 0) - { - _filterParams.searchText = ""; - _filterParams.lowerSearchText = ""; - _filterParams.isRangeSearch = false; - ClearFilterList(); - filterSearchButton.Image = null; - ResetFilterControls(); - saveFilterButton.Enabled = false; - return; - } - - FilterSearch(filterComboBox.Text); - } - - 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.ToLower(); - ConfigManager.Settings.filterHistoryList.Remove(text); - ConfigManager.Settings.filterHistoryList.Insert(0, text); - int maxHistory = ConfigManager.Settings.Preferences.maximumFilterEntries; - - if (ConfigManager.Settings.filterHistoryList.Count > maxHistory) - { - ConfigManager.Settings.filterHistoryList.RemoveAt(filterComboBox.Items.Count - 1); - } - - filterComboBox.Items.Clear(); - foreach (string 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 (string 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(); - - Settings 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)); - Task 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); - fs.FilterHitList = _filterHitList; - fs.FilterResultLines = _filterResultList; - fs.LastFilterLinesList = _lastFilterLinesList; - BackgroundProcessCancelHandler 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: {0} ms.", endTime - startTime); - - OnDeRegisterCancelHandler(cancelHandler); - StatusLineText("Filter duration: " + (endTime - startTime) + " ms."); - } - - private void FilterProgressCallback(int lineCount) - { - UpdateProgressBar(lineCount); - } - - private void Filter(FilterParams filterParams, List filterResultLines, List lastFilterLinesList, - List filterHitList) - { - long startTime = Environment.TickCount; - try - { - filterParams.Reset(); - int lineNum = 0; - //AddFilterLineFx addFx = new AddFilterLineFx(AddFilterLine); - ColumnizerCallback callback = new(this); - while (true) - { - ILogLine 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: {0} ms.", endTime - startTime); - - 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 (int 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 (int 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; - } - - private void AddFilterLine(int lineNum, bool immediate, FilterParams filterParams, List filterResultLines, - List lastFilterLinesList, List filterHitList) - { - int count; - lock (_filterResultList) - { - filterHitList.Add(lineNum); - IList 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}); - } - } - - 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(); - //} - - 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(); - } - - private void FilterComplete() - { - if (!IsDisposed && !_waitingForClose && !Disposing) - { - Invoke(new MethodInvoker(ResetStatusAfterFilter)); - } - } - - private void FilterComplete(IAsyncResult result) - { - if (!IsDisposed && !_waitingForClose && !Disposing) - { - Invoke(new MethodInvoker(ResetStatusAfterFilter)); - } - } - - 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: "); - } - } - - 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 - */ - - private void ShiftFilterLines(int offset) - { - List newFilterList = []; - lock (_filterResultList) - { - foreach (int lineNum in _filterResultList) - { - int line = lineNum - offset; - if (line >= 0) - { - newFilterList.Add(line); - } - } - - _filterResultList = newFilterList; - } - - newFilterList = []; - foreach (int lineNum in _filterHitList) - { - int line = lineNum - offset; - if (line >= 0) - { - newFilterList.Add(line); - } - } - - _filterHitList = newFilterList; - - int 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(); - } - - private void CheckForFilterDirty() - { - if (IsFilterSearchDirty(_filterParams)) - { - filterSearchButton.Image = _searchButtonImage; - saveFilterButton.Enabled = false; - } - else - { - filterSearchButton.Image = null; - saveFilterButton.Enabled = true; - } - } - - private bool IsFilterSearchDirty(FilterParams filterParams) - { - if (!filterParams.searchText.Equals(filterComboBox.Text)) - { - return true; - } - - if (filterParams.isRangeSearch != rangeCheckBox.Checked) - { - return true; - } - - if (filterParams.isRangeSearch && !filterParams.rangeSearchText.Equals(filterRangeComboBox.Text)) - { - 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; - } - - private void AdjustMinimumGridWith() - { - if (dataGridView.Columns.Count > 1) - { - //this.dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - AutoResizeColumns(dataGridView); - - int width = dataGridView.Columns.GetColumnsWidth(DataGridViewElementStates.Visible); - int 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; - } - } - } - - private void InvalidateCurrentRow(DataGridView gridView) - { - if (gridView.CurrentCellAddress.Y > -1) - { - gridView.InvalidateRow(gridView.CurrentCellAddress.Y); - } - } - - private void InvalidateCurrentRow() - { - InvalidateCurrentRow(dataGridView); - InvalidateCurrentRow(filterGridView); - } - - private void DisplayCurrentFileOnStatusline() - { - if (_logFileReader.IsMultiFile) - { - try - { - if (dataGridView.CurrentRow != null && dataGridView.CurrentRow.Index > -1) - { - string 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; - } - } - - private void UpdateFilterHistoryFromSettings() - { - ConfigManager.Settings.filterHistoryList = ConfigManager.Settings.filterHistoryList; - filterComboBox.Items.Clear(); - foreach (string item in ConfigManager.Settings.filterHistoryList) - { - filterComboBox.Items.Add(item); - } - - filterRangeComboBox.Items.Clear(); - foreach (string 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); - } - - 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; - } - - private void CheckForAdvancedButtonDirty() - { - if (IsAdvancedOptionActive() && !_showAdvanced) - { - advancedButton.Image = _advancedButtonImage; - } - else - { - advancedButton.Image = null; - } - } - - private void FilterToTab() - { - filterSearchButton.Enabled = false; - Task.Run(() => WriteFilterToTab()); - } - - private void WriteFilterToTab() - { - FilterPipe pipe = new(_filterParams.CreateCopy(), this); - lock (_filterResultList) - { - string namePrefix = "->F"; - string title; - if (IsTempFile) - { - title = TempTitleName + namePrefix + ++_filterPipeNameCounter; - } - else - { - title = Util.GetNameFromPath(FileName) + namePrefix + ++_filterPipeNameCounter; - } - - WritePipeToTab(pipe, _filterResultList, title, null); - } - } - - private void WritePipeToTab(FilterPipe pipe, IList lineNumberList, string name, PersistenceData persistenceData) - { - _logger.Info("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; - int count = 0; - pipe.OpenFile(); - LogExpertCallback callback = new(this); - foreach (int i in lineNumberList) - { - if (_shouldCancel) - { - break; - } - - ILogLine 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("WritePipeToTab(): finished"); - Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), pipe, name, persistenceData); - } - - private void WriteFilterToTabFinished(FilterPipe pipe, string name, PersistenceData persistenceData) - { - _isSearching = false; - if (!_shouldCancel) - { - string title = name; - ILogLineColumnizer preProcessColumnizer = null; - if (CurrentColumnizer is not ILogLineXmlColumnizer) - { - preProcessColumnizer = CurrentColumnizer; - } - - LogWindow 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. - /// - /// - /// - internal void WritePipeTab(IList lineEntryList, string title) - { - FilterPipe pipe = new(new FilterParams(), this); - pipe.IsStopped = true; - pipe.Closed += OnPipeDisconnected; - pipe.OpenFile(); - foreach (LineEntry entry in lineEntryList) - { - pipe.WriteToPipe(entry.logLine, entry.lineNum); - } - - pipe.CloseFile(); - Invoke(new WriteFilterToTabFinishedFx(WriteFilterToTabFinished), [pipe, title, null]); - } - - private void FilterRestore(LogWindow newWin, PersistenceData persistenceData) - { - newWin.WaitForLoadingFinished(); - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(persistenceData.columnizerName, - PluginRegistry.Instance.RegisteredColumnizers); - if (columnizer != null) - { - SetColumnizerFx fx = newWin.ForceColumnizer; - newWin.Invoke(fx, [columnizer]); - } - else - { - _logger.Warn("FilterRestore(): Columnizer {0} not found", persistenceData.columnizerName); - } - - newWin.BeginInvoke(new RestoreFiltersFx(newWin.RestoreFilters), [persistenceData]); - } - - private void ProcessFilterPipes(int lineNum) - { - ILogLine searchLine = _logFileReader.GetLogLine(lineNum); - if (searchLine == null) - { - return; - } - - ColumnizerCallback callback = new(this); - callback.LineNum = lineNum; - IList deleteList = []; - lock (_filterPipeList) - { - foreach (FilterPipe pipe in _filterPipeList) - { - if (pipe.IsStopped) - { - continue; - } - - long startTime = Environment.TickCount; - if (Util.TestFilterCondition(pipe.FilterParams, searchLine, callback)) - { - IList filterResult = - GetAdditionalFilterResults(pipe.FilterParams, lineNum, pipe.LastLinesHistoryList); - pipe.OpenFile(); - foreach (int line in filterResult) - { - pipe.LastLinesHistoryList.Add(line); - if (pipe.LastLinesHistoryList.Count > SPREAD_MAX * 2) - { - pipe.LastLinesHistoryList.RemoveAt(0); - } - - ILogLine textLine = _logFileReader.GetLogLine(line); - bool fileOk = pipe.WriteToPipe(textLine, line); - if (!fileOk) - { - deleteList.Add(pipe); - } - } - - pipe.CloseFile(); - } - - long endTime = Environment.TickCount; - //_logger.logDebug("ProcessFilterPipes(" + lineNum + ") duration: " + ((endTime - startTime))); - } - } - - foreach (FilterPipe pipe in deleteList) - { - _filterPipeList.Remove(pipe); - } - } - - private void CopyMarkedLinesToClipboard() - { - if (_guiStateArgs.CellSelectMode) - { - DataObject 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 (int lineNum in lineNumList) - { - ILogLine 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; - } - - private void ApplyDataGridViewPrefs(DataGridView dataGridView, Preferences prefs) - { - if (dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) > 1) - { - if (prefs.setLastColumnWidth) - { - dataGridView.Columns[dataGridView.Columns.GetColumnCount(DataGridViewElementStates.None) - 1].MinimumWidth = prefs.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); - } - - 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 - * =======================================================================*/ - - private void SetTimestampLimits() - { - if (!CurrentColumnizer.IsTimeshiftImplemented()) - { - return; - } - - int 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; - } - - private void BookmarkComment(Bookmark bookmark) - { - BookmarkCommentDlg dlg = new(); - dlg.Comment = bookmark.Text; - if (dlg.ShowDialog() == DialogResult.OK) - { - bookmark.Text = dlg.Comment; - dataGridView.Refresh(); - OnBookmarkTextChanged(bookmark); - } - } - - /// - /// Indicates which columns we are filtering on - /// - /// - /// - private string CalculateColumnNames(FilterParams filter) - { - string names = string.Empty; - - if (filter.columnRestrict) - { - foreach (int 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; - } - - private void ApplyFrozenState(DataGridView gridView) - { - SortedDictionary dict = []; - foreach (DataGridViewColumn col in gridView.Columns) - { - dict.Add(col.DisplayIndex, col); - } - - foreach (DataGridViewColumn col in dict.Values) - { - col.Frozen = _freezeStateMap.ContainsKey(gridView) && _freezeStateMap[gridView]; - bool sel = col.HeaderCell.Selected; - if (col.Index == _selectedCol) - { - break; - } - } - } - - private void ShowTimeSpread(bool show) - { - if (show) - { - tableLayoutPanel1.ColumnStyles[1].Width = 16; - } - else - { - tableLayoutPanel1.ColumnStyles[1].Width = 0; - } - - _timeSpreadCalc.Enabled = show; - } - - 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(); - } - - private void TestStatistic(PatternArgs patternArgs) - { - int beginLine = patternArgs.startLine; - _logger.Info("TestStatistics() called with start line {0}", beginLine); - - _patternArgs = patternArgs; - - int 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 = []; - int blockId = 0; - _isSearching = true; - _shouldCancel = false; - int searchLine = -1; - for (int i = beginLine; i < num && !_shouldCancel; ++i) - { - if (processedLinesDict.ContainsKey(i)) - { - continue; - } - - PatternBlock block; - int maxBlockLen = patternArgs.endLine - patternArgs.startLine; - //int searchLine = i + 1; - _logger.Debug("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("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("TestStatistics() ended"); - } - - private void addBlockTargetLinesToDict(Dictionary dict, PatternBlock block) - { - foreach (int lineNum in block.targetLines.Keys) - { - if (!dict.ContainsKey(lineNum)) - { - dict.Add(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 (PatternBlock 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) - { - int targetLine = FindSimilarLine(startNum, startLineToSearch, processedLinesDict); - if (targetLine == -1) - { - return null; - } - - PatternBlock block = new(); - block.startLine = startNum; - int srcLine = block.startLine; - block.targetStart = targetLine; - int srcMisses = 0; - block.srcLines.Add(srcLine, srcLine); - //block.targetLines.Add(targetLine, targetLine); - int len = 0; - QualityInfo qi = new(); - qi.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; - } - - int 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) - { - int tempWeight = block.weigth; - for (int tl = targetLine + 1; tl < nextTargetLine; ++tl) - { - qi = new QualityInfo(); - qi.quality = --tempWeight; - block.qualityInfoList[tl] = qi; - } - } - - targetLine = nextTargetLine; - qi = new QualityInfo(); - qi.quality = block.weigth; - block.qualityInfoList[targetLine] = qi; - } - else - { - srcMisses++; - block.weigth--; - targetLine++; - qi = new QualityInfo(); - qi.quality = block.weigth; - block.qualityInfoList[targetLine] = qi; - if (srcMisses > maxMisses) - { - break; - } - } - } - - block.targetEnd = targetLine; - qi = new QualityInfo(); - qi.quality = block.weigth; - block.qualityInfoList[targetLine] = qi; - for (int 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"); - - int num = _logFileReader.LineCount; - for (int i = 0; i < num; ++i) - { - string msg = GetMsgForLine(i); - if (msg != null) - { - msg = msg.ToLower(); - msg = regex.Replace(msg, "0"); - msg = regex2.Replace(msg, " "); - char[] chars = msg.ToCharArray(); - int value = 0; - int numOfE = 0; - int numOfA = 0; - int 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) - { - int value = _lineHashList[srcLine]; - - int num = _lineHashList.Count; - for (int 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) - { - int threshold = _patternArgs.fuzzy; - - bool prepared = false; - Regex regex = null; - Regex regex2 = null; - string msgToFind = null; - CultureInfo culture = CultureInfo.CurrentCulture; - - int num = _logFileReader.LineCount; - for (int 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; - } - - string msg = GetMsgForLine(i); - if (msg != null) - { - msg = regex.Replace(msg, "0"); - msg = regex2.Replace(msg, " "); - int lenDiff = Math.Abs(msg.Length - msgToFind.Length); - if (lenDiff > threshold) - { - //this.similarCache[srcLine, i] = lenDiff; - continue; - } - - msg = msg.ToLower(culture); - int distance = Util.YetiLevenshtein(msgToFind, msg); - //this.similarCache[srcLine, i] = distance; - if (distance < threshold) - { - return i; - } - } - } - } - - return -1; - } - - private string GetMsgForLine(int i) - { - ILogLine line = _logFileReader.GetLogLine(i); - ILogLineColumnizer columnizer = CurrentColumnizer; - ColumnizerCallback callback = new(this); - IColumnizedLogLine cols = columnizer.SplitLine(callback, line); - return cols.ColumnValues.Last().FullValue; - } - - private void ChangeRowHeight(bool decrease) - { - int rowNum = dataGridView.CurrentCellAddress.Y; - if (rowNum < 0 || rowNum >= dataGridView.RowCount) - { - return; - } - - if (decrease) - { - if (!_rowHeightList.ContainsKey(rowNum)) - { - return; - } - else - { - RowHeightEntry entry = _rowHeightList[rowNum]; - entry.Height -= _lineHeight; - if (entry.Height <= _lineHeight) - { - _rowHeightList.Remove(rowNum); - } - } - } - else - { - RowHeightEntry entry; - if (!_rowHeightList.ContainsKey(rowNum)) - { - entry = new RowHeightEntry(); - entry.LineNum = rowNum; - entry.Height = _lineHeight; - _rowHeightList[rowNum] = entry; - } - else - { - entry = _rowHeightList[rowNum]; - } - - entry.Height += _lineHeight; - } - - dataGridView.UpdateRowHeightInfo(rowNum, false); - if (rowNum == dataGridView.RowCount - 1 && _guiStateArgs.FollowTail) - { - dataGridView.FirstDisplayedScrollingRowIndex = rowNum; - } - - dataGridView.Refresh(); - } - - private int GetRowHeight(int rowNum) - { - if (_rowHeightList.ContainsKey(rowNum)) - { - return _rowHeightList[rowNum].Height; - } - else - { - return _lineHeight; - } - } - - private void AddBookmarkAtLineSilently(int lineNum) - { - if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - _bookmarkProvider.AddBookmark(new Bookmark(lineNum)); - } - } - - private void AddBookmarkAndEditComment() - { - int lineNum = dataGridView.CurrentCellAddress.Y; - if (!_bookmarkProvider.IsBookmarkAtLine(lineNum)) - { - ToggleBookmark(); - } - - BookmarkComment(_bookmarkProvider.GetBookmarkForLine(lineNum)); - } - - private void AddBookmarkComment(string text) - { - int 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); - } - - private void MarkCurrentFilterRange() - { - _filterParams.rangeSearchText = filterRangeComboBox.Text; - ColumnizerCallback callback = new(this); - RangeFinder rangeFinder = new(_filterParams, callback); - Entities.Range range = rangeFinder.FindRange(dataGridView.CurrentCellAddress.Y); - if (range != null) - { - SetCellSelectionMode(false); - _noSelectionUpdates = true; - for (int i = range.StartLine; i <= range.EndLine; ++i) - { - dataGridView.Rows[i].Selected = true; - } - - _noSelectionUpdates = false; - UpdateSelectionDisplay(); - } - } - - private void RemoveTempHighlights() - { - lock (_tempHighlightEntryListLock) - { - _tempHighlightEntryList.Clear(); - } - - RefreshAllGrids(); - } - - 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)); - } - - private void SetBookmarksForSelectedFilterLines() - { - lock (_filterResultList) - { - foreach (DataGridViewRow row in filterGridView.SelectedRows) - { - int lineNum = _filterResultList[row.Index]; - AddBookmarkAtLineSilently(lineNum); - } - } - - dataGridView.Refresh(); - filterGridView.Refresh(); - OnBookmarkAdded(); - } - - private void SetDefaultHighlightGroup() - { - HilightGroup group = _parentLogTabWin.FindHighlightGroupByFileMask(FileName); - if (group != null) - { - SetCurrentHighlightGroup(group.GroupName); - } - else - { - SetCurrentHighlightGroup("[Default]"); - } - } - - private void HandleChangedFilterOnLoadSetting() - { - _parentLogTabWin.Preferences.isFilterOnLoad = filterOnLoadCheckBox.Checked; - _parentLogTabWin.Preferences.isAutoHideFilterList = hideFilterListOnLoadCheckBox.Checked; - OnFilterListChanged(this); - } - - private void FireCancelHandlers() - { - lock (_cancelHandlerList) - { - foreach (BackgroundProcessCancelHandler handler in _cancelHandlerList) - { - handler.EscapePressed(); - } - } - } - - private void SyncOtherWindows(DateTime timestamp) - { - lock (_timeSyncListLock) - { - TimeSyncList?.NavigateToTimestamp(timestamp, this); - } - } - - private void AddSlaveToTimesync(LogWindow slave) - { - lock (_timeSyncListLock) - { - if (TimeSyncList == null) - { - if (slave.TimeSyncList == null) - { - TimeSyncList = new TimeSyncList(); - TimeSyncList.AddWindow(this); - } - else - { - TimeSyncList = slave.TimeSyncList; - } - - int currentLineNum = dataGridView.CurrentCellAddress.Y; - int refLine = currentLineNum; - DateTime 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)); - } - - private void AddSearchHitHighlightEntry(SearchParams para) - { - HilightEntry 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(); - } - - private void RemoveAllSearchHighlightEntries() - { - lock (_tempHighlightEntryListLock) - { - List newList = []; - foreach (HilightEntry he in _tempHighlightEntryList) - { - if (!he.IsSearchHit) - { - newList.Add(he); - } - } - - _tempHighlightEntryList = newList; - } - - RefreshAllGrids(); - } - - private DataGridViewColumn GetColumnByName(DataGridView dataGridView, string name) - { - foreach (DataGridViewColumn col in dataGridView.Columns) - { - if (col.HeaderText.Equals(name)) - { - return col; - } - } - - return null; - } - - private void SelectColumn() - { - string colName = columnComboBox.SelectedItem as string; - DataGridViewColumn col = GetColumnByName(dataGridView, colName); - if (col != null && !col.Frozen) - { - dataGridView.FirstDisplayedScrollingColumnIndex = col.Index; - int 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/Controls/LogWindow/LogWindowsPublic.cs b/src/LogExpert/Controls/LogWindow/LogWindowsPublic.cs deleted file mode 100644 index 8f8ef767..00000000 --- a/src/LogExpert/Controls/LogWindow/LogWindowsPublic.cs +++ /dev/null @@ -1,1817 +0,0 @@ -using LogExpert.Classes; -using LogExpert.Classes.Bookmark; -using LogExpert.Classes.Columnizer; -using LogExpert.Classes.Filter; -using LogExpert.Classes.Highlight; -using LogExpert.Classes.Log; -using LogExpert.Classes.Persister; -using LogExpert.Config; -using LogExpert.Entities; -using LogExpert.Entities.EventArgs; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; -//using System.Linq; - -namespace LogExpert.Controls.LogWindow -{ - internal 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. - // - bool isUsingDefaultColumnizer = false; - if (!LoadPersistenceOptions()) - { - if (!IsTempFile) - { - ILogLineColumnizer columnizer = FindColumnizer(); - if (columnizer != null) - { - if (_reloadMemento == null) - { - columnizer = ColumnizerPicker.CloneColumnizer(columnizer); - } - } - 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 LogfileReader(fileName, EncodingOptions, IsMultiFile, Preferences.bufferCount, Preferences.linesPerBuffer, _multiFileOptions) - { - 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; - } - - if (CurrentColumnizer is IPreProcessColumnizer processColumnizer) - { - _logFileReader.PreProcessColumnizer = processColumnizer; - } - else - { - _logFileReader.PreProcessColumnizer = null; - } - - RegisterLogFileReaderEvents(); - _logger.Info($"Loading logfile: {fileName}"); - _logFileReader.StartMonitoring(); - - if (isUsingDefaultColumnizer) - { - if (Preferences.autoPick) - { - ILogLineColumnizer newColumnizer = ColumnizerPicker.FindBetterColumnizer(FileName, _logFileReader, CurrentColumnizer); - - 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 (string name in fileNames) - { - _logger.Info("File: {0}", name); - } - - if (_logFileReader != null) - { - _logFileReader.StopMonitoring(); - UnRegisterLogFileReaderEvents(); - } - - EncodingOptions = encodingOptions; - _columnCache = new ColumnCache(); - - _logFileReader = new LogfileReader(fileNames, EncodingOptions, Preferences.bufferCount, Preferences.linesPerBuffer, _multiFileOptions); - _logFileReader.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 - { - PersistenceData persistenceData = GetPersistenceData(); - - if (ForcedPersistenceFileName == null) - { - return Persister.SavePersistenceData(FileName, persistenceData, Preferences); - } - - return 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(); - persistenceData.bookmarkList = _bookmarkProvider.BookmarkList; - persistenceData.rowHeightList = _rowHeightList; - persistenceData.multiFile = IsMultiFile; - persistenceData.multiFilePattern = _multiFileOptions.FormatPattern; - persistenceData.multiFileMaxDays = _multiFileOptions.MaxDayTry; - persistenceData.currentLine = dataGridView.CurrentCellAddress.Y; - persistenceData.firstDisplayedLine = dataGridView.FirstDisplayedScrollingRowIndex; - persistenceData.filterVisible = !splitContainerLogWindow.Panel2Collapsed; - persistenceData.filterAdvanced = !advancedFilterSplitContainer.Panel1Collapsed; - persistenceData.filterPosition = splitContainerLogWindow.SplitterDistance; - persistenceData.followTail = _guiStateArgs.FollowTail; - persistenceData.fileName = FileName; - persistenceData.tabName = Text; - persistenceData.sessionFileName = SessionFileName; - persistenceData.columnizerName = CurrentColumnizer.GetName(); - persistenceData.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 (FilterPipe filterPipe in _filterPipeList) - { - FilterTabData data = new(); - data.persistenceData = filterPipe.OwnLogWindow.GetPersistenceData(); - data.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 {0}", FileName); - - try - { - File.Delete(FileName); - } - catch (IOException e) - { - _logger.Error(e, "Error while deleting temp file {0}: {1}", FileName, e); - } - } - - FilterPipe?.CloseAndDisconnect(); - DisconnectFilterPipes(); - } - - public void WaitForLoadingFinished() - { - _externaLoadingFinishedEvent.WaitOne(); - } - - public void ForceColumnizer(ILogLineColumnizer columnizer) - { - _forcedColumnizer = ColumnizerPicker.CloneColumnizer(columnizer); - SetColumnizer(_forcedColumnizer); - } - - public void ForceColumnizerForLoading(ILogLineColumnizer columnizer) - { - _forcedColumnizerForLoading = ColumnizerPicker.CloneColumnizer(columnizer); - } - - public void PreselectColumnizer(string columnizerName) - { - ILogLineColumnizer columnizer = ColumnizerPicker.FindColumnizerByName(columnizerName, PluginRegistry.Instance.RegisteredColumnizers); - PreSelectColumnizer(ColumnizerPicker.CloneColumnizer(columnizer)); - } - - public void ColumnizerConfigChanged() - { - SetColumnizerInternal(CurrentColumnizer); - } - - public void SetColumnizer(ILogLineColumnizer columnizer, DataGridView 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).ToString() // line number - }; - } - - if (columnIndex == 0) // marker column - { - return Column.EmptyColumn; - } - - try - { - IColumnizedLogLine cols = GetColumnsForLine(rowIndex); - if (cols != null && cols.ColumnValues != null) - { - if (columnIndex <= cols.ColumnValues.Length + 1) - { - IColumn value = cols.ColumnValues[columnIndex - 2]; - - if (value != null && value.DisplayValue != null) - { - return value; - } - return value; - } - - if (columnIndex == 2) - { - return cols.ColumnValues[^1]; - } - - return Column.EmptyColumn; - } - } - catch - { - return Column.EmptyColumn; - } - - return Column.EmptyColumn; - } - - public void CellPainting(DataGridView gridView, int rowIndex, DataGridViewCellPaintingEventArgs e) - { - if (rowIndex < 0 || e.ColumnIndex < 0) - { - e.Handled = false; - return; - } - - ILogLine line = _logFileReader.GetLogLineWithWait(rowIndex).Result; - - if (line != null) - { - HilightEntry entry = FindFirstNoWordMatchHilightEntry(line); - e.Graphics.SetClip(e.CellBounds); - - if ((e.State & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected) - { - Color backColor = ColorMode.BackgroundColor; - - Brush brush; - - if (gridView.Focused) - { - brush = new SolidBrush(e.CellStyle.SelectionBackColor); - } - else - { - Color color = backColor; - brush = new SolidBrush(color); - } - - e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); - } - else - { - Color bgColor = ColorMode.DockBackgroundColor; - - if (!DebugOptions.disableWordHighlight) - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - else - { - if (entry != null) - { - bgColor = entry.BackgroundColor; - } - } - - e.CellStyle.BackColor = bgColor; - - 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); - Brush brush = new SolidBrush(BookmarkColor); - e.Graphics.FillRectangle(brush, r); - brush.Dispose(); - Bookmark bookmark = _bookmarkProvider.GetBookmarkForLine(rowIndex); - - if (bookmark.Text.Length > 0) - { - StringFormat format = new(); - format.LineAlignment = StringAlignment.Center; - format.Alignment = StringAlignment.Center; - Brush brush2 = new SolidBrush(Color.FromArgb(255, 190, 100, 0)); - 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(); - } - } - } - - e.Paint(e.CellBounds, DataGridViewPaintParts.Border); - e.Handled = true; - } - } - - public void OnDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) - { - DataGridView gridView = (DataGridView)sender; - CellPainting(gridView, e.RowIndex, e); - } - - /// - /// Returns the first HilightEntry that matches the given line - /// - /// - /// - /// - public HilightEntry FindHighlightEntry(ITextValue line, bool noWordMatches) - { - // first check the temp entries - lock (_tempHighlightEntryListLock) - { - foreach (HilightEntry entry in _tempHighlightEntryList) - { - if (noWordMatches && entry.IsWordMatch) - { - continue; - } - if (CheckHighlightEntryMatch(entry, line)) - { - return entry; - } - } - } - - lock (_currentHighlightGroupLock) - { - foreach (HilightEntry entry in _currentHighlightGroup.HilightEntryList) - { - if (noWordMatches && entry.IsWordMatch) - { - continue; - } - if (CheckHighlightEntryMatch(entry, line)) - { - return entry; - } - } - return null; - } - } - - public IList FindHighlightMatches(ITextValue column) - { - IList resultList = new List(); - if (column != null) - { - lock (_currentHighlightGroupLock) - { - GetHighlightEntryMatches(column, _currentHighlightGroup.HilightEntryList, resultList); - } - lock (_tempHighlightEntryList) - { - GetHighlightEntryMatches(column, _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 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); - SearchParams searchParams = _parentLogTabWin.SearchParams; - - if ((searchParams.isForward || searchParams.isFindNext) && !searchParams.isShiftF3Pressed) - { - searchParams.currentLine = dataGridView.CurrentCellAddress.Y + 1; - } - else - { - searchParams.currentLine = 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)); - int 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 (int 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: - { - int 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: - { - int 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; - - int firstLine = dataGridView.FirstDisplayedScrollingRowIndex; - if (firstLine < 0) - { - return; - } - - firstLine -= OVERSCAN; - if (firstLine < 0) - { - firstLine = 0; - } - - int oversizeCount = OVERSCAN; - - for (int i = firstLine; i < dataGridView.RowCount; ++i) - { - if (!dataGridView.Rows[i].Displayed && i > dataGridView.FirstDisplayedScrollingRowIndex) - { - if (oversizeCount-- < 0) - { - break; - } - } - if (_bookmarkProvider.IsBookmarkAtLine(i)) - { - Bookmark bookmark = _bookmarkProvider.GetBookmarkForLine(i); - if (bookmark.Text.Length > 0) - { - //BookmarkOverlay overlay = new BookmarkOverlay(); - BookmarkOverlay 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; - int heightSum = 0; - if (dataGridView.FirstDisplayedScrollingRowIndex < i) - { - for (int 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 (int 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={0}, width={1}, scroll_offset={2}", r.Location.X, r.Width, 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() - { - DataGridView 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)) - { - Bookmark 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) - { - ILogLine line = _logFileReader.GetLogLine(lineNum); - if (line == null) - { - return; - } - ParamParser 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) - { - int index = FindNextBookmarkIndex(_filterResultList[filterGridView.CurrentCellAddress.Y]); - int startIndex = index; - bool wrapped = false; - while (true) - { - int lineNum = _bookmarkProvider.Bookmarks[index].LineNum; - if (_filterResultList.Contains(lineNum)) - { - int 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 - { - int index = FindNextBookmarkIndex(dataGridView.CurrentCellAddress.Y); - if (index > _bookmarkProvider.Bookmarks.Count - 1) - { - index = 0; - } - - int 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--; - int index = FindPrevBookmarkIndex(_filterResultList[filterGridView.CurrentCellAddress.Y]); - if (index < 0) - { - index = _bookmarkProvider.Bookmarks.Count - 1; - } - int startIndex = index; - bool wrapped = false; - while (true) - { - int lineNum = _bookmarkProvider.Bookmarks[index].LineNum; - if (_filterResultList.Contains(lineNum)) - { - int 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 - { - int index = FindPrevBookmarkIndex(dataGridView.CurrentCellAddress.Y); - if (index < 0) - { - index = _bookmarkProvider.Bookmarks.Count - 1; - } - - int lineNum = _bookmarkProvider.Bookmarks[index].LineNum; - SelectLine(lineNum, false, true); - } - } - } - - public void DeleteBookmarks(List lineNumList) - { - bool bookmarksPresent = false; - foreach (int 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 - { - string text = _guiStateArgs.TimeshiftText; - if (text.StartsWith("+")) - { - text = text.Substring(1); - } - TimeSpan timeSpan = TimeSpan.Parse(text); - int 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) - { - List 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 - FilterPipe pipe = new FilterPipe(new FilterParams(), this); - pipe.IsStopped = true; - WritePipeToTab(pipe, lineNumList, Text + "->C", null); - } - else - { - string fileName = Path.GetTempFileName(); - FileStream fStream = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read); - StreamWriter writer = new StreamWriter(fStream, Encoding.Unicode); - - DataObject data = dataGridView.GetClipboardContent(); - string text = data.GetText(TextDataFormat.Text); - writer.Write(text); - - writer.Close(); - string 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(); - _reloadMemento.currentLine = dataGridView.CurrentCellAddress.Y; - _reloadMemento.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(Preferences newPreferences, bool isLoadTime, SettingsFlags flags) - { - if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) - { - NormalFont = new Font(new FontFamily(newPreferences.fontName), newPreferences.fontSize); - BoldFont = new Font(NormalFont, FontStyle.Bold); - MonospacedFont = new Font("Courier New", Preferences.fontSize, FontStyle.Bold); - - int lineSpacing = NormalFont.FontFamily.GetLineSpacing(FontStyle.Regular); - float 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, newPreferences); - ApplyDataGridViewPrefs(filterGridView, newPreferences); - - 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) - { - bool hasScrolled = false; - if (!CurrentColumnizer.IsTimeshiftImplemented() || dataGridView.RowCount == 0) - { - return false; - } - - //this.Cursor = Cursors.WaitCursor; - int currentLine = dataGridView.CurrentCellAddress.Y; - if (currentLine < 0 || currentLine >= dataGridView.RowCount) - { - currentLine = 0; - } - int 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) - { - int foundLine = - FindTimestampLine_Internal(lineNum, 0, dataGridView.RowCount - 1, timestamp, roundToSeconds); - if (foundLine >= 0) - { - // go backwards to the first occurence of the hit - DateTime 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); - int refLine = lineNum; - DateTime 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); - if (currentTimestamp.CompareTo(timestamp) == 0) - { - return rangeEnd; - } - return -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({0}) enter", lineNum); - DateTime timeStamp = DateTime.MinValue; - bool lookBack = false; - if (lineNum >= 0 && lineNum < dataGridView.RowCount) - { - while (timeStamp.CompareTo(DateTime.MinValue) == 0 && lineNum >= 0) - { - if (_isTimestampDisplaySyncing && _shouldTimestampDisplaySyncingCancel) - { - return DateTime.MinValue; - } - lookBack = true; - ILogLine 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; - } - - DateTime timeStamp = DateTime.MinValue; - bool lookFwd = false; - if (lineNum >= 0 && lineNum < dataGridView.RowCount) - { - while (timeStamp.CompareTo(DateTime.MinValue) == 0 && lineNum < dataGridView.RowCount) - { - lookFwd = true; - ILogLine 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() - { - int 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 = new List(); - foreach (DataGridViewRow row in dataGridView.SelectedRows) - { - if (row.Index != -1) - { - lineNumList.Add(row.Index); - } - } - lineNumList.Sort(); - patternArgs.startLine = lineNumList[0]; - patternArgs.endLine = lineNumList[lineNumList.Count - 1]; - } - else - { - if (dataGridView.CurrentCellAddress.Y != -1) - { - patternArgs.startLine = dataGridView.CurrentCellAddress.Y; - } - else - { - patternArgs.startLine = 0; - } - patternArgs.endLine = dataGridView.RowCount - 1; - } - } - - public void PatternStatistic(PatternArgs patternArgs) - { - PatternStatisticFx fx = new PatternStatisticFx(TestStatistic); - fx.BeginInvoke(patternArgs, null, null); - } - - public void ExportBookmarkList() - { - SaveFileDialog dlg = new SaveFileDialog(); - dlg.Title = "Choose a file to save bookmarks into"; - dlg.AddExtension = true; - dlg.DefaultExt = "csv"; - dlg.Filter = "CSV file (*.csv)|*.csv|Bookmark file (*.bmk)|*.bmk"; - dlg.FilterIndex = 1; - dlg.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 OpenFileDialog(); - dlg.Title = "Choose a file to load bookmarks from"; - dlg.AddExtension = true; - dlg.DefaultExt = "csv"; - dlg.DefaultExt = "csv"; - dlg.Filter = "CSV file (*.csv)|*.csv|Bookmark file (*.bmk)|*.bmk"; - dlg.FilterIndex = 1; - dlg.FileName = Path.GetFileNameWithoutExtension(FileName); - if (dlg.ShowDialog() == DialogResult.OK) - { - try - { - // add to the existing bookmarks - SortedList newBookmarks = new SortedList(); - BookmarkExporter.ImportBookmarkList(FileName, dlg.FileName, newBookmarks); - - // Add (or replace) to existing bookmark list - bool bookmarkAdded = false; - foreach (Bookmark 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 - { - Bookmark 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() - { - int index = filterListBox.SelectedIndex; - filterListBox.Items.Clear(); - foreach (FilterParams 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); - if (_currentHighlightGroup == null) - { - if (_parentLogTabWin.HilightGroupList.Count > 0) - { - _currentHighlightGroup = _parentLogTabWin.HilightGroupList[0]; - } - else - { - _currentHighlightGroup = new HilightGroup(); - } - } - _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 {0} to {1}", Util.GetNameFromPath(FileName), 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 {0}", Util.GetNameFromPath(FileName)); - TimeSyncList.WindowRemoved -= OnTimeSyncListWindowRemoved; - TimeSyncList.RemoveWindow(this); - TimeSyncList = null; - } - } - OnSyncModeChanged(); - } - - public void RefreshLogView() - { - RefreshAllGrids(); - } - - #endregion - } -} diff --git a/src/LogExpert/Controls/PatternWindow.cs b/src/LogExpert/Controls/PatternWindow.cs deleted file mode 100644 index d0c3b28d..00000000 --- a/src/LogExpert/Controls/PatternWindow.cs +++ /dev/null @@ -1,359 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; -using LogExpert.Classes; -using LogExpert.Entities.EventArgs; - -namespace LogExpert.Controls -{ - internal partial class PatternWindow : Form - { - #region Fields - - private readonly List> blockList = []; - private PatternBlock currentBlock; - private List currentList; - - private readonly LogWindow.LogWindow logWindow; - private PatternArgs patternArgs = new(); - - #endregion - - #region cTor - - public PatternWindow() - { - InitializeComponent(); - } - - public PatternWindow(LogWindow.LogWindow logWindow) - { - this.logWindow = logWindow; - InitializeComponent(); - this.recalcButton.Enabled = false; - } - - #endregion - - #region Properties - - public int Fuzzy - { - set { this.fuzzyKnobControl.Value = value; } - get { return this.fuzzyKnobControl.Value; } - } - - public int MaxDiff - { - set { this.maxDiffKnobControl.Value = value; } - get { return this.maxDiffKnobControl.Value; } - } - - public int MaxMisses - { - set { this.maxMissesKnobControl.Value = value; } - get { return this.maxMissesKnobControl.Value; } - } - - public int Weight - { - set { this.weigthKnobControl.Value = value; } - get { return this.weigthKnobControl.Value; } - } - - #endregion - - #region Public methods - - public void SetBlockList(List flatBlockList, PatternArgs patternArgs) - { - this.patternArgs = patternArgs; - blockList.Clear(); - List singeList = []; - //int blockId = -1; - for (int i = 0; i < flatBlockList.Count; ++i) - { - PatternBlock block = flatBlockList[i]; - singeList.Add(block); - //if (block.blockId != blockId) - //{ - // singeList = new List(); - // PatternBlock selfRefBlock = new PatternBlock(); - // selfRefBlock.targetStart = block.startLine; - // selfRefBlock.targetEnd = block.endLine; - // selfRefBlock.blockId = block.blockId; - // singeList.Add(selfRefBlock); - // singeList.Add(block); - // this.blockList.Add(singeList); - // blockId = block.blockId; - //} - //else - //{ - // singeList.Add(block); - //} - } - this.blockList.Add(singeList); - this.Invoke(new MethodInvoker(SetBlockListGuiStuff)); - } - - - public void SetColumnizer(ILogLineColumnizer columnizer) - { - this.logWindow.SetColumnizer(columnizer, this.patternHitsDataGridView); - this.logWindow.SetColumnizer(columnizer, this.contentDataGridView); - this.patternHitsDataGridView.Columns[0].Width = 20; - this.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; - - this.patternHitsDataGridView.Columns.Insert(1, blockInfoColumn); - this.contentDataGridView.Columns.Insert(1, contentInfoColumn); - } - - public void SetFont(string fontName, float fontSize) - { - Font font = new(new FontFamily(fontName), fontSize); - int lineSpacing = font.FontFamily.GetLineSpacing(FontStyle.Regular); - float lineSpacingPixel = font.Size * lineSpacing / font.FontFamily.GetEmHeight(FontStyle.Regular); - - this.patternHitsDataGridView.DefaultCellStyle.Font = font; - this.contentDataGridView.DefaultCellStyle.Font = font; - //this.lineHeight = font.Height + 4; - this.patternHitsDataGridView.RowTemplate.Height = font.Height + 4; - this.contentDataGridView.RowTemplate.Height = font.Height + 4; - } - - #endregion - - #region Private Methods - - private void SetBlockListGuiStuff() - { - this.patternHitsDataGridView.RowCount = 0; - this.blockCountLabel.Text = "0"; - this.contentDataGridView.RowCount = 0; - this.blockLinesLabel.Text = "0"; - this.recalcButton.Enabled = true; - this.setRangeButton.Enabled = true; - if (this.blockList.Count > 0) - { - SetCurrentList(this.blockList[0]); - } - } - - private void SetCurrentList(List patternList) - { - this.patternHitsDataGridView.RowCount = 0; - this.currentList = patternList; - this.patternHitsDataGridView.RowCount = this.currentList.Count; - this.patternHitsDataGridView.Refresh(); - this.blockCountLabel.Text = "" + this.currentList.Count; - } - - private int GetLineForHitGrid(int rowIndex) - { - int line; - line = currentList[rowIndex].targetStart; - return line; - } - - private int GetLineForContentGrid(int rowIndex) - { - int line; - line = currentBlock.targetStart + rowIndex; - return line; - } - - #endregion - - #region Events handler - - private void patternHitsDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) - { - if (this.currentList == null || e.RowIndex < 0) - { - return; - } - int rowIndex = GetLineForHitGrid(e.RowIndex); - int colIndex = e.ColumnIndex; - if (colIndex == 1) - { - e.Value = currentList[e.RowIndex].weigth; - } - else - { - if (colIndex > 1) - { - colIndex--; // correct the additional inserted col - } - e.Value = this.logWindow.GetCellValue(rowIndex, colIndex); - } - } - - private void patternHitsDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) - { - if (this.currentList == null || e.RowIndex < 0) - { - return; - } - if (e.ColumnIndex == 1) - { - e.PaintBackground(e.CellBounds, false); - int selCount = this.patternArgs.endLine - this.patternArgs.startLine; - int maxWeight = this.patternArgs.maxDiffInBlock * selCount + selCount; - if (maxWeight > 0) - { - int width = (int) ((double) (int) e.Value / (double) maxWeight * (double) e.CellBounds.Width); - Rectangle rect = new(e.CellBounds.X, e.CellBounds.Y, width, e.CellBounds.Height); - int alpha = 90 + (int) ((double) (int) e.Value / (double) maxWeight * (double) 165); - Color color = Color.FromArgb(alpha, 170, 180, 150); - Brush brush = new SolidBrush(color); - rect.Inflate(-2, -1); - e.Graphics.FillRectangle(brush, rect); - brush.Dispose(); - } - e.PaintContent(e.CellBounds); - e.Handled = true; - } - else - { - DataGridView gridView = (DataGridView) sender; - int rowIndex = GetLineForHitGrid(e.RowIndex); - this.logWindow.CellPainting(gridView, rowIndex, e); - } - } - - private void patternHitsDataGridView_MouseDoubleClick(object sender, MouseEventArgs e) - { - //if (this.currentList == null || patternHitsDataGridView.CurrentRow == null) - // return; - //int rowIndex = GetLineForHitGrid(patternHitsDataGridView.CurrentRow.Index); - - //this.logWindow.SelectLogLine(rowIndex); - } - - private void patternHitsDataGridView_CurrentCellChanged(object sender, EventArgs e) - { - if (this.currentList == null || patternHitsDataGridView.CurrentRow == null) - { - return; - } - if (patternHitsDataGridView.CurrentRow.Index > this.currentList.Count - 1) - { - return; - } - this.contentDataGridView.RowCount = 0; - this.currentBlock = this.currentList[patternHitsDataGridView.CurrentRow.Index]; - this.contentDataGridView.RowCount = this.currentBlock.targetEnd - this.currentBlock.targetStart + 1; - this.contentDataGridView.Refresh(); - this.contentDataGridView.CurrentCell = this.contentDataGridView.Rows[0].Cells[0]; - this.blockLinesLabel.Text = "" + this.contentDataGridView.RowCount; - } - - private void contentDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) - { - if (this.currentBlock == null || e.RowIndex < 0) - { - return; - } - int rowIndex = GetLineForContentGrid(e.RowIndex); - int colIndex = e.ColumnIndex; - if (colIndex == 1) - { - QualityInfo qi; - if (this.currentBlock.qualityInfoList.TryGetValue(rowIndex, out qi)) - { - e.Value = qi.quality; - } - else - { - e.Value = ""; - } - } - else - { - if (colIndex != 0) - { - colIndex--; // adjust the inserted column - } - e.Value = this.logWindow.GetCellValue(rowIndex, colIndex); - } - } - - private void contentDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) - { - if (this.currentBlock == null || e.RowIndex < 0) - { - return; - } - DataGridView gridView = (DataGridView) sender; - int rowIndex = GetLineForContentGrid(e.RowIndex); - this.logWindow.CellPainting(gridView, rowIndex, e); - } - - private void contentDataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) - { - if (this.currentBlock == null || contentDataGridView.CurrentRow == null) - { - return; - } - int rowIndex = GetLineForContentGrid(contentDataGridView.CurrentRow.Index); - - this.logWindow.SelectLogLine(rowIndex); - } - - private void recalcButton_Click(object sender, EventArgs e) - { - patternArgs.fuzzy = this.fuzzyKnobControl.Value; - patternArgs.maxDiffInBlock = this.maxDiffKnobControl.Value; - patternArgs.maxMisses = this.maxMissesKnobControl.Value; - patternArgs.minWeight = this.weigthKnobControl.Value; - this.logWindow.PatternStatistic(patternArgs); - this.recalcButton.Enabled = false; - this.setRangeButton.Enabled = false; - } - - private void closeButton_Click(object sender, EventArgs e) - { - Close(); - } - - private void contentDataGridView_ColumnDividerDoubleClick(object sender, - DataGridViewColumnDividerDoubleClickEventArgs e) - { - e.Handled = true; - this.contentDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - } - - private void patternHitsDataGridView_ColumnDividerDoubleClick(object sender, - DataGridViewColumnDividerDoubleClickEventArgs e) - { - e.Handled = true; - this.patternHitsDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - } - - private void setRangeButton_Click(object sender, EventArgs e) - { - this.logWindow.PatternStatisticSelectRange(patternArgs); - this.recalcButton.Enabled = true; - this.rangeLabel.Text = "Start: " + patternArgs.startLine + "\r\nEnd: " + patternArgs.endLine; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/AboutBox.Designer.cs b/src/LogExpert/Dialogs/AboutBox.Designer.cs deleted file mode 100644 index f8bf20b6..00000000 --- a/src/LogExpert/Dialogs/AboutBox.Designer.cs +++ /dev/null @@ -1,203 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class AboutBox - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); - logoPictureBox = new System.Windows.Forms.PictureBox(); - labelProductName = new System.Windows.Forms.Label(); - labelVersion = new System.Windows.Forms.Label(); - labelCopyright = new System.Windows.Forms.Label(); - textBoxDescription = new System.Windows.Forms.TextBox(); - linkLabelURL = new System.Windows.Forms.LinkLabel(); - panel1 = new System.Windows.Forms.Panel(); - okButton = new System.Windows.Forms.Button(); - tableLayoutPanel.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)logoPictureBox).BeginInit(); - panel1.SuspendLayout(); - SuspendLayout(); - // - // tableLayoutPanel - // - tableLayoutPanel.ColumnCount = 2; - tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 34.25484F)); - tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 65.74516F)); - tableLayoutPanel.Controls.Add(logoPictureBox, 0, 0); - tableLayoutPanel.Controls.Add(labelProductName, 1, 0); - tableLayoutPanel.Controls.Add(labelVersion, 1, 1); - tableLayoutPanel.Controls.Add(labelCopyright, 1, 2); - tableLayoutPanel.Controls.Add(textBoxDescription, 1, 4); - tableLayoutPanel.Controls.Add(linkLabelURL, 1, 3); - tableLayoutPanel.Controls.Add(panel1, 1, 5); - tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; - tableLayoutPanel.Location = new System.Drawing.Point(14, 14); - tableLayoutPanel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tableLayoutPanel.Name = "tableLayoutPanel"; - tableLayoutPanel.RowCount = 6; - tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.912043F)); - tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.912043F)); - tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 9.47226F)); - tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 11.84032F)); - tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 46.68471F)); - tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 12.17862F)); - tableLayoutPanel.Size = new System.Drawing.Size(914, 649); - tableLayoutPanel.TabIndex = 0; - // - // logoPictureBox - // - logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill; - logoPictureBox.Image = Properties.Resources.LogLover; - logoPictureBox.Location = new System.Drawing.Point(4, 5); - logoPictureBox.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - logoPictureBox.Name = "logoPictureBox"; - tableLayoutPanel.SetRowSpan(logoPictureBox, 6); - logoPictureBox.Size = new System.Drawing.Size(305, 639); - logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; - logoPictureBox.TabIndex = 12; - logoPictureBox.TabStop = false; - // - // labelProductName - // - labelProductName.Dock = System.Windows.Forms.DockStyle.Fill; - labelProductName.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, 0); - labelProductName.Location = new System.Drawing.Point(322, 0); - labelProductName.Margin = new System.Windows.Forms.Padding(9, 0, 4, 0); - labelProductName.MaximumSize = new System.Drawing.Size(0, 26); - labelProductName.Name = "labelProductName"; - labelProductName.Size = new System.Drawing.Size(588, 26); - labelProductName.TabIndex = 19; - labelProductName.Text = "Product Name"; - labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // labelVersion - // - labelVersion.Dock = System.Windows.Forms.DockStyle.Fill; - labelVersion.Location = new System.Drawing.Point(322, 64); - labelVersion.Margin = new System.Windows.Forms.Padding(9, 0, 4, 0); - labelVersion.MaximumSize = new System.Drawing.Size(0, 26); - labelVersion.Name = "labelVersion"; - labelVersion.Size = new System.Drawing.Size(588, 26); - labelVersion.TabIndex = 0; - labelVersion.Text = "Version"; - labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // labelCopyright - // - labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill; - labelCopyright.Location = new System.Drawing.Point(322, 128); - labelCopyright.Margin = new System.Windows.Forms.Padding(9, 0, 4, 0); - labelCopyright.Name = "labelCopyright"; - labelCopyright.Size = new System.Drawing.Size(588, 61); - labelCopyright.TabIndex = 21; - labelCopyright.Text = "Copyright"; - labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // textBoxDescription - // - textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill; - textBoxDescription.Location = new System.Drawing.Point(322, 270); - textBoxDescription.Margin = new System.Windows.Forms.Padding(9, 5, 4, 5); - textBoxDescription.Multiline = true; - textBoxDescription.Name = "textBoxDescription"; - textBoxDescription.ReadOnly = true; - textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both; - textBoxDescription.Size = new System.Drawing.Size(588, 292); - textBoxDescription.TabIndex = 23; - textBoxDescription.TabStop = false; - textBoxDescription.Text = "Description"; - // - // linkLabelURL - // - linkLabelURL.AutoSize = true; - linkLabelURL.Dock = System.Windows.Forms.DockStyle.Fill; - linkLabelURL.Location = new System.Drawing.Point(317, 189); - linkLabelURL.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - linkLabelURL.Name = "linkLabelURL"; - linkLabelURL.Size = new System.Drawing.Size(593, 76); - linkLabelURL.TabIndex = 25; - linkLabelURL.TabStop = true; - linkLabelURL.Text = "https://github.com/LogExperts/LogExpert"; - linkLabelURL.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - linkLabelURL.LinkClicked += OnLinkLabelURLClicked; - // - // panel1 - // - panel1.Controls.Add(okButton); - panel1.Dock = System.Windows.Forms.DockStyle.Fill; - panel1.Location = new System.Drawing.Point(317, 572); - panel1.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - panel1.Name = "panel1"; - panel1.Size = new System.Drawing.Size(593, 72); - panel1.TabIndex = 26; - // - // okButton - // - okButton.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - okButton.Location = new System.Drawing.Point(475, 32); - okButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - okButton.Name = "okButton"; - okButton.Size = new System.Drawing.Size(114, 35); - okButton.TabIndex = 0; - okButton.Text = "&OK"; - okButton.UseVisualStyleBackColor = true; - // - // AboutBox - // - ClientSize = new System.Drawing.Size(942, 677); - Controls.Add(tableLayoutPanel); - FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - MaximizeBox = false; - MinimizeBox = false; - Name = "AboutBox"; - Padding = new System.Windows.Forms.Padding(14); - ShowIcon = false; - ShowInTaskbar = false; - StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - Text = "AboutBox"; - tableLayoutPanel.ResumeLayout(false); - tableLayoutPanel.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)logoPictureBox).EndInit(); - panel1.ResumeLayout(false); - ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.TableLayoutPanel tableLayoutPanel; - private System.Windows.Forms.PictureBox logoPictureBox; - private System.Windows.Forms.Label labelProductName; - private System.Windows.Forms.Label labelVersion; - private System.Windows.Forms.Label labelCopyright; - private System.Windows.Forms.TextBox textBoxDescription; - private System.Windows.Forms.LinkLabel linkLabelURL; - private System.Windows.Forms.Panel panel1; - private System.Windows.Forms.Button okButton; - } -} diff --git a/src/LogExpert/Dialogs/AboutBox.cs b/src/LogExpert/Dialogs/AboutBox.cs deleted file mode 100644 index 77663d42..00000000 --- a/src/LogExpert/Dialogs/AboutBox.cs +++ /dev/null @@ -1,132 +0,0 @@ -using System.Diagnostics; -using System.IO; -using System.Reflection; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - internal partial class AboutBox : Form - { - #region Fields - - private readonly Assembly _assembly; - - #endregion - - #region cTor - - public AboutBox() - { - InitializeComponent(); - - _assembly = Assembly.GetExecutingAssembly(); - - Text = $@"About {AssemblyTitle}"; - labelProductName.Text = AssemblyProduct; - labelVersion.Text = AssemblyVersion; - labelCopyright.Text = AssemblyCopyright; - //this.labelCompanyName.Text = AssemblyCompany; - textBoxDescription.Text = AssemblyDescription + - "\r\n\r\nCredits:\r\n\r\n" + - "DockPanel control (c) 2007 Weifen Luo \r\n" + - "Early bird test: Mathias Dräger\r\n" + - "\r\n" + - "LogExpert uses modules from:\r\n" + - "http://sourceforge.net/projects/dockpanelsuite/\r\n" + - "http://www.xml-rpc.net/"; - string link = "https://github.com/LogExperts/LogExpert"; - linkLabelURL.Links.Add(new LinkLabel.Link(0, link.Length, link)); - } - - #endregion - - #region Properties - - public string AssemblyTitle - { - get - { - object[] attributes = _assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false); - if (attributes.Length > 0) - { - AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0]; - if (titleAttribute.Title != "") - { - return titleAttribute.Title; - } - } - return Path.GetFileNameWithoutExtension(_assembly.Location); - } - } - - public string AssemblyVersion - { - get - { - AssemblyName assembly = _assembly.GetName(); - string version = $"{assembly.Version.Major}.{assembly.Version.Minor}.{assembly.Version.Build}.{assembly.Version.Revision}"; - if (assembly.Version.Revision >= 9000) - { - version += " Testrelease"; - } - - return version; - } - } - - public string AssemblyDescription - { - get - { - object[] attributes = _assembly.GetCustomAttributes(typeof(AssemblyDescriptionAttribute), false); - if (attributes.Length == 0) - { - return string.Empty; - } - return ((AssemblyDescriptionAttribute)attributes[0]).Description; - } - } - - public string AssemblyProduct - { - get - { - object[] attributes = _assembly.GetCustomAttributes(typeof(AssemblyProductAttribute), false); - if (attributes.Length == 0) - { - return string.Empty; - } - return ((AssemblyProductAttribute)attributes[0]).Product; - } - } - - public string AssemblyCopyright - { - get - { - object[] attributes = _assembly.GetCustomAttributes(typeof(AssemblyCopyrightAttribute), false); - if (attributes.Length == 0) - { - return string.Empty; - } - return ((AssemblyCopyrightAttribute)attributes[0]).Copyright; - } - } - - #endregion - - #region Events handler - - private void OnLinkLabelURLClicked(object sender, LinkLabelLinkClickedEventArgs e) - { - string target = e.Link.LinkData as string; - Process.Start(new ProcessStartInfo - { - UseShellExecute = true, - FileName = target, - }); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/AllowOnlyOneInstanceErrorDialog.Designer.cs b/src/LogExpert/Dialogs/AllowOnlyOneInstanceErrorDialog.Designer.cs deleted file mode 100644 index e9f7f27f..00000000 --- a/src/LogExpert/Dialogs/AllowOnlyOneInstanceErrorDialog.Designer.cs +++ /dev/null @@ -1,100 +0,0 @@ - -namespace LogExpert.Dialogs -{ - partial class AllowOnlyOneInstanceErrorDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.checkBoxIgnoreMessage = new System.Windows.Forms.CheckBox(); - this.buttonOk = new System.Windows.Forms.Button(); - this.labelErrorText = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // checkBoxIgnoreMessage - // - this.checkBoxIgnoreMessage.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.checkBoxIgnoreMessage.AutoSize = true; - this.checkBoxIgnoreMessage.Location = new System.Drawing.Point(9, 56); - this.checkBoxIgnoreMessage.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); - this.checkBoxIgnoreMessage.Name = "checkBoxIgnoreMessage"; - this.checkBoxIgnoreMessage.Size = new System.Drawing.Size(177, 17); - this.checkBoxIgnoreMessage.TabIndex = 0; - this.checkBoxIgnoreMessage.Text = "Show this message only once\\?"; - this.checkBoxIgnoreMessage.UseVisualStyleBackColor = true; - // - // buttonOk - // - this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(209, 53); - this.buttonOk.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(74, 23); - this.buttonOk.TabIndex = 1; - this.buttonOk.Text = "Ok"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); - // - // labelErrorText - // - this.labelErrorText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.labelErrorText.AutoEllipsis = true; - this.labelErrorText.Location = new System.Drawing.Point(9, 8); - this.labelErrorText.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); - this.labelErrorText.Name = "labelErrorText"; - this.labelErrorText.Size = new System.Drawing.Size(273, 43); - this.labelErrorText.TabIndex = 2; - this.labelErrorText.Text = "Only one instance allowed, uncheck \\\"View Settings => Allow only 1 Instances\\\" to" + - " start multiple instances!"; - // - // AllowOnlyOneInstanceErrorDialog - // - this.ClientSize = new System.Drawing.Size(293, 84); - this.Controls.Add(this.labelErrorText); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.checkBoxIgnoreMessage); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2); - this.MaximizeBox = false; - this.Name = "AllowOnlyOneInstanceErrorDialog"; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; - this.Text = "AllowOnlyOneInstanceErrorDialog"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.CheckBox checkBoxIgnoreMessage; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Label labelErrorText; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/AllowOnlyOneInstanceErrorDialog.cs b/src/LogExpert/Dialogs/AllowOnlyOneInstanceErrorDialog.cs deleted file mode 100644 index 2c2c29f1..00000000 --- a/src/LogExpert/Dialogs/AllowOnlyOneInstanceErrorDialog.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class AllowOnlyOneInstanceErrorDialog : Form - { - public bool DoNotShowThisMessageAgain { get; private set; } - - public AllowOnlyOneInstanceErrorDialog() - { - InitializeComponent(); - SetText(); - } - - private void SetText() - { - labelErrorText.Text = @"Only one instance allowed, uncheck ""View Settings => Allow only 1 Instances"" to start multiple instances!"; - } - - private void OnButtonOkClick(object sender, System.EventArgs e) - { - DoNotShowThisMessageAgain = checkBoxIgnoreMessage.Checked; - } - } -} diff --git a/src/LogExpert/Dialogs/BookmarkCommentDlg.Designer.cs b/src/LogExpert/Dialogs/BookmarkCommentDlg.Designer.cs deleted file mode 100644 index fbb61e1f..00000000 --- a/src/LogExpert/Dialogs/BookmarkCommentDlg.Designer.cs +++ /dev/null @@ -1,90 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class BookmarkCommentDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BookmarkCommentDlg)); - this.okButton = new System.Windows.Forms.Button(); - this.cancelButton = new System.Windows.Forms.Button(); - this.commentTextBox = new System.Windows.Forms.TextBox(); - this.SuspendLayout(); - // - // okButton - // - this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okButton.Location = new System.Drawing.Point(150, 86); - this.okButton.Name = "okButton"; - this.okButton.Size = new System.Drawing.Size(75, 23); - this.okButton.TabIndex = 1; - this.okButton.Text = "OK"; - this.okButton.UseVisualStyleBackColor = true; - // - // cancelButton - // - this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(241, 86); - this.cancelButton.Name = "cancelButton"; - this.cancelButton.Size = new System.Drawing.Size(75, 23); - this.cancelButton.TabIndex = 2; - this.cancelButton.Text = "&Cancel"; - this.cancelButton.UseVisualStyleBackColor = true; - // - // commentTextBox - // - this.commentTextBox.Dock = System.Windows.Forms.DockStyle.Top; - this.commentTextBox.Location = new System.Drawing.Point(0, 0); - this.commentTextBox.Multiline = true; - this.commentTextBox.Name = "commentTextBox"; - this.commentTextBox.Size = new System.Drawing.Size(324, 80); - this.commentTextBox.TabIndex = 0; - // - // BookmarkCommentDlg - // - this.AcceptButton = this.okButton; - this.CancelButton = this.cancelButton; - this.ClientSize = new System.Drawing.Size(324, 115); - this.Controls.Add(this.commentTextBox); - this.Controls.Add(this.cancelButton); - this.Controls.Add(this.okButton); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.Name = "BookmarkCommentDlg"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "Bookmark comment"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button okButton; - private System.Windows.Forms.Button cancelButton; - private System.Windows.Forms.TextBox commentTextBox; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/BookmarkCommentDlg.cs b/src/LogExpert/Dialogs/BookmarkCommentDlg.cs deleted file mode 100644 index bc533cfb..00000000 --- a/src/LogExpert/Dialogs/BookmarkCommentDlg.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class BookmarkCommentDlg : Form - { - #region cTor - - public BookmarkCommentDlg() - { - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - InitializeComponent(); - } - - #endregion - - #region Properties - - public string Comment - { - set => commentTextBox.Text = value; - get => commentTextBox.Text; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/BookmarkWindow.Designer.cs b/src/LogExpert/Dialogs/BookmarkWindow.Designer.cs deleted file mode 100644 index e0931cdd..00000000 --- a/src/LogExpert/Dialogs/BookmarkWindow.Designer.cs +++ /dev/null @@ -1,196 +0,0 @@ -namespace LogExpert.Dialogs { - partial class BookmarkWindow { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) { - if (disposing && (components != null)) { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() { - this.components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BookmarkWindow)); - this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); - this.deleteBookmarkssToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.removeCommentsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); - this.bookmarkTextBox = new System.Windows.Forms.TextBox(); - this.splitContainer1 = new System.Windows.Forms.SplitContainer(); - this.bookmarkDataGridView = new LogExpert.Dialogs.BufferedDataGridView(); - this.commentColumnCheckBox = new System.Windows.Forms.CheckBox(); - this.label1 = new System.Windows.Forms.Label(); - this.contextMenuStrip1.SuspendLayout(); - this.splitContainer1.Panel1.SuspendLayout(); - this.splitContainer1.Panel2.SuspendLayout(); - this.splitContainer1.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)(this.bookmarkDataGridView)).BeginInit(); - this.SuspendLayout(); - // - // contextMenuStrip1 - // - this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { - this.deleteBookmarkssToolStripMenuItem, - this.removeCommentsToolStripMenuItem}); - this.contextMenuStrip1.Name = "contextMenuStrip1"; - this.contextMenuStrip1.Size = new System.Drawing.Size(186, 48); - // - // deleteBookmarkssToolStripMenuItem - // - 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); - // - // 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); - // - // bookmarkTextBox - // - this.bookmarkTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.bookmarkTextBox.Location = new System.Drawing.Point(0, 20); - this.bookmarkTextBox.Multiline = true; - this.bookmarkTextBox.Name = "bookmarkTextBox"; - 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); - // - // splitContainer1 - // - this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill; - this.splitContainer1.Location = new System.Drawing.Point(0, 0); - this.splitContainer1.Name = "splitContainer1"; - // - // splitContainer1.Panel1 - // - this.splitContainer1.Panel1.Controls.Add(this.bookmarkDataGridView); - this.splitContainer1.Panel1MinSize = 40; - // - // splitContainer1.Panel2 - // - this.splitContainer1.Panel2.Controls.Add(this.commentColumnCheckBox); - this.splitContainer1.Panel2.Controls.Add(this.label1); - this.splitContainer1.Panel2.Controls.Add(this.bookmarkTextBox); - this.splitContainer1.Size = new System.Drawing.Size(717, 158); - this.splitContainer1.SplitterDistance = 517; - this.splitContainer1.TabIndex = 7; - // - // bookmarkDataGridView - // - this.bookmarkDataGridView.AllowUserToAddRows = false; - this.bookmarkDataGridView.AllowUserToDeleteRows = false; - this.bookmarkDataGridView.AllowUserToOrderColumns = true; - this.bookmarkDataGridView.AllowUserToResizeRows = false; - this.bookmarkDataGridView.BackgroundColor = System.Drawing.SystemColors.Window; - this.bookmarkDataGridView.BorderStyle = System.Windows.Forms.BorderStyle.None; - this.bookmarkDataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; - this.bookmarkDataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - this.bookmarkDataGridView.ContextMenuStrip = this.contextMenuStrip1; - this.bookmarkDataGridView.Dock = System.Windows.Forms.DockStyle.Fill; - this.bookmarkDataGridView.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; - this.bookmarkDataGridView.EditModeMenuStrip = null; - this.bookmarkDataGridView.Location = new System.Drawing.Point(0, 0); - this.bookmarkDataGridView.Margin = new System.Windows.Forms.Padding(0); - this.bookmarkDataGridView.Name = "bookmarkDataGridView"; - this.bookmarkDataGridView.PaintWithOverlays = false; - this.bookmarkDataGridView.ReadOnly = true; - this.bookmarkDataGridView.RowHeadersVisible = false; - this.bookmarkDataGridView.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; - 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); - // - // commentColumnCheckBox - // - this.commentColumnCheckBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.commentColumnCheckBox.AutoSize = true; - this.commentColumnCheckBox.Location = new System.Drawing.Point(7, 138); - this.commentColumnCheckBox.Name = "commentColumnCheckBox"; - this.commentColumnCheckBox.Size = new System.Drawing.Size(136, 17); - this.commentColumnCheckBox.TabIndex = 8; - this.commentColumnCheckBox.Text = "Show comment column"; - this.commentColumnCheckBox.UseVisualStyleBackColor = true; - this.commentColumnCheckBox.CheckedChanged += new System.EventHandler(this.commentColumnCheckBox_CheckedChanged); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(4, 4); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(104, 13); - this.label1.TabIndex = 7; - this.label1.Text = "Bookmark comment:"; - // - // BookmarkWindow - // - this.ClientSize = new System.Drawing.Size(717, 158); - this.ControlBox = false; - this.Controls.Add(this.splitContainer1); - this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)(((((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft) - | WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight) - | WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop) - | WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom))); - this.DoubleBuffered = true; - this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "BookmarkWindow"; - this.ShowIcon = false; - this.ShowInTaskbar = false; - this.Text = "Bookmarks"; - this.ClientSizeChanged += new System.EventHandler(this.BookmarkWindow_ClientSizeChanged); - this.SizeChanged += new System.EventHandler(this.BookmarkWindow_SizeChanged); - this.contextMenuStrip1.ResumeLayout(false); - this.splitContainer1.Panel1.ResumeLayout(false); - this.splitContainer1.Panel2.ResumeLayout(false); - this.splitContainer1.Panel2.PerformLayout(); - this.splitContainer1.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)(this.bookmarkDataGridView)).EndInit(); - this.ResumeLayout(false); - } - - #endregion - - private BufferedDataGridView bookmarkDataGridView; - private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; - private System.Windows.Forms.ToolStripMenuItem deleteBookmarkssToolStripMenuItem; - private System.Windows.Forms.TextBox bookmarkTextBox; - private System.Windows.Forms.SplitContainer splitContainer1; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.ToolStripMenuItem removeCommentsToolStripMenuItem; - private System.Windows.Forms.CheckBox commentColumnCheckBox; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/BookmarkWindow.cs b/src/LogExpert/Dialogs/BookmarkWindow.cs deleted file mode 100644 index 7f92cee5..00000000 --- a/src/LogExpert/Dialogs/BookmarkWindow.cs +++ /dev/null @@ -1,674 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; -using LogExpert.Classes; -using LogExpert.Config; -using LogExpert.Entities; -using LogExpert.Extensions.Forms; -using LogExpert.Interface; -using NLog; -using WeifenLuo.WinFormsUI.Docking; - -namespace LogExpert.Dialogs -{ - public partial class BookmarkWindow : DockContent, ISharedToolWindow, IBookmarkView - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - private readonly object paintLock = new(); - - private IBookmarkData bookmarkData; - private ILogPaintContext logPaintContext; - private ILogView logView; - - #endregion - - #region cTor - - public BookmarkWindow() - { - InitializeComponent(); - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - bookmarkDataGridView.CellValueNeeded += boomarkDataGridView_CellValueNeeded; - bookmarkDataGridView.CellPainting += boomarkDataGridView_CellPainting; - - 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 = LogExpert.Config.ColorMode.BackgroundColor; - component.ForeColor = LogExpert.Config.ColorMode.ForeColor; - } - else - { - component.BackColor = LogExpert.Config.ColorMode.BackgroundColor; - component.ForeColor = LogExpert.Config.ColorMode.ForeColor; - } - - } - #endregion - - #region DataGridView - - BackColor = LogExpert.Config.ColorMode.DockBackgroundColor; - - // Main DataGridView - bookmarkDataGridView.BackgroundColor = LogExpert.Config.ColorMode.DockBackgroundColor; - bookmarkDataGridView.ColumnHeadersDefaultCellStyle.BackColor = LogExpert.Config.ColorMode.BackgroundColor; - bookmarkDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = LogExpert.Config.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 = LogExpert.Config.ColorMode.ForeColor; - item.BackColor = LogExpert.Config.ColorMode.MenuBackgroundColor; - } - - #endregion DataGridView - } - - #endregion - - #region Properties - - public bool LineColumnVisible - { - set => bookmarkDataGridView.Columns[2].Visible = value; - } - - public bool ShowBookmarkCommentColumn - { - get => commentColumnCheckBox.Checked; - set - { - commentColumnCheckBox.Checked = value; - ShowCommentColumn(value); - } - } - - #endregion - - #region Public methods - - public void SetColumnizer(ILogLineColumnizer columnizer) - { - PaintHelper.SetColumnizer(columnizer, bookmarkDataGridView); - - if (bookmarkDataGridView.ColumnCount > 0) - { - 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; - bookmarkDataGridView.Columns.Insert(1, commentColumn); - ShowCommentColumn(commentColumnCheckBox.Checked); - ResizeColumns(); - } - - /// - /// Called from LogWindow after reloading and when double clicking a header divider. - /// - public void ResizeColumns() - { - // this.bookmarkDataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells); - for (int i = 2; i < bookmarkDataGridView.ColumnCount; ++i) - { - bookmarkDataGridView.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.DisplayedCells); - } - } - - public void UpdateView() - { - bookmarkDataGridView.RowCount = bookmarkData?.Bookmarks.Count ?? 0; - ResizeColumns(); - bookmarkDataGridView.Refresh(); - } - - /// - /// Called from LogWindow if the bookmark text was changed via popup window - /// - /// - public void BookmarkTextChanged(Bookmark bookmark) - { - int rowIndex = bookmarkDataGridView.CurrentCellAddress.Y; - if (rowIndex == -1) - { - return; - } - - if (bookmarkData.Bookmarks[rowIndex] == bookmark) - { - bookmarkTextBox.Text = bookmark.Text; - } - - bookmarkDataGridView.Refresh(); - } - - public void SelectBookmark(int lineNum) - { - if (bookmarkData.IsBookmarkAtLine(lineNum)) - { - if (bookmarkDataGridView.Rows.GetRowCount(DataGridViewElementStates.None) < bookmarkData.Bookmarks.Count) - { - // just for the case... There was an exception but I cannot find the cause - UpdateView(); - } - - int row = bookmarkData.GetBookmarkIndexForLine(lineNum); - bookmarkDataGridView.CurrentCell = bookmarkDataGridView.Rows[row].Cells[0]; - } - } - - public void SetBookmarkData(IBookmarkData bookmarkData) - { - this.bookmarkData = bookmarkData; - bookmarkDataGridView.RowCount = bookmarkData?.Bookmarks.Count ?? 0; - HideIfNeeded(); - } - - public void PreferencesChanged(Preferences newPreferences, bool isLoadTime, SettingsFlags flags) - { - if ((flags & SettingsFlags.GuiOrColors) == SettingsFlags.GuiOrColors) - { - SetFont(newPreferences.fontName, newPreferences.fontSize); - if (bookmarkDataGridView.Columns.Count > 1 && newPreferences.setLastColumnWidth) - { - bookmarkDataGridView.Columns[bookmarkDataGridView.Columns.Count - 1].MinimumWidth = - newPreferences.lastColumnWidth; - } - - PaintHelper.ApplyDataGridViewPrefs(bookmarkDataGridView, newPreferences); - } - } - - public void SetCurrentFile(FileViewContext ctx) - { - if (ctx != null) - { - _logger.Debug("Current file changed to {0}", ctx.LogView.FileName); - lock (paintLock) - { - logView = ctx.LogView; - logPaintContext = ctx.LogPaintContext; - } - - SetColumnizer(ctx.LogView.CurrentColumnizer); - } - else - { - logView = null; - logPaintContext = null; - } - - UpdateView(); - } - - public void FileChanged() - { - // nothing to do - } - - #endregion - - #region Overrides - - protected override string GetPersistString() - { - return WindowTypes.BookmarkWindow.ToString(); - } - - protected override void OnPaint(PaintEventArgs e) - { - if (!splitContainer1.Visible) - { - Rectangle r = ClientRectangle; - e.Graphics.FillRectangle(SystemBrushes.FromSystemColor(LogExpert.Config.ColorMode.BookmarksDefaultBackgroundColor), r); - RectangleF rect = r; - StringFormat sf = new(); - sf.Alignment = StringAlignment.Center; - sf.LineAlignment = StringAlignment.Center; - e.Graphics.DrawString("No bookmarks in current file", SystemFonts.DialogFont, SystemBrushes.WindowText, r, sf); - } - else - { - base.OnPaint(e); - } - } - - #endregion - - #region Private Methods - - private void SetFont(string fontName, float fontSize) - { - Font font = new(new FontFamily(fontName), fontSize); - bookmarkDataGridView.DefaultCellStyle.Font = font; - bookmarkDataGridView.RowTemplate.Height = font.Height + 4; - bookmarkDataGridView.Refresh(); - } - - - private void CommentPainting(DataGridView gridView, int rowIndex, DataGridViewCellPaintingEventArgs e) - { - Color backColor = LogExpert.Config.ColorMode.DockBackgroundColor; - - 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"); - Color color = Color.FromArgb(255, 170, 170, 170); - brush = new SolidBrush(color); - } - - e.Graphics.FillRectangle(brush, e.CellBounds); - brush.Dispose(); - } - else - { - e.CellStyle.BackColor = backColor; - e.PaintBackground(e.CellBounds, false); - } - - e.PaintContent(e.CellBounds); - } - - private void DeleteSelectedBookmarks() - { - List lineNumList = []; - foreach (DataGridViewRow row in bookmarkDataGridView.SelectedRows) - { - if (row.Index != -1) - { - lineNumList.Add(bookmarkData.Bookmarks[row.Index].LineNum); - } - } - - logView?.DeleteBookmarks(lineNumList); - } - - private static void InvalidateCurrentRow(DataGridView gridView) - { - if (gridView.CurrentCellAddress.Y > -1) - { - gridView.InvalidateRow(gridView.CurrentCellAddress.Y); - } - } - - private void CurrentRowChanged(int rowIndex) - { - if (rowIndex == -1) - { - // multiple selection or no selection at all - bookmarkTextBox.Enabled = false; - -// disable the control first so that changes made to it won't propagate to the bookmark item - bookmarkTextBox.Text = string.Empty; - } - else - { - Bookmark bookmark = bookmarkData.Bookmarks[rowIndex]; - bookmarkTextBox.Text = bookmark.Text; - bookmarkTextBox.Enabled = true; - } - } - - - private void ShowCommentColumn(bool show) - { - bookmarkDataGridView.Columns[1].Visible = show; - } - - private void HideIfNeeded() - { - splitContainer1.Visible = bookmarkDataGridView.RowCount > 0; - } - - #endregion - - #region Events handler - - private void boomarkDataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) - { - if (bookmarkData == null) - { - return; - } - - lock (paintLock) - { - try - { - if (e.RowIndex < 0 || e.ColumnIndex < 0 || bookmarkData.Bookmarks.Count <= e.RowIndex) - { - e.Handled = false; - return; - } - - int lineNum = bookmarkData.Bookmarks[e.RowIndex].LineNum; - - // if (e.ColumnIndex == 1) - // { - // CommentPainting(this.bookmarkDataGridView, lineNum, e); - // } - { -// else - PaintHelper.CellPainting(logPaintContext, bookmarkDataGridView, lineNum, e); - } - } - catch (Exception ex) - { - _logger.Error(ex); - } - } - } - - private void boomarkDataGridView_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) - { - if (bookmarkData == null) - { - return; - } - - if (e.RowIndex < 0 || e.ColumnIndex < 0 || bookmarkData.Bookmarks.Count <= e.RowIndex) - { - e.Value = string.Empty; - return; - } - - Bookmark bookmarkForLine = bookmarkData.Bookmarks[e.RowIndex]; - int lineNum = bookmarkForLine.LineNum; - if (e.ColumnIndex == 1) - { - e.Value = bookmarkForLine.Text?.Replace('\n', ' ').Replace('\r', ' '); - } - else - { - int columnIndex = e.ColumnIndex > 1 ? e.ColumnIndex - 1 : e.ColumnIndex; - e.Value = logPaintContext.GetCellValue(lineNum, columnIndex); - } - } - - - private void boomarkDataGridView_MouseDoubleClick(object sender, MouseEventArgs e) - { - // if (this.bookmarkDataGridView.CurrentRow != null) - // { - // int lineNum = this.BookmarkList.Values[this.bookmarkDataGridView.CurrentRow.Index].LineNum; - // this.logWindow.SelectLogLine(lineNum); - // } - } - - private void boomarkDataGridView_ColumnDividerDoubleClick(object sender, - DataGridViewColumnDividerDoubleClickEventArgs e) - { - e.Handled = true; - ResizeColumns(); - } - - private void bookmarkGridView_KeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Enter) - { - if (bookmarkDataGridView.CurrentCellAddress.Y >= 0 && - bookmarkDataGridView.CurrentCellAddress.Y < bookmarkData.Bookmarks.Count) - { - int lineNum = bookmarkData.Bookmarks[bookmarkDataGridView.CurrentCellAddress.Y].LineNum; - logView.SelectLogLine(lineNum); - } - - e.Handled = true; - } - - if (e.KeyCode == Keys.Delete && e.Modifiers == Keys.None) - { - DeleteSelectedBookmarks(); - } - - if (e.KeyCode == Keys.Tab) - { - if (bookmarkDataGridView.Focused) - { - bookmarkTextBox.Focus(); - e.Handled = true; - } - } - } - - private void bookmarkGridView_Enter(object sender, EventArgs e) - { - InvalidateCurrentRow(bookmarkDataGridView); - } - - private void bookmarkGridView_Leave(object sender, EventArgs e) - { - InvalidateCurrentRow(bookmarkDataGridView); - } - - private void deleteBookmarksToolStripMenuItem_Click(object sender, EventArgs e) - { - DeleteSelectedBookmarks(); - } - - private void bookmarkTextBox_TextChanged(object sender, EventArgs e) - { - if (!bookmarkTextBox.Enabled) - { - return; // ignore all changes done while the control is disabled - } - - int rowIndex = bookmarkDataGridView.CurrentCellAddress.Y; - if (rowIndex == -1) - { - return; - } - - if (bookmarkData.Bookmarks.Count <= rowIndex) - { - return; - } - - Bookmark bookmark = bookmarkData.Bookmarks[rowIndex]; - bookmark.Text = bookmarkTextBox.Text; - logView?.RefreshLogView(); - } - - private void bookmarkDataGridView_SelectionChanged(object sender, EventArgs e) - { - if (bookmarkDataGridView.SelectedRows.Count != 1 - || bookmarkDataGridView.SelectedRows[0].Index >= bookmarkData.Bookmarks.Count) - { - CurrentRowChanged(-1); - } - else - { - CurrentRowChanged(bookmarkDataGridView.SelectedRows[0].Index); - } - } - - private void bookmarkDataGridView_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) - { - if (e.KeyCode == Keys.Tab) - { - e.IsInputKey = true; - } - } - - private void bookmarkDataGridView_CellToolTipTextNeeded(object sender, - DataGridViewCellToolTipTextNeededEventArgs e) - { - if (e.ColumnIndex != 0 || e.RowIndex <= -1 || e.RowIndex >= bookmarkData.Bookmarks.Count) - { - return; - } - - Bookmark bookmark = bookmarkData.Bookmarks[e.RowIndex]; - if (!string.IsNullOrEmpty(bookmark.Text)) - { - e.ToolTipText = bookmark.Text; - return; - } - } - - private void bookmarkDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e) - { - // Toggle bookmark when double-clicking on the first column - if (e.ColumnIndex == 0 && e.RowIndex >= 0 && bookmarkDataGridView.CurrentRow != null) - { - int index = bookmarkDataGridView.CurrentRow.Index; - int lineNum = bookmarkData.Bookmarks[bookmarkDataGridView.CurrentRow.Index].LineNum; - bookmarkData.ToggleBookmark(lineNum); - -// we don't ask for confirmation if the bookmark has an associated comment... - int boomarkCount = bookmarkData.Bookmarks.Count; - bookmarkDataGridView.RowCount = boomarkCount; - - if (index < boomarkCount) - { - bookmarkDataGridView.CurrentCell = bookmarkDataGridView.Rows[index].Cells[0]; - } - else - { - if (boomarkCount > 0) - { - bookmarkDataGridView.CurrentCell = - bookmarkDataGridView.Rows[boomarkCount - 1].Cells[0]; - } - } - - if (boomarkCount > index) - { - CurrentRowChanged(index); - } - else - { - if (boomarkCount > 0) - { - CurrentRowChanged(bookmarkDataGridView.RowCount - 1); - } - else - { - CurrentRowChanged(-1); - } - } - - return; - } - - if (bookmarkDataGridView.CurrentRow != null && e.RowIndex >= 0) - { - int lineNum = bookmarkData.Bookmarks[bookmarkDataGridView.CurrentRow.Index].LineNum; - logView.SelectAndEnsureVisible(lineNum, true); - } - } - - private void removeCommentsToolStripMenuItem_Click(object sender, EventArgs e) - { - 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) - { - bookmarkData.Bookmarks[row.Index].Text = string.Empty; - } - } - - bookmarkTextBox.Text = string.Empty; - bookmarkDataGridView.Refresh(); - logView.RefreshLogView(); - } - } - - private void commentColumnCheckBox_CheckedChanged(object sender, EventArgs e) - { - ShowCommentColumn(commentColumnCheckBox.Checked); - } - - private void BookmarkWindow_ClientSizeChanged(object sender, EventArgs e) - { - if (Width > 0 && Height > 0) - { - if (Width > Height) - { - splitContainer1.Orientation = Orientation.Vertical; - int distance = Width - 200; - splitContainer1.SplitterDistance = distance > splitContainer1.Panel1MinSize - ? distance - : splitContainer1.Panel1MinSize; - } - else - { - splitContainer1.Orientation = Orientation.Horizontal; - int distance = Height - 200; - splitContainer1.SplitterDistance = distance > splitContainer1.Panel1MinSize - ? distance - : splitContainer1.Panel1MinSize; - } - } - - if (!splitContainer1.Visible) - { - // redraw the "no bookmarks" display - Invalidate(); - } - } - - private void bookmarkDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) - { - HideIfNeeded(); - } - - private void bookmarkDataGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) - { - HideIfNeeded(); - } - - private void BookmarkWindow_SizeChanged(object sender, EventArgs e) - { - // if (!this.splitContainer1.Visible) - // { - // // redraw the "no bookmarks" display - // Invalidate(); - // } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/BufferedDataGridView.cs b/src/LogExpert/Dialogs/BufferedDataGridView.cs deleted file mode 100644 index 749c2c75..00000000 --- a/src/LogExpert/Dialogs/BufferedDataGridView.cs +++ /dev/null @@ -1,343 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Drawing; -using System.Data; -using System.Text; -using System.Windows.Forms; -using System.Drawing.Drawing2D; -using LogExpert.Entities; -using NLog; - -namespace LogExpert.Dialogs -{ - public partial class BufferedDataGridView : DataGridView - { - #region Fields - - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - private readonly Brush _brush; - - private readonly Color _bubbleColor = Color.FromArgb(160, 250, 250, 00); - 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 BookmarkOverlay _draggedOverlay; - private Point _dragStartPoint; - private bool _isDrag; - private Size _oldOverlayOffset; - - #endregion - - #region cTor - - public BufferedDataGridView() - { - _pen = new Pen(_bubbleColor, (float) 3.0); - _brush = new SolidBrush(_bubbleColor); - - InitializeComponent(); - DoubleBuffered = true; - VirtualMode = true; - } - - #endregion - - #region Delegates - - public delegate void OverlayDoubleClickedEventHandler(object sender, OverlayEventArgs e); - - #endregion - - #region Events - - public event OverlayDoubleClickedEventHandler OverlayDoubleClicked; - - #endregion - - #region Properties - - /* - public Graphics Buffer - { - get { return this.myBuffer.Graphics; } - } - */ - - public ContextMenuStrip EditModeMenuStrip { get; set; } = null; - - public bool PaintWithOverlays { get; set; } = false; - - #endregion - - #region Public methods - - public void AddOverlay(BookmarkOverlay overlay) - { - lock (_overlayList) - { - _overlayList.Add(overlay.Position.Y, overlay); - } - } - - #endregion - - #region Overrides - - protected override void OnPaint(PaintEventArgs e) - { - try - { - if (PaintWithOverlays) - { - PaintOverlays(e); - } - else - { - base.OnPaint(e); - } - } - catch (Exception ex) - { - _logger.Error(ex); - } - } - - protected override void OnEditingControlShowing(DataGridViewEditingControlShowingEventArgs e) - { - base.OnEditingControlShowing(e); - e.Control.KeyDown -= OnControlKeyDown; - e.Control.KeyDown += OnControlKeyDown; - DataGridViewTextBoxEditingControl editControl = (DataGridViewTextBoxEditingControl) e.Control; - e.Control.PreviewKeyDown -= Control_PreviewKeyDown; - e.Control.PreviewKeyDown += Control_PreviewKeyDown; - - editControl.ContextMenuStrip = EditModeMenuStrip; - } - - protected override void OnMouseDown(MouseEventArgs e) - { - BookmarkOverlay overlay = GetOverlayForPosition(e.Location); - if (overlay != null) - { - if (e.Button == MouseButtons.Right) - { - if (_isDrag) - { - _isDrag = false; - overlay.Bookmark.OverlayOffset = _oldOverlayOffset; - Refresh(); - } - } - else - { - _dragStartPoint = e.Location; - _isDrag = true; - _draggedOverlay = overlay; - _oldOverlayOffset = overlay.Bookmark.OverlayOffset; - } - } - else - { - _isDrag = false; - base.OnMouseDown(e); - } - } - - protected override void OnMouseUp(MouseEventArgs e) - { - if (_isDrag) - { - _isDrag = false; - Refresh(); - } - else - { - base.OnMouseUp(e); - } - } - - protected override void OnMouseMove(MouseEventArgs e) - { - if (_isDrag) - { - Cursor = Cursors.Hand; - Size offset = new(e.X - _dragStartPoint.X, e.Y - _dragStartPoint.Y); - _draggedOverlay.Bookmark.OverlayOffset = _oldOverlayOffset + offset; - Refresh(); - } - else - { - BookmarkOverlay overlay = GetOverlayForPosition(e.Location); - Cursor = overlay != null ? Cursors.Hand : Cursors.Default; - base.OnMouseMove(e); - } - } - - protected override void OnMouseDoubleClick(MouseEventArgs e) - { - BookmarkOverlay overlay = GetOverlayForPosition(e.Location); - if (overlay != null) - { - if (e.Button == MouseButtons.Left) - { - OnOverlayDoubleClicked(new OverlayEventArgs(overlay)); - } - } - else - { - base.OnMouseDoubleClick(e); - } - } - - #endregion - - #region Private Methods - - private BookmarkOverlay GetOverlayForPosition(Point pos) - { - lock (_overlayList) - { - foreach (BookmarkOverlay overlay in _overlayList.Values) - { - if (overlay.BubbleRect.Contains(pos)) - { - return overlay; - } - } - } - - return null; - } - - private void PaintOverlays(PaintEventArgs e) - { - BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current; - using (BufferedGraphics myBuffer = currentContext.Allocate(CreateGraphics(), ClientRectangle)) - { - lock (_overlayList) - { - _overlayList.Clear(); - } - - myBuffer.Graphics.SetClip(ClientRectangle, CombineMode.Union); - e.Graphics.SetClip(ClientRectangle, CombineMode.Union); - - PaintEventArgs args = new(myBuffer.Graphics, e.ClipRectangle); - - base.OnPaint(args); - - StringFormat format = new(); - format.LineAlignment = StringAlignment.Center; - format.Alignment = StringAlignment.Near; - - myBuffer.Graphics.SetClip(DisplayRectangle, CombineMode.Intersect); - - // Remove Columnheader from Clippingarea - Rectangle rectTableHeader = new(DisplayRectangle.X, DisplayRectangle.Y, DisplayRectangle.Width, ColumnHeadersHeight); - myBuffer.Graphics.SetClip(rectTableHeader, CombineMode.Exclude); - - //e.Graphics.SetClip(rect, CombineMode.Union); - - lock (_overlayList) - { - foreach (BookmarkOverlay overlay in _overlayList.Values) - { - SizeF 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); - rectBubble.Location += overlay.Bookmark.OverlayOffset; - overlay.BubbleRect = rectBubble; - myBuffer.Graphics.SetClip(rectBubble, CombineMode.Union); // Bubble to clip - myBuffer.Graphics.SetClip(rectTableHeader, CombineMode.Exclude); - e.Graphics.SetClip(rectBubble, CombineMode.Union); - RectangleF textRect = new(rectBubble.X, rectBubble.Y, rectBubble.Width, rectBubble.Height); - myBuffer.Graphics.FillRectangle(_brush, rectBubble); - //myBuffer.Graphics.DrawLine(_pen, overlay.Position, new Point(rect.X, rect.Y + rect.Height / 2)); - myBuffer.Graphics.DrawLine(_pen, overlay.Position, new Point(rectBubble.X, rectBubble.Y + rectBubble.Height)); - myBuffer.Graphics.DrawString(overlay.Bookmark.Text, _font, _textBrush, textRect, format); - - if (_logger.IsDebugEnabled) - { - _logger.Debug("ClipRgn: {0},{1},{2},{3}", myBuffer.Graphics.ClipBounds.Left, myBuffer.Graphics.ClipBounds.Top, myBuffer.Graphics.ClipBounds.Width, myBuffer.Graphics.ClipBounds.Height); - } - } - } - - myBuffer.Render(e.Graphics); - } - } - - #endregion - - #region Events handler - - private void Control_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) - { - if ((e.KeyCode == Keys.C || e.KeyCode == Keys.Insert) && e.Control) - { - if (EditingControl != null) - { - e.IsInputKey = true; - } - } - } - - private void OnControlKeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Down) - { - if (EditingControl != null) - { - if (EditingControl is LogCellEditingControl editControl) - { - editControl.EditingControlDataGridView.EndEdit(); - int line = editControl.EditingControlDataGridView.CurrentCellAddress.Y; - if (e.KeyCode == Keys.Up) - { - if (line > 0) - { - line--; - } - } - - if (e.KeyCode == Keys.Down) - { - if (line < editControl.EditingControlDataGridView.RowCount - 1) - { - line++; - } - } - - int col = editControl.EditingControlDataGridView.CurrentCellAddress.X; - int scrollIndex = editControl.EditingControlDataGridView.HorizontalScrollingOffset; - int selStart = editControl.SelectionStart; - editControl.EditingControlDataGridView.CurrentCell = editControl.EditingControlDataGridView.Rows[line].Cells[col]; - editControl.EditingControlDataGridView.BeginEdit(false); - editControl.SelectionStart = selStart; - editControl.ScrollToCaret(); - editControl.EditingControlDataGridView.HorizontalScrollingOffset = scrollIndex; - e.Handled = true; - } - else - { - _logger.Warn("Edit control was null, to be checked"); - } - } - } - } - - #endregion - - protected virtual void OnOverlayDoubleClicked(OverlayEventArgs e) - { - OverlayDoubleClicked?.Invoke(this, e); - } - } -} diff --git a/src/LogExpert/Dialogs/ChooseIconDlg.Designer.cs b/src/LogExpert/Dialogs/ChooseIconDlg.Designer.cs deleted file mode 100644 index 00cf7708..00000000 --- a/src/LogExpert/Dialogs/ChooseIconDlg.Designer.cs +++ /dev/null @@ -1,125 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class ChooseIconDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ChooseIconDlg)); - this.iconListView = new System.Windows.Forms.ListView(); - this.iconFileLabel = new System.Windows.Forms.Label(); - this.buttonChooseIconFile = new System.Windows.Forms.Button(); - this.okButton = new System.Windows.Forms.Button(); - this.cancelButton = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // iconListView - // - this.iconListView.Alignment = System.Windows.Forms.ListViewAlignment.Left; - this.iconListView.AutoArrange = false; - this.iconListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; - this.iconListView.HideSelection = false; - this.iconListView.Location = new System.Drawing.Point(18, 63); - this.iconListView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - this.iconListView.MultiSelect = false; - this.iconListView.Name = "iconListView"; - this.iconListView.ShowGroups = false; - this.iconListView.Size = new System.Drawing.Size(529, 118); - this.iconListView.TabIndex = 0; - this.iconListView.UseCompatibleStateImageBehavior = false; - // - // iconFileLabel - // - this.iconFileLabel.Location = new System.Drawing.Point(18, 26); - this.iconFileLabel.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - this.iconFileLabel.Name = "iconFileLabel"; - this.iconFileLabel.Size = new System.Drawing.Size(411, 35); - this.iconFileLabel.TabIndex = 1; - this.iconFileLabel.Text = "label1"; - // - // buttonChooseIconFile - // - this.buttonChooseIconFile.Location = new System.Drawing.Point(438, 18); - this.buttonChooseIconFile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - this.buttonChooseIconFile.Name = "buttonChooseIconFile"; - this.buttonChooseIconFile.Size = new System.Drawing.Size(112, 35); - this.buttonChooseIconFile.TabIndex = 2; - this.buttonChooseIconFile.Text = "Icon file..."; - this.buttonChooseIconFile.UseVisualStyleBackColor = true; - this.buttonChooseIconFile.Click += new System.EventHandler(this.OnButtonChooseIconFileClick); - // - // okButton - // - this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okButton.Location = new System.Drawing.Point(316, 226); - this.okButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - this.okButton.Name = "okButton"; - this.okButton.Size = new System.Drawing.Size(112, 35); - this.okButton.TabIndex = 3; - this.okButton.Text = "OK"; - this.okButton.UseVisualStyleBackColor = true; - this.okButton.Click += new System.EventHandler(this.OnOkButtonClick); - // - // cancelButton - // - this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(440, 226); - this.cancelButton.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - this.cancelButton.Name = "cancelButton"; - this.cancelButton.Size = new System.Drawing.Size(112, 35); - this.cancelButton.TabIndex = 4; - this.cancelButton.Text = "Cancel"; - this.cancelButton.UseVisualStyleBackColor = true; - // - // ChooseIconDlg - // - this.ClientSize = new System.Drawing.Size(568, 278); - this.Controls.Add(this.cancelButton); - this.Controls.Add(this.okButton); - this.Controls.Add(this.buttonChooseIconFile); - this.Controls.Add(this.iconFileLabel); - this.Controls.Add(this.iconListView); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "ChooseIconDlg"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Choose Icon"; - this.Load += new System.EventHandler(this.ChooseIconDlg_Load); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.ListView iconListView; - private System.Windows.Forms.Label iconFileLabel; - private System.Windows.Forms.Button buttonChooseIconFile; - private System.Windows.Forms.Button okButton; - private System.Windows.Forms.Button cancelButton; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ChooseIconDlg.cs b/src/LogExpert/Dialogs/ChooseIconDlg.cs deleted file mode 100644 index 69a8c606..00000000 --- a/src/LogExpert/Dialogs/ChooseIconDlg.cs +++ /dev/null @@ -1,117 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using System.IO; -using LogExpert.Classes; - -namespace LogExpert.Dialogs -{ - public partial class ChooseIconDlg : Form - { - #region Fields - - #endregion - - #region cTor - - public ChooseIconDlg(string fileName) - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - FileName = fileName; - } - - #endregion - - #region Properties - - public string FileName { get; set; } - - public int IconIndex { get; set; } - - #endregion - - #region Private Methods - - private void FillIconList() - { - iconListView.Items.Clear(); - - Icon[,] icons = Win32.ExtractIcons(FileName); - - if (icons == null) - { - return; - } - - ImageList imageList = new(); - - if (icons.GetLength(0) > 0) - { - imageList.ImageSize = icons[1, 0].Size; - iconListView.LargeImageList = imageList; - for (int i = 0; i < icons.GetLength(1); ++i) - { - imageList.Images.Add(icons[1, i]); - ListViewItem item = new(); - item.ImageIndex = i; - iconListView.Items.Add(item); - } - } - } - - private void DisposeIcons() - { - ImageList imageList = iconListView.LargeImageList; - iconListView.LargeImageList = null; - foreach (Image image in imageList.Images) - { - image.Dispose(); - } - } - - #endregion - - #region Events handler - - private void ChooseIconDlg_Load(object sender, EventArgs e) - { - FillIconList(); - iconFileLabel.Text = FileName; - } - - private void OnButtonChooseIconFileClick(object sender, EventArgs e) - { - OpenFileDialog dlg = new(); - dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - - if (string.IsNullOrEmpty(iconFileLabel.Text) == false) - { - FileInfo info = new(iconFileLabel.Text); - if (info.Directory != null && info.Directory.Exists) - { - dlg.InitialDirectory = info.DirectoryName; - } - } - - if (dlg.ShowDialog() == DialogResult.OK) - { - iconFileLabel.Text = dlg.FileName; - FileName = dlg.FileName; - FillIconList(); - } - } - - private void OnOkButtonClick(object sender, EventArgs e) - { - IconIndex = iconListView.SelectedIndices.Count > 0 ? iconListView.SelectedIndices[0] : -1; - ; - DisposeIcons(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ColorComboBox.cs b/src/LogExpert/Dialogs/ColorComboBox.cs deleted file mode 100644 index 434529b1..00000000 --- a/src/LogExpert/Dialogs/ColorComboBox.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System.Windows.Forms; -using System.Drawing; -using System.Drawing.Drawing2D; - -namespace LogExpert.Dialogs -{ - public class ColorComboBox : ComboBox - { - #region Fields - - private Color _customColor = Color.FromKnownColor(KnownColor.Black); - - #endregion - - #region cTor - - 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); - } - } - - #endregion - - #region Properties - - public Color CustomColor - { - get => _customColor; - set - { - _customColor = value; - Items.RemoveAt(0); - Items.Insert(0, _customColor); - } - } - - public Color SelectedColor => (Color) (SelectedIndex != -1 ? Items[SelectedIndex] : null); - - #endregion - - #region Events handler - - private void OnColorComboBoxDrawItem(object sender, DrawItemEventArgs e) - { - e.DrawBackground(); - if (e.Index >= 0) - { - Rectangle rectangle = new(4, e.Bounds.Top + 2, 30, e.Bounds.Height - 4); - Color rectColor = (Color) Items[e.Index]; - e.Graphics.FillRectangle(new SolidBrush(rectColor), rectangle); - e.Graphics.DrawRectangle(Pens.Black, rectangle); - - if (e.Index == 0) - { - e.Graphics.DrawString("Custom", e.Font, Brushes.Black, - new PointF(42, e.Bounds.Top + 2)); - } - else - { - e.Graphics.DrawString(((Color) Items[e.Index]).Name, e.Font, Brushes.Black, - new PointF(42, e.Bounds.Top + 2)); - } - - if (!Enabled) - { - HatchBrush brush = new(HatchStyle.Percent50, Color.LightGray, Color.FromArgb(10, Color.LightGray)); - rectangle.Inflate(1, 1); - e.Graphics.FillRectangle(brush, rectangle); - brush.Dispose(); - } - e.DrawFocusRectangle(); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/DateTimeDragControl.cs b/src/LogExpert/Dialogs/DateTimeDragControl.cs deleted file mode 100644 index b424e4a2..00000000 --- a/src/LogExpert/Dialogs/DateTimeDragControl.cs +++ /dev/null @@ -1,518 +0,0 @@ -using LogExpert.Classes.DateTimeParser; - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Globalization; -using System.Linq; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - /// - /// This control displays date and time and allows user to interact with the individual parts using the mouse - /// to increment and decrement the values. The date format displayed is derived from the application UI locale. - /// We currently support only three: US (mm/dd/yyyy), French (yyyy-mm-dd) and German (dd.mm.yyyy). - /// The control raises events (ValueChanged, ValueDragged) when the date/time changes so that owner can react accordingly. - /// - public partial class DateTimeDragControl : UserControl - { - #region Fields - - private const int NO_DIGIT_DRAGGED = -1; - private int _addedValue; - - - private DateTime _dateTime; - private readonly IList _digitRects = new List(); - private readonly StringFormat _digitsFormat = new(); - private int _draggedDigit; - - public DragOrientations dragOrientation = DragOrientations.Vertical; - - private readonly ToolStripItem toolStripItemHorizontalDrag = new ToolStripMenuItem(); - private readonly ToolStripItem toolStripItemVerticalDrag = new ToolStripMenuItem(); - private readonly ToolStripItem toolStripItemVerticalInvertedDrag = new ToolStripMenuItem(); - - private int _oldValue; - - private string[] _dateParts; - - private int _startMouseX; - private int _startMouseY; - - #endregion - - #region cTor - - /// - /// Default Constructor - /// - public DateTimeDragControl() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - _digitsFormat.LineAlignment = StringAlignment.Center; - _digitsFormat.Alignment = StringAlignment.Near; - _digitsFormat.Trimming = StringTrimming.None; - _digitsFormat.FormatFlags = StringFormatFlags.FitBlackBox | StringFormatFlags.NoClip | StringFormatFlags.NoWrap; - - _draggedDigit = NO_DIGIT_DRAGGED; - } - - #endregion - - #region Delegates - - public delegate void ValueChangedEventHandler(object sender, EventArgs e); - - public delegate void ValueDraggedEventHandler(object sender, EventArgs e); - - #endregion - - #region Events - - public event ValueChangedEventHandler ValueChanged; - public event ValueDraggedEventHandler ValueDragged; - - #endregion - - #region Properties - - public DateTime MinDateTime { get; set; } = DateTime.MinValue; - - public DateTime MaxDateTime { get; set; } = DateTime.MaxValue; - - public DragOrientations DragOrientation - { - get => dragOrientation; - set - { - dragOrientation = value; - UpdateContextMenu(); - } - } - - public Color HoverColor { get; set; } - - public DateTime DateTime - { - get => _dateTime.Subtract(TimeSpan.FromMilliseconds(_dateTime.Millisecond)); - set - { - _dateTime = value; - - if (_dateTime < MinDateTime) - { - _dateTime = MinDateTime; - } - if (_dateTime > MaxDateTime) - { - _dateTime = MaxDateTime; - } - } - } - - #endregion - - #region Private Methods - - // Returns the index of the rectangle (digitRects) under the mouse cursor - private int DetermineDraggedDigit(MouseEventArgs e) - { - for (int i = 0; i < _digitRects.Count; ++i) - { - if (_digitRects[i].Contains(e.Location) && Token.IsDatePart(_dateParts[i])) - { - return i; - } - } - - return NO_DIGIT_DRAGGED; - } - - // Return the value corresponding to current dragged digit - private int GetDraggedValue() - { - string datePart = _dateParts[_draggedDigit]; - - if (datePart.StartsWith("y", StringComparison.OrdinalIgnoreCase)) - { - return _dateTime.Year; - } - - if (datePart.StartsWith("M")) - { - return _dateTime.Month; - } - - if (datePart.StartsWith("d", StringComparison.OrdinalIgnoreCase)) - { - return _dateTime.Day; - } - - if (datePart.StartsWith("h", StringComparison.OrdinalIgnoreCase)) - { - return _dateTime.Hour; - } - - if (datePart.StartsWith("m")) - { - return _dateTime.Minute; - } - - return datePart.StartsWith("s", StringComparison.OrdinalIgnoreCase) ? _dateTime.Second : NO_DIGIT_DRAGGED; - } - - private bool SetDraggedValue(int delta) - { - if (_draggedDigit == NO_DIGIT_DRAGGED) - { - return false; - } - - bool changed = true; - try - { - string datePart = _dateParts[_draggedDigit]; - - if (datePart.StartsWith("y", StringComparison.OrdinalIgnoreCase)) - { - _dateTime = _dateTime.AddYears(delta); - } - else if (datePart.StartsWith("M")) - { - _dateTime = _dateTime.AddMonths(delta); - } - else if (datePart.StartsWith("d", StringComparison.OrdinalIgnoreCase)) - { - _dateTime = _dateTime.AddDays(delta); - } - else if (datePart.StartsWith("h", StringComparison.OrdinalIgnoreCase)) - { - _dateTime = _dateTime.AddHours(delta); - } - else if (datePart.StartsWith("m")) - { - _dateTime = _dateTime.AddMinutes(delta); - } - else if (datePart.StartsWith("s", StringComparison.OrdinalIgnoreCase)) - { - _dateTime = _dateTime.AddSeconds(delta); - } - } - catch (Exception) - { - // invalid value dragged - } - - if (_dateTime > MaxDateTime) - { - _dateTime = MaxDateTime; - changed = false; - } - if (_dateTime < MinDateTime) - { - _dateTime = MinDateTime; - changed = false; - } - - return changed; - } - - private void InitCustomRects(Section dateSection) - { - _dateParts = dateSection - .GeneralTextDateDurationParts - .Select(DateFormatPartAdjuster.AdjustDateTimeFormatPart) - .ToArray(); - - Rectangle rect = ClientRectangle; - int oneCharWidth = rect.Width / _dateParts.Sum(s => s.Length); - int left = rect.Left; - - _digitRects.Clear(); - - foreach (string datePart in _dateParts) - { - int s = datePart.Length * oneCharWidth; - _digitRects.Add(new Rectangle(left, rect.Top, s, rect.Height)); - left += s; - } - - } - - private void InitDigitRects() - { - CultureInfo culture = System.Threading.Thread.CurrentThread.CurrentCulture; - - string datePattern = string.Concat(culture.DateTimeFormat.ShortDatePattern, " ", culture.DateTimeFormat.LongTimePattern); - - List
sections = Parser.ParseSections(datePattern, out _); - Section dateSection = sections.FirstOrDefault(); - - if (dateSection == null) - { - sections = Parser.ParseSections("dd.MM.yyyy HH:mm:ss", out bool _); - dateSection = sections.Single(); - } - - InitCustomRects(dateSection); - } - - #endregion - - #region Events handler - - private void DateTimeDragControl_Load(object sender, EventArgs e) - { - InitDigitRects(); - - BuildContextualMenu(); - } - - #endregion - - protected void OnValueChanged(EventArgs e) - { - ValueChanged?.Invoke(this, e); - } - - protected void OnValueDragged(EventArgs e) - { - ValueDragged?.Invoke(this, e); - } - - public enum DragOrientations - { - Horizontal, - Vertical, - InvertedVertical - } - - #region Contextual Menu - - private void BuildContextualMenu() - { - ContextMenuStrip = new ContextMenuStrip(); - ContextMenuStrip.Name = "Timestamp selector"; - ContextMenuStrip.Items.Add(toolStripItemHorizontalDrag); - ContextMenuStrip.Items.Add(toolStripItemVerticalDrag); - ContextMenuStrip.Items.Add(toolStripItemVerticalInvertedDrag); - - toolStripItemHorizontalDrag.Click += OnToolStripItemHorizontalDragClick; - toolStripItemHorizontalDrag.Text = "Drag horizontal"; - - toolStripItemVerticalDrag.Click += OnToolStripItemVerticalDragClick; - toolStripItemVerticalDrag.Text = "Drag vertical"; - - toolStripItemVerticalInvertedDrag.Click += OnToolStripItemVerticalInvertedDragClick; - toolStripItemVerticalInvertedDrag.Text = "Drag vertical inverted"; - - ContextMenuStrip.Opening += OnContextMenuStripOpening; - - UpdateContextMenu(); - } - - private void UpdateContextMenu() - { - toolStripItemHorizontalDrag.Enabled = DragOrientation != DragOrientations.Horizontal; - toolStripItemVerticalDrag.Enabled = DragOrientation != DragOrientations.Vertical; - toolStripItemVerticalInvertedDrag.Enabled = DragOrientation != DragOrientations.InvertedVertical; - } - - private void OnContextMenuStripOpening(object sender, CancelEventArgs e) - { - if (Capture) - { - e.Cancel = true; - } - } - - private void OnToolStripItemHorizontalDragClick(object sender, EventArgs e) - { - DragOrientation = DragOrientations.Horizontal; - toolStripItemHorizontalDrag.Enabled = false; - toolStripItemVerticalDrag.Enabled = true; - toolStripItemVerticalInvertedDrag.Enabled = true; - } - - private void OnToolStripItemVerticalDragClick(object sender, EventArgs e) - { - DragOrientation = DragOrientations.Vertical; - toolStripItemHorizontalDrag.Enabled = true; - toolStripItemVerticalDrag.Enabled = false; - toolStripItemVerticalInvertedDrag.Enabled = true; - } - - private void OnToolStripItemVerticalInvertedDragClick(object sender, EventArgs e) - { - DragOrientation = DragOrientations.InvertedVertical; - toolStripItemHorizontalDrag.Enabled = true; - toolStripItemVerticalDrag.Enabled = true; - toolStripItemVerticalInvertedDrag.Enabled = false; - } - - #endregion - - #region Rendering - - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - - // Show what digit is dragged - using (Brush hoverBrush = new SolidBrush(HoverColor)) - { - if (_draggedDigit != NO_DIGIT_DRAGGED) - { - e.Graphics.FillRectangle(hoverBrush, _digitRects[_draggedDigit]); - } - } - - // Display current value with user-defined date format and fixed time format ("HH:mm:ss") - using (Brush brush = new SolidBrush(Color.Black)) - { - for (int i = 0; i < _dateParts.Length; i++) - { - string datePart = _dateParts[i]; - Rectangle rect = _digitRects[i]; - string value; - - if (Token.IsDatePart(datePart)) - { - try - { - value = _dateTime.ToString("-" + datePart + "-"); - value = value.Substring(1, value.Length - 2); - } - catch - { - value = datePart; - } - } - else - { - value = datePart; - } - - e.Graphics.DrawString(value, Font, brush, rect, _digitsFormat); - } - } - } - - private void DateTimeDragControl_Resize(object sender, EventArgs e) - { - InitDigitRects(); - } - - #endregion - - #region Mouse callbacks - - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - if (e.Button == MouseButtons.Left) - { - _draggedDigit = DetermineDraggedDigit(e); - if (_draggedDigit == NO_DIGIT_DRAGGED) - { - return; - } - Capture = true; - _startMouseY = e.Y; - _startMouseX = e.X; - _oldValue = GetDraggedValue(); - _addedValue = 0; - } - else if (e.Button == MouseButtons.Right && Capture) - { - Capture = false; - SetDraggedValue(0); //undo - } - Invalidate(); // repaint with the selected item (or none) - } - - protected override void OnMouseUp(MouseEventArgs e) - { - if (!Capture) - { - return; - } - - base.OnMouseUp(e); - - Capture = false; - _draggedDigit = NO_DIGIT_DRAGGED; - Invalidate(); // repaint without the selected item - - OnValueChanged(EventArgs.Empty); - } - - protected override void OnMouseMove(MouseEventArgs e) - { - base.OnMouseMove(e); - - if (!Capture) - { - return; - } - - int diff; - switch (DragOrientation) - { - case DragOrientations.Vertical: - { - diff = _startMouseY - e.Y; - break; - } - case DragOrientations.InvertedVertical: - { - diff = _startMouseY + e.Y; - break; - } - default: - { - diff = e.X - _startMouseX; - break; - } - } - - int delta = diff / 5 - _addedValue; // one unit per 5 pixels move - - if (delta == 0) - { - return; - } - - if (SetDraggedValue(delta)) - { - _addedValue += delta; - } - - Invalidate(); - - OnValueDragged(EventArgs.Empty); - } - - private void DateTimeDragControl_MouseLeave(object sender, EventArgs e) - { - if (Capture) - { - return; - } - - _draggedDigit = NO_DIGIT_DRAGGED; - Refresh(); - } - - #endregion - } -} diff --git a/src/LogExpert/Dialogs/ExceptionWindow.Designer.cs b/src/LogExpert/Dialogs/ExceptionWindow.Designer.cs deleted file mode 100644 index 3fbdc6e0..00000000 --- a/src/LogExpert/Dialogs/ExceptionWindow.Designer.cs +++ /dev/null @@ -1,108 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class ExceptionWindow - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExceptionWindow)); - this.stackTraceTextBox = new System.Windows.Forms.TextBox(); - this.label1 = new System.Windows.Forms.Label(); - this.okButton = new System.Windows.Forms.Button(); - this.copyButton = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // stackTraceTextBox - // - this.stackTraceTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) - | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.stackTraceTextBox.Location = new System.Drawing.Point(12, 42); - this.stackTraceTextBox.Multiline = true; - this.stackTraceTextBox.Name = "stackTraceTextBox"; - this.stackTraceTextBox.ReadOnly = true; - this.stackTraceTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.stackTraceTextBox.Size = new System.Drawing.Size(439, 205); - this.stackTraceTextBox.TabIndex = 0; - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(13, 13); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(310, 13); - this.label1.TabIndex = 1; - this.label1.Text = "An unhandled error has occured. Please report to the developer."; - // - // okButton - // - this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okButton.Location = new System.Drawing.Point(376, 265); - this.okButton.Name = "okButton"; - this.okButton.Size = new System.Drawing.Size(75, 23); - this.okButton.TabIndex = 2; - this.okButton.Text = "Close"; - this.okButton.UseVisualStyleBackColor = true; - // - // copyButton - // - this.copyButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.copyButton.Location = new System.Drawing.Point(12, 265); - this.copyButton.Name = "copyButton"; - this.copyButton.Size = new System.Drawing.Size(117, 23); - this.copyButton.TabIndex = 4; - this.copyButton.Text = "Copy to clipboard"; - this.copyButton.UseVisualStyleBackColor = true; - this.copyButton.Click += new System.EventHandler(this.copyButton_Click); - // - // ExceptionWindow - // - this.CancelButton = this.okButton; - this.ClientSize = new System.Drawing.Size(464, 300); - this.Controls.Add(this.copyButton); - this.Controls.Add(this.okButton); - this.Controls.Add(this.label1); - this.Controls.Add(this.stackTraceTextBox); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "ExceptionWindow"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "LogExpert Error"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.TextBox stackTraceTextBox; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Button okButton; - private System.Windows.Forms.Button copyButton; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ExceptionWindow.cs b/src/LogExpert/Dialogs/ExceptionWindow.cs deleted file mode 100644 index 4d557602..00000000 --- a/src/LogExpert/Dialogs/ExceptionWindow.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class ExceptionWindow : Form - { - #region Fields - - private readonly string _errorText; - - private readonly string _stackTrace; - - #endregion - - #region cTor - - public ExceptionWindow(string errorText, string stackTrace) - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - _errorText = errorText; - _stackTrace = stackTrace; - - stackTraceTextBox.Text = _errorText + @"\n\n" + _stackTrace; - stackTraceTextBox.Select(0, 0); - } - - #endregion - - #region Private Methods - - private void CopyToClipboard() - { - Clipboard.SetText(_errorText + @"\n\n" + _stackTrace); - } - - #endregion - - #region Events handler - - private void copyButton_Click(object sender, EventArgs e) - { - CopyToClipboard(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/FilterColumnChooser.Designer.cs b/src/LogExpert/Dialogs/FilterColumnChooser.Designer.cs deleted file mode 100644 index 6936b914..00000000 --- a/src/LogExpert/Dialogs/FilterColumnChooser.Designer.cs +++ /dev/null @@ -1,218 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class FilterColumnChooser - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FilterColumnChooser)); - this.columnListBox = new System.Windows.Forms.CheckedListBox(); - this.buttonOk = new System.Windows.Forms.Button(); - this.toolTipEmptyColumnNoHit = new System.Windows.Forms.ToolTip(this.components); - this.emptyColumnNoHitRadioButton = new System.Windows.Forms.RadioButton(); - this.toolTipListBox = new System.Windows.Forms.ToolTip(this.components); - this.checkBoxExactMatch = new System.Windows.Forms.CheckBox(); - this.groupBox1 = new System.Windows.Forms.GroupBox(); - this.emptyColumnUsePrevRadioButton = new System.Windows.Forms.RadioButton(); - this.emptyColumnHitRadioButton = new System.Windows.Forms.RadioButton(); - this.groupBoxExectMatch = new System.Windows.Forms.GroupBox(); - this.toolTipSearchHit = new System.Windows.Forms.ToolTip(this.components); - this.toolTipPrevContent = new System.Windows.Forms.ToolTip(this.components); - this.toolTipExactMatch = new System.Windows.Forms.ToolTip(this.components); - this.buttonCancel = new System.Windows.Forms.Button(); - this.groupBox1.SuspendLayout(); - this.groupBoxExectMatch.SuspendLayout(); - this.SuspendLayout(); - // - // columnListBox - // - this.columnListBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.columnListBox.CheckOnClick = true; - this.columnListBox.Font = new System.Drawing.Font("Courier New", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); - this.columnListBox.FormattingEnabled = true; - this.columnListBox.Location = new System.Drawing.Point(3, 3); - this.columnListBox.Name = "columnListBox"; - this.columnListBox.Size = new System.Drawing.Size(177, 119); - this.columnListBox.TabIndex = 0; - this.toolTipListBox.SetToolTip(this.columnListBox, "Choose one ore more columns to restrict the search operations to the selected col" + - "umns."); - // - // buttonOk - // - this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(3, 309); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 2; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnOkButtonClick); - // - // toolTipEmptyColumnNoHit - // - this.toolTipEmptyColumnNoHit.ToolTipTitle = "Empty column"; - // - // emptyColumnNoHitRadioButton - // - this.emptyColumnNoHitRadioButton.AutoSize = true; - this.emptyColumnNoHitRadioButton.Location = new System.Drawing.Point(6, 21); - this.emptyColumnNoHitRadioButton.Name = "emptyColumnNoHitRadioButton"; - this.emptyColumnNoHitRadioButton.Size = new System.Drawing.Size(75, 24); - this.emptyColumnNoHitRadioButton.TabIndex = 0; - this.emptyColumnNoHitRadioButton.TabStop = true; - this.emptyColumnNoHitRadioButton.Text = "No hit"; - this.toolTipEmptyColumnNoHit.SetToolTip(this.emptyColumnNoHitRadioButton, "No search hit on empty columns"); - this.emptyColumnNoHitRadioButton.UseVisualStyleBackColor = true; - // - // toolTipListBox - // - this.toolTipListBox.ToolTipTitle = "Columns"; - // - // checkBoxExactMatch - // - this.checkBoxExactMatch.AutoSize = true; - this.checkBoxExactMatch.Location = new System.Drawing.Point(9, 11); - this.checkBoxExactMatch.Name = "checkBoxExactMatch"; - this.checkBoxExactMatch.Size = new System.Drawing.Size(123, 24); - this.checkBoxExactMatch.TabIndex = 4; - this.checkBoxExactMatch.Text = "Exact match"; - this.toolTipExactMatch.SetToolTip(this.checkBoxExactMatch, "If selected, the search string must match exactly (no substring search)"); - this.checkBoxExactMatch.UseVisualStyleBackColor = true; - // - // groupBox1 - // - this.groupBox1.Controls.Add(this.emptyColumnUsePrevRadioButton); - this.groupBox1.Controls.Add(this.emptyColumnHitRadioButton); - this.groupBox1.Controls.Add(this.emptyColumnNoHitRadioButton); - this.groupBox1.Location = new System.Drawing.Point(3, 177); - this.groupBox1.Name = "groupBox1"; - this.groupBox1.Size = new System.Drawing.Size(177, 108); - this.groupBox1.TabIndex = 5; - this.groupBox1.TabStop = false; - this.groupBox1.Text = "On empty columns"; - // - // emptyColumnUsePrevRadioButton - // - this.emptyColumnUsePrevRadioButton.AutoSize = true; - this.emptyColumnUsePrevRadioButton.Location = new System.Drawing.Point(6, 76); - this.emptyColumnUsePrevRadioButton.Name = "emptyColumnUsePrevRadioButton"; - this.emptyColumnUsePrevRadioButton.Size = new System.Drawing.Size(155, 24); - this.emptyColumnUsePrevRadioButton.TabIndex = 2; - this.emptyColumnUsePrevRadioButton.TabStop = true; - this.emptyColumnUsePrevRadioButton.Text = "Use prev content"; - this.toolTipPrevContent.SetToolTip(this.emptyColumnUsePrevRadioButton, "An empty column will be a search hit if the previous non-empty column was a searc" + - "h hit"); - this.emptyColumnUsePrevRadioButton.UseVisualStyleBackColor = true; - // - // emptyColumnHitRadioButton - // - this.emptyColumnHitRadioButton.AutoSize = true; - this.emptyColumnHitRadioButton.Location = new System.Drawing.Point(6, 49); - this.emptyColumnHitRadioButton.Name = "emptyColumnHitRadioButton"; - this.emptyColumnHitRadioButton.Size = new System.Drawing.Size(106, 24); - this.emptyColumnHitRadioButton.TabIndex = 1; - this.emptyColumnHitRadioButton.TabStop = true; - this.emptyColumnHitRadioButton.Text = "Search hit"; - this.toolTipSearchHit.SetToolTip(this.emptyColumnHitRadioButton, "An empty column will always be a search hit"); - this.emptyColumnHitRadioButton.UseVisualStyleBackColor = true; - // - // groupBoxExectMatch - // - this.groupBoxExectMatch.Controls.Add(this.checkBoxExactMatch); - this.groupBoxExectMatch.Location = new System.Drawing.Point(3, 130); - this.groupBoxExectMatch.Name = "groupBoxExectMatch"; - this.groupBoxExectMatch.Size = new System.Drawing.Size(177, 41); - this.groupBoxExectMatch.TabIndex = 6; - this.groupBoxExectMatch.TabStop = false; - // - // toolTipSearchHit - // - this.toolTipSearchHit.ToolTipTitle = "Empty column"; - // - // toolTipPrevContent - // - this.toolTipPrevContent.ToolTipTitle = "Empty column"; - // - // toolTipExactMatch - // - this.toolTipExactMatch.ToolTipTitle = "Exact match"; - // - // buttonCancel - // - this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(104, 309); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 7; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // FilterColumnChooser - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(184, 335); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.groupBoxExectMatch); - this.Controls.Add(this.groupBox1); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.columnListBox); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.Name = "FilterColumnChooser"; - this.ShowInTaskbar = false; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Columns"; - this.groupBox1.ResumeLayout(false); - this.groupBox1.PerformLayout(); - this.groupBoxExectMatch.ResumeLayout(false); - this.groupBoxExectMatch.PerformLayout(); - this.ResumeLayout(false); - - } - - #endregion - - private System.Windows.Forms.CheckedListBox columnListBox; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.ToolTip toolTipEmptyColumnNoHit; - private System.Windows.Forms.ToolTip toolTipListBox; - private System.Windows.Forms.CheckBox checkBoxExactMatch; - private System.Windows.Forms.GroupBox groupBox1; - private System.Windows.Forms.RadioButton emptyColumnUsePrevRadioButton; - private System.Windows.Forms.RadioButton emptyColumnHitRadioButton; - private System.Windows.Forms.RadioButton emptyColumnNoHitRadioButton; - private System.Windows.Forms.GroupBox groupBoxExectMatch; - private System.Windows.Forms.ToolTip toolTipExactMatch; - private System.Windows.Forms.ToolTip toolTipSearchHit; - private System.Windows.Forms.ToolTip toolTipPrevContent; - private System.Windows.Forms.Button buttonCancel; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/FilterColumnChooser.cs b/src/LogExpert/Dialogs/FilterColumnChooser.cs deleted file mode 100644 index dffb2a95..00000000 --- a/src/LogExpert/Dialogs/FilterColumnChooser.cs +++ /dev/null @@ -1,72 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using LogExpert.Classes.Filter; - -namespace LogExpert.Dialogs -{ - public partial class FilterColumnChooser : Form - { - #region Fields - - private readonly ILogLineColumnizer _columnizer; - private readonly FilterParams _filterParams; - - #endregion - - #region cTor - - public FilterColumnChooser(FilterParams filterParams) - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - columnListBox.ItemHeight = columnListBox.Font.Height; - - _columnizer = filterParams.currentColumnizer; - _filterParams = filterParams; - - Init(); - } - - #endregion - - #region Private Methods - - private void Init() - { - int count = _columnizer.GetColumnCount(); - string[] names = _columnizer.GetColumnNames(); - - for (int i = 0; i < count; ++i) - { - columnListBox.Items.Add(names[i], _filterParams.columnList.Contains(i)); - } - - emptyColumnUsePrevRadioButton.Checked = _filterParams.emptyColumnUsePrev; - emptyColumnHitRadioButton.Checked = _filterParams.emptyColumnHit; - emptyColumnNoHitRadioButton.Checked = _filterParams.emptyColumnHit == false && _filterParams.emptyColumnUsePrev == false; - checkBoxExactMatch.Checked = _filterParams.exactColumnMatch; - } - - #endregion - - #region Events handler - - private void OnOkButtonClick(object sender, EventArgs e) - { - _filterParams.columnList.Clear(); - foreach (int colNum in columnListBox.CheckedIndices) - { - _filterParams.columnList.Add(colNum); - } - _filterParams.emptyColumnUsePrev = emptyColumnUsePrevRadioButton.Checked; - _filterParams.emptyColumnHit = emptyColumnHitRadioButton.Checked; - _filterParams.exactColumnMatch = checkBoxExactMatch.Checked; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/FilterSelectorForm.Designer.cs b/src/LogExpert/Dialogs/FilterSelectorForm.Designer.cs deleted file mode 100644 index 6b01e99f..00000000 --- a/src/LogExpert/Dialogs/FilterSelectorForm.Designer.cs +++ /dev/null @@ -1,156 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class FilterSelectorForm - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FilterSelectorForm)); - this.filterComboBox = new System.Windows.Forms.ComboBox(); - this.label1 = new System.Windows.Forms.Label(); - this.okButton = new System.Windows.Forms.Button(); - this.cancelButton = new System.Windows.Forms.Button(); - this.commentTextBox = new System.Windows.Forms.TextBox(); - this.applyToAllCheckBox = new System.Windows.Forms.CheckBox(); - this.helpProvider1 = new System.Windows.Forms.HelpProvider(); - this.configButton = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // filterComboBox - // - this.filterComboBox.DisplayMember = "Text"; - this.filterComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.filterComboBox.FormattingEnabled = true; - this.filterComboBox.Location = new System.Drawing.Point(12, 25); - this.filterComboBox.Name = "filterComboBox"; - this.filterComboBox.Size = new System.Drawing.Size(298, 21); - this.filterComboBox.TabIndex = 0; - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(13, 6); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(108, 13); - this.label1.TabIndex = 1; - this.label1.Text = "Choose a columnizer:"; - // - // okButton - // - this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okButton.Location = new System.Drawing.Point(154, 194); - this.okButton.Name = "okButton"; - this.okButton.Size = new System.Drawing.Size(75, 23); - this.okButton.TabIndex = 2; - this.okButton.Text = "OK"; - this.okButton.UseVisualStyleBackColor = true; - // - // cancelButton - // - this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(235, 194); - this.cancelButton.Name = "cancelButton"; - this.cancelButton.Size = new System.Drawing.Size(75, 23); - this.cancelButton.TabIndex = 3; - this.cancelButton.Text = "Cancel"; - this.cancelButton.UseVisualStyleBackColor = true; - // - // commentTextBox - // - this.commentTextBox.Location = new System.Drawing.Point(12, 81); - this.commentTextBox.Multiline = true; - this.commentTextBox.Name = "commentTextBox"; - this.commentTextBox.ReadOnly = true; - this.commentTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.commentTextBox.Size = new System.Drawing.Size(298, 89); - this.commentTextBox.TabIndex = 4; - // - // applyToAllCheckBox - // - this.applyToAllCheckBox.AutoSize = true; - this.applyToAllCheckBox.Location = new System.Drawing.Point(12, 176); - this.applyToAllCheckBox.Name = "applyToAllCheckBox"; - this.applyToAllCheckBox.Size = new System.Drawing.Size(125, 17); - this.applyToAllCheckBox.TabIndex = 6; - this.applyToAllCheckBox.Text = "Apply to all open files"; - this.applyToAllCheckBox.UseVisualStyleBackColor = true; - // - // helpProvider1 - // - this.helpProvider1.HelpNamespace = "LogExpert.chm"; - // - // configButton - // - this.configButton.Location = new System.Drawing.Point(235, 52); - this.configButton.Name = "configButton"; - this.configButton.Size = new System.Drawing.Size(75, 23); - this.configButton.TabIndex = 7; - this.configButton.Text = "Config..."; - this.configButton.UseVisualStyleBackColor = true; - this.configButton.Click += new System.EventHandler(this.OnConfigButtonClick); - // - // FilterSelectorForm - // - this.AcceptButton = this.okButton; - this.CancelButton = this.cancelButton; - this.ClientSize = new System.Drawing.Size(322, 232); - this.Controls.Add(this.configButton); - this.Controls.Add(this.applyToAllCheckBox); - this.Controls.Add(this.commentTextBox); - this.Controls.Add(this.cancelButton); - this.Controls.Add(this.okButton); - this.Controls.Add(this.label1); - this.Controls.Add(this.filterComboBox); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.helpProvider1.SetHelpKeyword(this, "Columnizers.htm"); - this.helpProvider1.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "FilterSelectorForm"; - this.helpProvider1.SetShowHelp(this, true); - this.ShowIcon = false; - this.ShowInTaskbar = false; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Columnizer"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.ComboBox filterComboBox; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Button okButton; - private System.Windows.Forms.Button cancelButton; - private System.Windows.Forms.TextBox commentTextBox; - private System.Windows.Forms.CheckBox applyToAllCheckBox; - private System.Windows.Forms.HelpProvider helpProvider1; - private System.Windows.Forms.Button configButton; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/FilterSelectorForm.cs b/src/LogExpert/Dialogs/FilterSelectorForm.cs deleted file mode 100644 index 9410c479..00000000 --- a/src/LogExpert/Dialogs/FilterSelectorForm.cs +++ /dev/null @@ -1,99 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; -using LogExpert.Config; - -namespace LogExpert.Dialogs -{ - public partial class FilterSelectorForm : Form - { - #region Fields - - private readonly ILogLineColumnizerCallback _callback; - private readonly IList _columnizerList; - - #endregion - - #region cTor - - public FilterSelectorForm(IList existingColumnizerList, ILogLineColumnizer currentColumnizer, ILogLineColumnizerCallback callback) - { - SelectedColumnizer = currentColumnizer; - _callback = callback; - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - filterComboBox.SelectedIndexChanged += OnFilterComboBoxSelectedIndexChanged; - - // for the currently selected columnizer use the current instance and not the template instance from - // columnizer registry. This ensures that changes made in columnizer config dialogs - // will apply to the current instance - _columnizerList = new List(); - - foreach (ILogLineColumnizer col in existingColumnizerList) - { - _columnizerList.Add(col.GetType() == SelectedColumnizer.GetType() ? SelectedColumnizer : col); - } - - foreach (ILogLineColumnizer col in _columnizerList) - { - filterComboBox.Items.Add(col); - } - - foreach (ILogLineColumnizer columnizer in _columnizerList) - { - if (columnizer.GetType() == SelectedColumnizer.GetType()) - { - filterComboBox.SelectedItem = columnizer; - break; - } - } - } - - #endregion - - #region Properties - - public ILogLineColumnizer SelectedColumnizer { get; private set; } - - public bool ApplyToAll => applyToAllCheckBox.Checked; - - public bool IsConfigPressed { get; private set; } - - #endregion - - #region Events handler - - private void OnFilterComboBoxSelectedIndexChanged(object sender, EventArgs e) - { - ILogLineColumnizer col = _columnizerList[filterComboBox.SelectedIndex]; - SelectedColumnizer = col; - string description = col.GetDescription(); - description += "\r\nSupports timeshift: " + (SelectedColumnizer.IsTimeshiftImplemented() ? "Yes" : "No"); - commentTextBox.Text = description; - configButton.Enabled = SelectedColumnizer is IColumnizerConfigurator; - } - - - private void OnConfigButtonClick(object sender, EventArgs e) - { - if (SelectedColumnizer is IColumnizerConfigurator configurator) - { - string configDir = ConfigManager.ConfigDir; - - if (ConfigManager.Settings.Preferences.PortableMode) - { - configDir = ConfigManager.PortableModeDir; - } - - configurator.Configure(_callback, configDir); - IsConfigPressed = true; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/GotoLineDialog.Designer.cs b/src/LogExpert/Dialogs/GotoLineDialog.Designer.cs deleted file mode 100644 index 7e99ca2d..00000000 --- a/src/LogExpert/Dialogs/GotoLineDialog.Designer.cs +++ /dev/null @@ -1,108 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class GotoLineDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.labelLineNumber = new System.Windows.Forms.Label(); - this.buttonOk = new System.Windows.Forms.Button(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.lineNumberTextBox = new System.Windows.Forms.TextBox(); - this.SuspendLayout(); - // - // labelLineNumber - // - this.labelLineNumber.AutoSize = true; - this.labelLineNumber.Location = new System.Drawing.Point(12, 30); - this.labelLineNumber.Name = "labelLineNumber"; - this.labelLineNumber.Size = new System.Drawing.Size(101, 20); - this.labelLineNumber.TabIndex = 0; - this.labelLineNumber.Text = "Line number:"; - // - // buttonOk - // - this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); - this.buttonOk.AutoSize = true; - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(15, 90); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 30); - this.buttonOk.TabIndex = 2; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.okButton_Click); - // - // buttonCancel - // - this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonCancel.AutoSize = true; - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(149, 90); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 30); - this.buttonCancel.TabIndex = 3; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // lineNumberTextBox - // - this.lineNumberTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); - this.lineNumberTextBox.Location = new System.Drawing.Point(124, 27); - this.lineNumberTextBox.Name = "lineNumberTextBox"; - this.lineNumberTextBox.Size = new System.Drawing.Size(100, 26); - this.lineNumberTextBox.TabIndex = 0; - // - // GotoLineDialog - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(243, 130); - this.Controls.Add(this.lineNumberTextBox); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.labelLineNumber); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "GotoLineDialog"; - this.ShowIcon = false; - this.ShowInTaskbar = false; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Go to line"; - this.Load += new System.EventHandler(this.GotoLineDialog_Load); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Label labelLineNumber; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.TextBox lineNumberTextBox; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/GotoLineDialog.cs b/src/LogExpert/Dialogs/GotoLineDialog.cs deleted file mode 100644 index 622a1ccb..00000000 --- a/src/LogExpert/Dialogs/GotoLineDialog.cs +++ /dev/null @@ -1,53 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class GotoLineDialog : Form - { - #region Fields - - #endregion - - #region cTor - - public GotoLineDialog(Form parent) - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - Owner = parent; - } - - #endregion - - #region Properties - - public int Line { get; private set; } - - #endregion - - #region Events handler - - private void GotoLineDialog_Load(object sender, EventArgs e) - { - } - - private void okButton_Click(object sender, EventArgs e) - { - try - { - Line = int.Parse(lineNumberTextBox.Text); - } - catch (Exception) - { - Line = -1; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/HighlightDialog.Designer.cs b/src/LogExpert/Dialogs/HighlightDialog.Designer.cs deleted file mode 100644 index f3c92b7a..00000000 --- a/src/LogExpert/Dialogs/HighlightDialog.Designer.cs +++ /dev/null @@ -1,727 +0,0 @@ -using LogExpert.Properties; -using System.Drawing; - -namespace LogExpert.Dialogs -{ - partial class HighlightDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HighlightDialog)); - listBoxHighlight = new System.Windows.Forms.ListBox(); - btnAdd = new System.Windows.Forms.Button(); - btnDelete = new System.Windows.Forms.Button(); - btnMoveUp = new System.Windows.Forms.Button(); - btnMoveDown = new System.Windows.Forms.Button(); - labelForgroundColor = new System.Windows.Forms.Label(); - labelBackgroundColor = new System.Windows.Forms.Label(); - btnOk = new System.Windows.Forms.Button(); - btnCancel = new System.Windows.Forms.Button(); - textBoxSearchString = new System.Windows.Forms.TextBox(); - labelSearchString = new System.Windows.Forms.Label(); - btnApply = new System.Windows.Forms.Button(); - btnCustomForeColor = new System.Windows.Forms.Button(); - btnCustomBackColor = new System.Windows.Forms.Button(); - checkBoxRegex = new System.Windows.Forms.CheckBox(); - checkBoxCaseSensitive = new System.Windows.Forms.CheckBox(); - checkBoxDontDirtyLed = new System.Windows.Forms.CheckBox(); - groupBoxLineMatchCriteria = new System.Windows.Forms.GroupBox(); - groupBoxColoring = new System.Windows.Forms.GroupBox(); - checkBoxNoBackground = new System.Windows.Forms.CheckBox(); - checkBoxBold = new System.Windows.Forms.CheckBox(); - checkBoxWordMatch = new System.Windows.Forms.CheckBox(); - colorBoxForeground = new ColorComboBox(); - colorBoxBackground = new ColorComboBox(); - groupBoxActions = new System.Windows.Forms.GroupBox(); - btnBookmarkComment = new System.Windows.Forms.Button(); - btnSelectPlugin = new System.Windows.Forms.Button(); - checkBoxPlugin = new System.Windows.Forms.CheckBox(); - checkBoxStopTail = new System.Windows.Forms.CheckBox(); - checkBoxBookmark = new System.Windows.Forms.CheckBox(); - helpProvider = new System.Windows.Forms.HelpProvider(); - groupBox4 = new System.Windows.Forms.GroupBox(); - btnImportGroup = new System.Windows.Forms.Button(); - btnExportGroup = new System.Windows.Forms.Button(); - btnMoveGroupDown = new System.Windows.Forms.Button(); - btnMoveGroupUp = new System.Windows.Forms.Button(); - labelAssignNamesToGroups = new System.Windows.Forms.Label(); - btnCopyGroup = new System.Windows.Forms.Button(); - btnDeleteGroup = new System.Windows.Forms.Button(); - btnNewGroup = new System.Windows.Forms.Button(); - comboBoxGroups = new System.Windows.Forms.ComboBox(); - toolTip = new System.Windows.Forms.ToolTip(components); - pnlBackground = new System.Windows.Forms.Panel(); - groupBoxLineMatchCriteria.SuspendLayout(); - groupBoxColoring.SuspendLayout(); - groupBoxActions.SuspendLayout(); - groupBox4.SuspendLayout(); - pnlBackground.SuspendLayout(); - SuspendLayout(); - // - // listBoxHighlight - // - listBoxHighlight.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - listBoxHighlight.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; - listBoxHighlight.FormattingEnabled = true; - listBoxHighlight.Location = new Point(32, 160); - listBoxHighlight.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - listBoxHighlight.Name = "listBoxHighlight"; - listBoxHighlight.Size = new Size(487, 228); - listBoxHighlight.TabIndex = 0; - listBoxHighlight.SelectedIndexChanged += OnListBoxHighlightSelectedIndexChanged; - // - // btnAdd - // - btnAdd.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnAdd.Location = new Point(529, 218); - btnAdd.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnAdd.Name = "btnAdd"; - btnAdd.Size = new Size(158, 35); - btnAdd.TabIndex = 1; - btnAdd.Text = "&Add"; - toolTip.SetToolTip(btnAdd, "Create a new hilight item from information below"); - btnAdd.UseVisualStyleBackColor = true; - btnAdd.Click += OnAddButtonClick; - // - // btnDelete - // - btnDelete.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnDelete.Location = new Point(529, 263); - btnDelete.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnDelete.Name = "btnDelete"; - btnDelete.Size = new Size(158, 35); - btnDelete.TabIndex = 2; - btnDelete.Text = "D&elete"; - toolTip.SetToolTip(btnDelete, "Delete the current hilight"); - btnDelete.UseVisualStyleBackColor = true; - btnDelete.Click += OnDeleteButtonClick; - // - // btnMoveUp - // - btnMoveUp.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnMoveUp.Location = new Point(529, 160); - btnMoveUp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnMoveUp.Name = "btnMoveUp"; - btnMoveUp.Size = new Size(75, 35); - btnMoveUp.TabIndex = 3; - btnMoveUp.Text = "&Up"; - toolTip.SetToolTip(btnMoveUp, "Move the current hilight one position up"); - btnMoveUp.UseVisualStyleBackColor = true; - btnMoveUp.Click += OnBtnMoveUpClick; - // - // btnMoveDown - // - btnMoveDown.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnMoveDown.Location = new Point(612, 160); - btnMoveDown.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnMoveDown.Name = "btnMoveDown"; - btnMoveDown.Size = new Size(75, 35); - btnMoveDown.TabIndex = 4; - btnMoveDown.Text = "&Down"; - toolTip.SetToolTip(btnMoveDown, "Move the current hilight one position down"); - btnMoveDown.UseVisualStyleBackColor = true; - btnMoveDown.Click += OnBtnMoveDownClick; - // - // labelForgroundColor - // - labelForgroundColor.AutoSize = true; - labelForgroundColor.Location = new Point(9, 38); - labelForgroundColor.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelForgroundColor.Name = "labelForgroundColor"; - labelForgroundColor.Size = new Size(99, 15); - labelForgroundColor.TabIndex = 6; - labelForgroundColor.Text = "Foreground color"; - // - // labelBackgroundColor - // - labelBackgroundColor.AutoSize = true; - labelBackgroundColor.Location = new Point(9, 115); - labelBackgroundColor.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelBackgroundColor.Name = "labelBackgroundColor"; - labelBackgroundColor.Size = new Size(101, 15); - labelBackgroundColor.TabIndex = 8; - labelBackgroundColor.Text = "Background color"; - // - // btnOk - // - btnOk.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; - btnOk.Location = new Point(449, 832); - btnOk.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnOk.Name = "btnOk"; - btnOk.Size = new Size(112, 35); - btnOk.TabIndex = 9; - btnOk.Text = "OK"; - btnOk.UseVisualStyleBackColor = true; - btnOk.Click += OnBtnOkClick; - // - // btnCancel - // - btnCancel.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - btnCancel.Location = new Point(576, 832); - btnCancel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnCancel.Name = "btnCancel"; - btnCancel.Size = new Size(112, 35); - btnCancel.TabIndex = 10; - btnCancel.Text = "Cancel"; - btnCancel.UseVisualStyleBackColor = true; - // - // textBoxSearchString - // - textBoxSearchString.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - textBoxSearchString.Location = new Point(9, 55); - textBoxSearchString.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - textBoxSearchString.Name = "textBoxSearchString"; - textBoxSearchString.Size = new Size(639, 23); - textBoxSearchString.TabIndex = 11; - textBoxSearchString.TextChanged += ChangeToDirty; - // - // labelSearchString - // - labelSearchString.AutoSize = true; - labelSearchString.Location = new Point(9, 31); - labelSearchString.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelSearchString.Name = "labelSearchString"; - labelSearchString.Size = new Size(78, 15); - labelSearchString.TabIndex = 12; - labelSearchString.Text = "Search string:"; - // - // btnApply - // - btnApply.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnApply.Enabled = false; - btnApply.Image = (Image)resources.GetObject("btnApply.Image"); - btnApply.ImageAlign = ContentAlignment.MiddleRight; - btnApply.Location = new Point(529, 308); - btnApply.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnApply.Name = "btnApply"; - btnApply.Size = new Size(158, 35); - btnApply.TabIndex = 13; - btnApply.Text = "A&pply"; - toolTip.SetToolTip(btnApply, "Apply changes below to current hiligth"); - btnApply.UseVisualStyleBackColor = true; - btnApply.Click += OnBtnApplyClick; - // - // btnCustomForeColor - // - btnCustomForeColor.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnCustomForeColor.Location = new Point(247, 60); - btnCustomForeColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnCustomForeColor.Name = "btnCustomForeColor"; - btnCustomForeColor.Size = new Size(78, 35); - btnCustomForeColor.TabIndex = 14; - btnCustomForeColor.Text = "Custom"; - toolTip.SetToolTip(btnCustomForeColor, "Pick a custom foreground color"); - btnCustomForeColor.UseVisualStyleBackColor = true; - btnCustomForeColor.Click += OnBtnCustomForeColorClick; - // - // btnCustomBackColor - // - btnCustomBackColor.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnCustomBackColor.Location = new Point(247, 137); - btnCustomBackColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnCustomBackColor.Name = "btnCustomBackColor"; - btnCustomBackColor.Size = new Size(78, 35); - btnCustomBackColor.TabIndex = 15; - btnCustomBackColor.Text = "Custom"; - toolTip.SetToolTip(btnCustomBackColor, "Pick a custom background color"); - btnCustomBackColor.UseVisualStyleBackColor = true; - btnCustomBackColor.Click += OnBtnCustomBackColorClick; - // - // checkBoxRegex - // - checkBoxRegex.AutoSize = true; - checkBoxRegex.Location = new Point(180, 95); - checkBoxRegex.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxRegex.Name = "checkBoxRegex"; - checkBoxRegex.Size = new Size(57, 19); - checkBoxRegex.TabIndex = 16; - checkBoxRegex.Text = "RegEx"; - toolTip.SetToolTip(checkBoxRegex, "Whether the string is a regular expresion"); - checkBoxRegex.UseVisualStyleBackColor = true; - checkBoxRegex.CheckedChanged += ChangeToDirty; - checkBoxRegex.MouseUp += OnChkBoxRegexMouseUp; - // - // checkBoxCaseSensitive - // - checkBoxCaseSensitive.AutoSize = true; - checkBoxCaseSensitive.Location = new Point(14, 95); - checkBoxCaseSensitive.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxCaseSensitive.Name = "checkBoxCaseSensitive"; - checkBoxCaseSensitive.Size = new Size(99, 19); - checkBoxCaseSensitive.TabIndex = 17; - checkBoxCaseSensitive.Text = "Case sensitive"; - toolTip.SetToolTip(checkBoxCaseSensitive, "Whether the string will match uppercases and lowercases"); - checkBoxCaseSensitive.UseVisualStyleBackColor = true; - checkBoxCaseSensitive.CheckedChanged += ChangeToDirty; - // - // checkBoxDontDirtyLed - // - checkBoxDontDirtyLed.AutoSize = true; - checkBoxDontDirtyLed.Location = new Point(15, 38); - checkBoxDontDirtyLed.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxDontDirtyLed.Name = "checkBoxDontDirtyLed"; - checkBoxDontDirtyLed.Size = new Size(118, 19); - checkBoxDontDirtyLed.TabIndex = 18; - checkBoxDontDirtyLed.Text = "Don't lit dirty LED"; - toolTip.SetToolTip(checkBoxDontDirtyLed, "When matching a line, don't mark the page as \"dirty\""); - checkBoxDontDirtyLed.UseVisualStyleBackColor = true; - checkBoxDontDirtyLed.CheckedChanged += ChangeToDirty; - // - // groupBoxLineMatchCriteria - // - groupBoxLineMatchCriteria.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - groupBoxLineMatchCriteria.Controls.Add(textBoxSearchString); - groupBoxLineMatchCriteria.Controls.Add(labelSearchString); - groupBoxLineMatchCriteria.Controls.Add(checkBoxRegex); - groupBoxLineMatchCriteria.Controls.Add(checkBoxCaseSensitive); - groupBoxLineMatchCriteria.Location = new Point(18, 437); - groupBoxLineMatchCriteria.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxLineMatchCriteria.Name = "groupBoxLineMatchCriteria"; - groupBoxLineMatchCriteria.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxLineMatchCriteria.Size = new Size(671, 135); - groupBoxLineMatchCriteria.TabIndex = 19; - groupBoxLineMatchCriteria.TabStop = false; - groupBoxLineMatchCriteria.Text = "Line match criteria"; - // - // groupBoxColoring - // - groupBoxColoring.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - groupBoxColoring.Controls.Add(checkBoxNoBackground); - groupBoxColoring.Controls.Add(checkBoxBold); - groupBoxColoring.Controls.Add(checkBoxWordMatch); - groupBoxColoring.Controls.Add(labelForgroundColor); - groupBoxColoring.Controls.Add(colorBoxForeground); - groupBoxColoring.Controls.Add(btnCustomForeColor); - groupBoxColoring.Controls.Add(btnCustomBackColor); - groupBoxColoring.Controls.Add(labelBackgroundColor); - groupBoxColoring.Controls.Add(colorBoxBackground); - groupBoxColoring.Location = new Point(18, 581); - groupBoxColoring.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxColoring.Name = "groupBoxColoring"; - groupBoxColoring.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxColoring.Size = new Size(349, 286); - groupBoxColoring.TabIndex = 20; - groupBoxColoring.TabStop = false; - groupBoxColoring.Text = "Coloring"; - // - // checkBoxNoBackground - // - checkBoxNoBackground.AutoSize = true; - checkBoxNoBackground.Enabled = false; - checkBoxNoBackground.Location = new Point(141, 240); - checkBoxNoBackground.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxNoBackground.Name = "checkBoxNoBackground"; - checkBoxNoBackground.Size = new Size(109, 19); - checkBoxNoBackground.TabIndex = 18; - checkBoxNoBackground.Text = "No Background"; - toolTip.SetToolTip(checkBoxNoBackground, "Don't set the background color"); - checkBoxNoBackground.UseVisualStyleBackColor = true; - checkBoxNoBackground.CheckedChanged += OnChkBoxNoBackgroundCheckedChanged; - // - // checkBoxBold - // - checkBoxBold.AutoSize = true; - checkBoxBold.Location = new Point(9, 205); - checkBoxBold.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxBold.Name = "checkBoxBold"; - checkBoxBold.Size = new Size(50, 19); - checkBoxBold.TabIndex = 17; - checkBoxBold.Text = "Bold"; - toolTip.SetToolTip(checkBoxBold, "Display the line in bold characters"); - checkBoxBold.UseVisualStyleBackColor = true; - checkBoxBold.CheckedChanged += OnChkBoxBoldCheckedChanged; - // - // checkBoxWordMatch - // - checkBoxWordMatch.AutoSize = true; - checkBoxWordMatch.Location = new Point(9, 240); - checkBoxWordMatch.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxWordMatch.Name = "checkBoxWordMatch"; - checkBoxWordMatch.Size = new Size(89, 19); - checkBoxWordMatch.TabIndex = 16; - checkBoxWordMatch.Text = "Word mode"; - toolTip.SetToolTip(checkBoxWordMatch, "Don't highlight the whole line but only the matching keywords"); - checkBoxWordMatch.UseVisualStyleBackColor = true; - checkBoxWordMatch.CheckedChanged += OnChkBoxWordMatchCheckedChanged; - // - // colorBoxForeground - // - colorBoxForeground.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - colorBoxForeground.CustomColor = Color.Black; - colorBoxForeground.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; - colorBoxForeground.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - colorBoxForeground.FormattingEnabled = true; - colorBoxForeground.Items.AddRange(new object[] { Color.Black, 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, Color.Black, 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, Color.Black, 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, Color.Black, 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 }); - colorBoxForeground.Location = new Point(8, 63); - colorBoxForeground.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - colorBoxForeground.Name = "colorBoxForeground"; - colorBoxForeground.Size = new Size(229, 24); - colorBoxForeground.TabIndex = 5; - colorBoxForeground.SelectedIndexChanged += ChangeToDirty; - // - // colorBoxBackground - // - colorBoxBackground.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - colorBoxBackground.CustomColor = Color.Black; - colorBoxBackground.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; - colorBoxBackground.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - colorBoxBackground.FormattingEnabled = true; - colorBoxBackground.Items.AddRange(new object[] { Color.Black, 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, Color.Black, 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, Color.Black, 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, Color.Black, 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 }); - colorBoxBackground.Location = new Point(9, 140); - colorBoxBackground.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - colorBoxBackground.Name = "colorBoxBackground"; - colorBoxBackground.Size = new Size(229, 24); - colorBoxBackground.TabIndex = 7; - colorBoxBackground.SelectedIndexChanged += ChangeToDirty; - // - // groupBoxActions - // - groupBoxActions.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - groupBoxActions.Controls.Add(btnBookmarkComment); - groupBoxActions.Controls.Add(btnSelectPlugin); - groupBoxActions.Controls.Add(checkBoxPlugin); - groupBoxActions.Controls.Add(checkBoxStopTail); - groupBoxActions.Controls.Add(checkBoxBookmark); - groupBoxActions.Controls.Add(checkBoxDontDirtyLed); - groupBoxActions.Location = new Point(377, 581); - groupBoxActions.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxActions.Name = "groupBoxActions"; - groupBoxActions.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxActions.Size = new Size(312, 195); - groupBoxActions.TabIndex = 21; - groupBoxActions.TabStop = false; - groupBoxActions.Text = "Actions"; - // - // btnBookmarkComment - // - btnBookmarkComment.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnBookmarkComment.Location = new Point(210, 69); - btnBookmarkComment.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnBookmarkComment.Name = "btnBookmarkComment"; - btnBookmarkComment.Size = new Size(81, 31); - btnBookmarkComment.TabIndex = 23; - btnBookmarkComment.Text = "Text..."; - btnBookmarkComment.UseVisualStyleBackColor = true; - btnBookmarkComment.Click += OnBtnBookmarkCommentClick; - // - // btnSelectPlugin - // - btnSelectPlugin.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnSelectPlugin.Location = new Point(210, 143); - btnSelectPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnSelectPlugin.Name = "btnSelectPlugin"; - btnSelectPlugin.Size = new Size(81, 31); - btnSelectPlugin.TabIndex = 22; - btnSelectPlugin.Text = "Select..."; - btnSelectPlugin.UseVisualStyleBackColor = true; - btnSelectPlugin.Click += OnPluginButtonClick; - // - // checkBoxPlugin - // - checkBoxPlugin.AutoSize = true; - checkBoxPlugin.Location = new Point(15, 148); - checkBoxPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxPlugin.Name = "checkBoxPlugin"; - checkBoxPlugin.Size = new Size(60, 19); - checkBoxPlugin.TabIndex = 21; - checkBoxPlugin.Text = "Plugin"; - toolTip.SetToolTip(checkBoxPlugin, "When matching a line, call a keyword action plugin"); - checkBoxPlugin.UseVisualStyleBackColor = true; - checkBoxPlugin.CheckedChanged += OnChkBoxPluginCheckedChanged; - // - // checkBoxStopTail - // - checkBoxStopTail.AutoSize = true; - checkBoxStopTail.Location = new Point(15, 111); - checkBoxStopTail.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxStopTail.Name = "checkBoxStopTail"; - checkBoxStopTail.Size = new Size(109, 19); - checkBoxStopTail.TabIndex = 20; - checkBoxStopTail.Text = "Stop Follow Tail"; - toolTip.SetToolTip(checkBoxStopTail, "When matching a line, stop automatic scrolling"); - checkBoxStopTail.UseVisualStyleBackColor = true; - checkBoxStopTail.CheckedChanged += ChangeToDirty; - // - // checkBoxBookmark - // - checkBoxBookmark.AutoSize = true; - checkBoxBookmark.Location = new Point(15, 74); - checkBoxBookmark.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxBookmark.Name = "checkBoxBookmark"; - checkBoxBookmark.Size = new Size(99, 19); - checkBoxBookmark.TabIndex = 19; - checkBoxBookmark.Text = "Set bookmark"; - toolTip.SetToolTip(checkBoxBookmark, "When matching a line, create a new bookmark for it"); - checkBoxBookmark.UseVisualStyleBackColor = true; - checkBoxBookmark.CheckedChanged += ChangeToDirty; - // - // helpProvider - // - helpProvider.HelpNamespace = "LogExpert.chm"; - helpProvider.Tag = ""; - // - // groupBox4 - // - groupBox4.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - groupBox4.Controls.Add(btnImportGroup); - groupBox4.Controls.Add(btnExportGroup); - groupBox4.Controls.Add(btnMoveGroupDown); - groupBox4.Controls.Add(btnMoveGroupUp); - groupBox4.Controls.Add(labelAssignNamesToGroups); - groupBox4.Controls.Add(btnCopyGroup); - groupBox4.Controls.Add(btnDeleteGroup); - groupBox4.Controls.Add(btnNewGroup); - groupBox4.Controls.Add(comboBoxGroups); - groupBox4.Location = new Point(18, 5); - groupBox4.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBox4.Name = "groupBox4"; - groupBox4.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBox4.Size = new Size(671, 129); - groupBox4.TabIndex = 22; - groupBox4.TabStop = false; - groupBox4.Text = "Groups"; - // - // btnImportGroup - // - btnImportGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - btnImportGroup.Location = new Point(333, 26); - btnImportGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnImportGroup.Name = "btnImportGroup"; - btnImportGroup.Size = new Size(75, 35); - btnImportGroup.TabIndex = 7; - btnImportGroup.Text = "Import"; - toolTip.SetToolTip(btnImportGroup, "Import highlight groups"); - btnImportGroup.UseVisualStyleBackColor = true; - btnImportGroup.Click += OnBtnImportGroupClick; - // - // btnExportGroup - // - btnExportGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - btnExportGroup.Location = new Point(333, 75); - btnExportGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnExportGroup.Name = "btnExportGroup"; - btnExportGroup.Size = new Size(75, 35); - btnExportGroup.TabIndex = 8; - btnExportGroup.Text = "Export"; - toolTip.SetToolTip(btnExportGroup, "Export highlight groups"); - btnExportGroup.UseVisualStyleBackColor = true; - btnExportGroup.Click += OnBtnExportGroupClick; - // - // btnMoveGroupDown - // - btnMoveGroupDown.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnMoveGroupDown.Location = new Point(582, 75); - btnMoveGroupDown.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnMoveGroupDown.Name = "btnMoveGroupDown"; - btnMoveGroupDown.Size = new Size(75, 35); - btnMoveGroupDown.TabIndex = 6; - btnMoveGroupDown.Text = "Down"; - toolTip.SetToolTip(btnMoveGroupDown, "Move the current hilight group one position down"); - btnMoveGroupDown.UseVisualStyleBackColor = true; - btnMoveGroupDown.Click += OnBtnGroupDownClick; - // - // btnMoveGroupUp - // - btnMoveGroupUp.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right; - btnMoveGroupUp.Location = new Point(499, 75); - btnMoveGroupUp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnMoveGroupUp.Name = "btnMoveGroupUp"; - btnMoveGroupUp.Size = new Size(75, 35); - btnMoveGroupUp.TabIndex = 5; - btnMoveGroupUp.Text = "Up"; - toolTip.SetToolTip(btnMoveGroupUp, "Move the current hilight group one position up"); - btnMoveGroupUp.UseVisualStyleBackColor = true; - btnMoveGroupUp.Click += OnBtnGroupUpClick; - // - // labelAssignNamesToGroups - // - labelAssignNamesToGroups.AutoSize = true; - labelAssignNamesToGroups.Location = new Point(9, 88); - labelAssignNamesToGroups.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelAssignNamesToGroups.Name = "labelAssignNamesToGroups"; - labelAssignNamesToGroups.Size = new Size(276, 15); - labelAssignNamesToGroups.TabIndex = 4; - labelAssignNamesToGroups.Text = "You can assign groups to file names in the settings."; - // - // btnCopyGroup - // - btnCopyGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - btnCopyGroup.Location = new Point(582, 26); - btnCopyGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnCopyGroup.Name = "btnCopyGroup"; - btnCopyGroup.Size = new Size(75, 35); - btnCopyGroup.TabIndex = 3; - btnCopyGroup.Text = "Copy"; - toolTip.SetToolTip(btnCopyGroup, "Copy the current hilight group into a new one"); - btnCopyGroup.UseVisualStyleBackColor = true; - btnCopyGroup.Click += OnBtnCopyGroupClick; - // - // btnDeleteGroup - // - btnDeleteGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - btnDeleteGroup.Location = new Point(499, 26); - btnDeleteGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnDeleteGroup.Name = "btnDeleteGroup"; - btnDeleteGroup.Size = new Size(75, 35); - btnDeleteGroup.TabIndex = 2; - btnDeleteGroup.Text = "Del"; - toolTip.SetToolTip(btnDeleteGroup, "Delete the current hilight group"); - btnDeleteGroup.UseVisualStyleBackColor = true; - btnDeleteGroup.Click += OnBtnDelGroupClick; - // - // btnNewGroup - // - btnNewGroup.Anchor = System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right; - btnNewGroup.Location = new Point(416, 26); - btnNewGroup.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - btnNewGroup.Name = "btnNewGroup"; - btnNewGroup.Size = new Size(75, 35); - btnNewGroup.TabIndex = 1; - btnNewGroup.Text = "New group"; - btnNewGroup.TextAlign = ContentAlignment.MiddleLeft; - toolTip.SetToolTip(btnNewGroup, "Create a new empty hilight group"); - btnNewGroup.UseVisualStyleBackColor = true; - btnNewGroup.Click += OnBtnNewGroupClick; - // - // comboBoxGroups - // - comboBoxGroups.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - comboBoxGroups.DisplayMember = "GroupName"; - comboBoxGroups.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; - comboBoxGroups.Location = new Point(14, 32); - comboBoxGroups.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - comboBoxGroups.Name = "comboBoxGroups"; - comboBoxGroups.Size = new Size(311, 24); - comboBoxGroups.TabIndex = 0; - toolTip.SetToolTip(comboBoxGroups, "Choose a group to create different highlight settings. Type in a name to change in the name of a group."); - comboBoxGroups.DrawItem += OnCmbBoxGroupDrawItem; - comboBoxGroups.SelectionChangeCommitted += OnCmbBoxGroupSelectionChangeCommitted; - comboBoxGroups.TextUpdate += OnCmbBoxGroupTextUpdate; - // - // pnlBackground - // - pnlBackground.AutoScroll = true; - pnlBackground.Controls.Add(listBoxHighlight); - pnlBackground.Controls.Add(btnAdd); - pnlBackground.Controls.Add(btnDelete); - pnlBackground.Controls.Add(btnMoveUp); - pnlBackground.Controls.Add(btnMoveDown); - pnlBackground.Controls.Add(btnOk); - pnlBackground.Controls.Add(btnCancel); - pnlBackground.Controls.Add(btnApply); - pnlBackground.Controls.Add(groupBoxLineMatchCriteria); - pnlBackground.Controls.Add(groupBoxColoring); - pnlBackground.Controls.Add(groupBoxActions); - pnlBackground.Controls.Add(groupBox4); - pnlBackground.Dock = System.Windows.Forms.DockStyle.Fill; - pnlBackground.Location = new Point(0, 0); - pnlBackground.Name = "pnlBackground"; - pnlBackground.Size = new Size(708, 895); - pnlBackground.TabIndex = 23; - // - // HighlightDialog - // - AcceptButton = btnOk; - CancelButton = btnCancel; - ClientSize = new Size(708, 895); - Controls.Add(pnlBackground); - DoubleBuffered = true; - helpProvider.SetHelpKeyword(this, "Highlighting.htm"); - helpProvider.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); - helpProvider.SetHelpString(this, ""); - Icon = (Icon)resources.GetObject("$this.Icon"); - Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - MaximizeBox = false; - MinimizeBox = false; - MinimumSize = new Size(660, 934); - Name = "HighlightDialog"; - helpProvider.SetShowHelp(this, true); - StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - Text = "Highlighting and action triggers"; - Shown += OnHighlightDialogShown; - groupBoxLineMatchCriteria.ResumeLayout(false); - groupBoxLineMatchCriteria.PerformLayout(); - groupBoxColoring.ResumeLayout(false); - groupBoxColoring.PerformLayout(); - groupBoxActions.ResumeLayout(false); - groupBoxActions.PerformLayout(); - groupBox4.ResumeLayout(false); - groupBox4.PerformLayout(); - pnlBackground.ResumeLayout(false); - ResumeLayout(false); - } - - #endregion - - private System.Windows.Forms.ListBox listBoxHighlight; - private System.Windows.Forms.Button btnAdd; - private System.Windows.Forms.Button btnDelete; - private System.Windows.Forms.Button btnMoveUp; - private System.Windows.Forms.Button btnMoveDown; - private ColorComboBox colorBoxForeground; - private System.Windows.Forms.Label labelForgroundColor; - private ColorComboBox colorBoxBackground; - private System.Windows.Forms.Label labelBackgroundColor; - private System.Windows.Forms.Button btnOk; - private System.Windows.Forms.Button btnCancel; - private System.Windows.Forms.TextBox textBoxSearchString; - private System.Windows.Forms.Label labelSearchString; - private System.Windows.Forms.Button btnApply; - private System.Windows.Forms.Button btnCustomForeColor; - private System.Windows.Forms.Button btnCustomBackColor; - private System.Windows.Forms.CheckBox checkBoxRegex; - private System.Windows.Forms.CheckBox checkBoxCaseSensitive; - private System.Windows.Forms.CheckBox checkBoxDontDirtyLed; - private System.Windows.Forms.GroupBox groupBoxLineMatchCriteria; - private System.Windows.Forms.GroupBox groupBoxColoring; - private System.Windows.Forms.GroupBox groupBoxActions; - private System.Windows.Forms.CheckBox checkBoxBookmark; - private System.Windows.Forms.CheckBox checkBoxStopTail; - private System.Windows.Forms.HelpProvider helpProvider; - private System.Windows.Forms.CheckBox checkBoxPlugin; - private System.Windows.Forms.Button btnSelectPlugin; - private System.Windows.Forms.Button btnBookmarkComment; - private System.Windows.Forms.GroupBox groupBox4; - private System.Windows.Forms.ComboBox comboBoxGroups; - private System.Windows.Forms.Button btnDeleteGroup; - private System.Windows.Forms.Button btnNewGroup; - private System.Windows.Forms.Button btnCopyGroup; - private System.Windows.Forms.ToolTip toolTip; - private System.Windows.Forms.Label labelAssignNamesToGroups; - private System.Windows.Forms.Button btnMoveGroupUp; - private System.Windows.Forms.Button btnMoveGroupDown; - private System.Windows.Forms.CheckBox checkBoxWordMatch; - private System.Windows.Forms.CheckBox checkBoxBold; - private System.Windows.Forms.CheckBox checkBoxNoBackground; - private System.Windows.Forms.Button btnImportGroup; - private System.Windows.Forms.Button btnExportGroup; - private System.Windows.Forms.Panel pnlBackground; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/HighlightDialog.cs b/src/LogExpert/Dialogs/HighlightDialog.cs deleted file mode 100644 index e25d12b0..00000000 --- a/src/LogExpert/Dialogs/HighlightDialog.cs +++ /dev/null @@ -1,724 +0,0 @@ -using LogExpert.Classes.Highlight; -using LogExpert.Config; -using LogExpert.Entities; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class HighlightDialog : Form - { - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - #region Private Fields - - private readonly Image _applyButtonImage; - private string _bookmarkComment; - private ActionEntry _currentActionEntry = new(); - private HilightGroup _currentGroup; - private List _highlightGroupList; - - #endregion - - #region Ctor - - public HighlightDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - Load += OnHighlightDialogLoad; - listBoxHighlight.DrawItem += OnHighlightListBoxDrawItem; - _applyButtonImage = btnApply.Image; - btnApply.Image = null; - } - - #endregion - - #region Properties / Indexers - - public List HighlightGroupList - { - get => _highlightGroupList; - set - { - _highlightGroupList ??= []; - - foreach (var group in value) - { - _highlightGroupList.Add((HilightGroup)group.Clone()); - } - } - } - - public IList KeywordActionList { get; set; } - - public string PreSelectedGroupName { get; set; } - - private bool IsDirty => btnApply.Image == _applyButtonImage; - - #endregion - - #region Event handling Methods - - private void OnAddButtonClick(object sender, EventArgs e) - { - AddNewEntry(); - Dirty(); - } - - private void OnBtnApplyClick(object sender, EventArgs e) - { - SaveEntry(); - } - - private void OnBtnBookmarkCommentClick(object sender, EventArgs e) - { - BookmarkCommentDlg dlg = new(); - dlg.Comment = _bookmarkComment; - if (dlg.ShowDialog() == DialogResult.OK) - { - _bookmarkComment = dlg.Comment; - Dirty(); - } - } - - private void OnBtnCopyGroupClick(object sender, EventArgs e) - { - if (comboBoxGroups.SelectedIndex >= 0 && comboBoxGroups.SelectedIndex < HighlightGroupList.Count) - { - HilightGroup newGroup = (HilightGroup)HighlightGroupList[comboBoxGroups.SelectedIndex].Clone(); - newGroup.GroupName = "Copy of " + newGroup.GroupName; - - HighlightGroupList.Add(newGroup); - FillGroupComboBox(); - SelectGroup(HighlightGroupList.Count - 1); - } - } - - private void OnBtnCustomBackColorClick(object sender, EventArgs e) - { - ChooseColor(colorBoxBackground); - Dirty(); - } - - private void OnBtnCustomForeColorClick(object sender, EventArgs e) - { - ChooseColor(colorBoxForeground); - Dirty(); - } - - private void OnBtnDelGroupClick(object sender, EventArgs e) - { - // the last group cannot be deleted - if (HighlightGroupList.Count == 1) - { - return; - } - - if (comboBoxGroups.SelectedIndex >= 0 && comboBoxGroups.SelectedIndex < HighlightGroupList.Count) - { - int index = comboBoxGroups.SelectedIndex; - HighlightGroupList.RemoveAt(comboBoxGroups.SelectedIndex); - FillGroupComboBox(); - if (index < HighlightGroupList.Count) - { - SelectGroup(index); - } - else - { - SelectGroup(HighlightGroupList.Count - 1); - } - } - } - - private void OnBtnExportGroupClick(object sender, EventArgs e) - { - //SaveFileDialog dlg = new SaveFileDialog(); - //dlg.Title = @"Export Settings to file"; - //dlg.DefaultExt = "json"; - //dlg.AddExtension = true; - //dlg.Filter = @"Settings (*.json)|*.json|All files (*.*)|*.*"; - - //DialogResult result = dlg.ShowDialog(); - - //if (result == DialogResult.OK) - //{ - // FileInfo fileInfo = new FileInfo(dlg.FileName); - // ConfigManager.Export(fileInfo); - //} - } - - private void OnBtnGroupDownClick(object sender, EventArgs e) - { - int index = comboBoxGroups.SelectedIndex; - if (index > -1 && index < _highlightGroupList.Count - 1) - { - _highlightGroupList.Reverse(index, 2); - comboBoxGroups.Refresh(); - FillGroupComboBox(); - SelectGroup(index + 1); - } - } - - private void OnBtnGroupUpClick(object sender, EventArgs e) - { - int index = comboBoxGroups.SelectedIndex; - if (index > 0) - { - _highlightGroupList.Reverse(index - 1, 2); - comboBoxGroups.Refresh(); - FillGroupComboBox(); - SelectGroup(index - 1); - } - } - - private void OnBtnImportGroupClick(object sender, EventArgs e) - { - ImportSettingsDialog dlg = new(); - - foreach (Control ctl in dlg.groupBoxImportOptions.Controls) - { - if (ctl.Tag != null) - { - ((CheckBox)ctl).Checked = false; - } - } - - dlg.checkBoxHighlightSettings.Checked = true; - dlg.checkBoxKeepExistingSettings.Checked = true; - - if (dlg.ShowDialog() != DialogResult.OK) - { - return; - } - - if (string.IsNullOrWhiteSpace(dlg.FileName)) - { - return; - } - - Cursor.Current = Cursors.WaitCursor; - - FileInfo fileInfo; - - try - { - fileInfo = new FileInfo(dlg.FileName); - } - catch (Exception ex) - { - MessageBox.Show(this, $@"Settings could not be imported: {ex}", @"LogExpert"); - _logger.Error($"Error while trying to access file: {dlg.FileName}: {ex}"); - return; - } - - ConfigManager.Import(fileInfo, dlg.ImportFlags); - Cursor.Current = Cursors.Default; - - _highlightGroupList = ConfigManager.Settings.hilightGroupList; - - FillGroupComboBox(); - - MessageBox.Show(this, @"Settings imported", @"LogExpert"); - } - - private void OnBtnMoveDownClick(object sender, EventArgs e) - { - int index = listBoxHighlight.SelectedIndex; - - if (index > -1 && index < listBoxHighlight.Items.Count - 1) - { - object item = listBoxHighlight.SelectedItem; - listBoxHighlight.Items.RemoveAt(index); - listBoxHighlight.Items.Insert(index + 1, item); - listBoxHighlight.SelectedIndex = index + 1; - _currentGroup.HilightEntryList.Reverse(index, 2); - } - } - - private void OnBtnMoveUpClick(object sender, EventArgs e) - { - int index = listBoxHighlight.SelectedIndex; - if (index > 0) - { - object item = listBoxHighlight.SelectedItem; - listBoxHighlight.Items.RemoveAt(index); // will also clear the selection - listBoxHighlight.Items.Insert(index - 1, item); - listBoxHighlight.SelectedIndex = index - 1; // restore the selection - _currentGroup.HilightEntryList.Reverse(index - 1, 2); - } - } - - private void OnBtnNewGroupClick(object sender, EventArgs e) - { - // Propose a unique name - const string baseName = "New group"; - string name = baseName; - bool uniqueName = false; - int i = 1; - while (!uniqueName) - { - uniqueName = HighlightGroupList.FindIndex(delegate (HilightGroup g) { return g.GroupName == name; }) < 0; - - if (!uniqueName) - { - name = $"{baseName} #{i++}"; - } - } - - HilightGroup newGroup = new() { GroupName = name }; - HighlightGroupList.Add(newGroup); - FillGroupComboBox(); - SelectGroup(HighlightGroupList.Count - 1); - } - - private void OnBtnOkClick(object sender, EventArgs e) - { - // Apply pending changes if closing the form. - if (IsDirty) - { - // cannot call 'this.applyButton.PerformClick();' because it prohibits the OK button to terminate the dialog - OnBtnApplyClick(btnApply, EventArgs.Empty); - } - } - - private void OnChkBoxBoldCheckedChanged(object sender, EventArgs e) - { - Dirty(); - } - - private void OnChkBoxNoBackgroundCheckedChanged(object sender, EventArgs e) - { - colorBoxBackground.Enabled = !checkBoxNoBackground.Checked; - btnCustomBackColor.Enabled = !checkBoxNoBackground.Checked; - Dirty(); - } - - private void OnChkBoxPluginCheckedChanged(object sender, EventArgs e) - { - Dirty(); - btnSelectPlugin.Enabled = checkBoxPlugin.Checked; - } - - private void OnChkBoxRegexMouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Right) - { - RegexHelperDialog dlg = new(); - dlg.Owner = this; - dlg.CaseSensitive = checkBoxCaseSensitive.Checked; - dlg.Pattern = textBoxSearchString.Text; - DialogResult res = dlg.ShowDialog(); - if (res == DialogResult.OK) - { - checkBoxCaseSensitive.Checked = dlg.CaseSensitive; - textBoxSearchString.Text = dlg.Pattern; - } - } - } - - private void OnChkBoxWordMatchCheckedChanged(object sender, EventArgs e) - { - Dirty(); - checkBoxNoBackground.Enabled = checkBoxWordMatch.Checked; - } - - private void OnCmbBoxGroupDrawItem(object sender, DrawItemEventArgs e) - { - e.DrawBackground(); - if (e.Index >= 0) - { - HilightGroup group = HighlightGroupList[e.Index]; - Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); - - Brush brush = new SolidBrush(SystemColors.ControlText); - e.Graphics.DrawString(group.GroupName, e.Font, brush, new PointF(rectangle.Left, rectangle.Top)); - e.DrawFocusRectangle(); - brush.Dispose(); - } - } - - private void OnCmbBoxGroupSelectionChangeCommitted(object sender, EventArgs e) - { - SelectGroup(comboBoxGroups.SelectedIndex); - } - - private void OnCmbBoxGroupTextUpdate(object sender, EventArgs e) - { - _currentGroup.GroupName = comboBoxGroups.Text; - } - - private void OnDeleteButtonClick(object sender, EventArgs e) - { - if (listBoxHighlight.SelectedIndex >= 0) - { - int removeIndex = listBoxHighlight.SelectedIndex; - _currentGroup.HilightEntryList.RemoveAt(removeIndex); - listBoxHighlight.Items.RemoveAt(removeIndex); - - // Select previous (or first if none before) - int nextSelectIndex = removeIndex; - if (nextSelectIndex >= listBoxHighlight.Items.Count) - { - nextSelectIndex--; // if last item was removed, go one up - } - - if (nextSelectIndex >= 0) - { - listBoxHighlight.SelectedIndex = nextSelectIndex; // if still some item, select it - } - - ReEvaluateHighlightButtonStates(); - } - } - - private void OnHighlightDialogLoad(object sender, EventArgs e) - { - colorBoxForeground.SelectedIndex = 1; - colorBoxBackground.SelectedIndex = 2; - btnApply.Enabled = false; - btnApply.Image = null; - btnBookmarkComment.Enabled = false; - btnSelectPlugin.Enabled = false; - - ReEvaluateHighlightButtonStates(); - } - - private void OnHighlightDialogShown(object sender, EventArgs e) - { - InitData(); - } - - private void OnHighlightListBoxDrawItem(object sender, DrawItemEventArgs e) - { - e.DrawBackground(); - if (e.Index >= 0) - { - HilightEntry entry = (HilightEntry)listBoxHighlight.Items[e.Index]; - Rectangle rectangle = new(0, e.Bounds.Top, e.Bounds.Width, e.Bounds.Height); - - if ((e.State & DrawItemState.Selected) != DrawItemState.Selected) - { - e.Graphics.FillRectangle(new SolidBrush(entry.BackgroundColor), rectangle); - } - - e.Graphics.DrawString(entry.SearchText, e.Font, new SolidBrush(entry.ForegroundColor), - new PointF(rectangle.Left, rectangle.Top)); - - e.DrawFocusRectangle(); - } - } - - private void OnListBoxHighlightSelectedIndexChanged(object sender, EventArgs e) - { - StartEditEntry(); - } - - private void OnPluginButtonClick(object sender, EventArgs e) - { - KeywordActionDlg dlg = new(_currentActionEntry, KeywordActionList); - - if (dlg.ShowDialog() == DialogResult.OK) - { - _currentActionEntry = dlg.ActionEntry; - Dirty(); - } - } - - #endregion - - #region Private Methods - - private void AddNewEntry() - { - { - try - { - CheckRegex(); - - HilightEntry entry = new() - { - SearchText = textBoxSearchString.Text, - ForegroundColor = colorBoxForeground.SelectedColor, - BackgroundColor = colorBoxBackground.SelectedColor, - IsRegEx = checkBoxRegex.Checked, - IsCaseSensitive = checkBoxCaseSensitive.Checked, - IsLedSwitch = checkBoxDontDirtyLed.Checked, - IsStopTail = checkBoxStopTail.Checked, - IsSetBookmark = checkBoxBookmark.Checked, - IsActionEntry = checkBoxPlugin.Checked, - ActionEntry = _currentActionEntry, - IsWordMatch = checkBoxWordMatch.Checked, - IsBold = checkBoxBold.Checked, - NoBackground = checkBoxNoBackground.Checked - }; - - listBoxHighlight.Items.Add(entry); - - // Select the newly created item - _currentGroup.HilightEntryList.Add(entry); - listBoxHighlight.SelectedItem = entry; - } - catch (Exception ex) - { - _logger.Error(ex, "Error during add of highlight entry"); - MessageBox.Show($"Error during add of entry.\r\n{ex.Message}"); - } - } - } - - private void ChangeToDirty(object sender, EventArgs e) - { - Dirty(); - } - - private void CheckRegex() - { - if (checkBoxRegex.Checked) - { - if (string.IsNullOrWhiteSpace(textBoxSearchString.Text)) - { - throw new ArgumentException("Regex value is null or whitespace"); - } - - // ReSharper disable once ReturnValueOfPureMethodIsNotUsed - Regex.IsMatch("", textBoxSearchString.Text); - } - } - - private void ChooseColor(ColorComboBox comboBox) - { - ColorDialog colorDialog = new(); - colorDialog.AllowFullOpen = true; - colorDialog.ShowHelp = false; - colorDialog.Color = comboBox.CustomColor; - if (colorDialog.ShowDialog() == DialogResult.OK) - { - comboBox.CustomColor = colorDialog.Color; - comboBox.SelectedIndex = 0; - } - } - - private void Dirty() - { - int index = listBoxHighlight.SelectedIndex; - if (index > -1) - { - btnApply.Enabled = true; - btnApply.Image = _applyButtonImage; - } - - btnAdd.Enabled = textBoxSearchString.Text.Length > 0; - } - - private void FillGroupComboBox() - { - SelectGroup(-1); - - comboBoxGroups.Items.Clear(); - - foreach (HilightGroup group in HighlightGroupList) - { - comboBoxGroups.Items.Add(group); - } - - ReEvaluateGroupButtonStates(); - } - - private void FillHighlightListBox() - { - listBoxHighlight.Items.Clear(); - if (_currentGroup != null) - { - foreach (HilightEntry entry in _currentGroup.HilightEntryList) - { - listBoxHighlight.Items.Add(entry); - } - } - } - - private void InitData() - { - const string def = "[Default]"; - HighlightGroupList ??= []; - - if (HighlightGroupList.Count == 0) - { - HilightGroup highlightGroup = new() - { - GroupName = def, - HilightEntryList = [] - }; - - HighlightGroupList.Add(highlightGroup); - } - - FillGroupComboBox(); - - _currentGroup = null; - string groupToSelect = PreSelectedGroupName; - if (string.IsNullOrEmpty(groupToSelect)) - { - groupToSelect = def; - } - - foreach (HilightGroup group in HighlightGroupList) - { - if (group.GroupName.Equals(groupToSelect)) - { - _currentGroup = group; - comboBoxGroups.SelectedValue = group; - comboBoxGroups.SelectedIndex = HighlightGroupList.IndexOf(group); - break; - } - } - - ReEvaluateGroupButtonStates(); - - FillHighlightListBox(); - } - - private void ReEvaluateGroupButtonStates() - { - // Refresh button states based on the selection in the combobox - bool atLeastOneSelected = comboBoxGroups.SelectedItem != null; - bool moreThanOne = comboBoxGroups.Items.Count > 1; - bool firstSelected = atLeastOneSelected && comboBoxGroups.SelectedIndex == 0; - bool lastSelected = atLeastOneSelected && comboBoxGroups.SelectedIndex == comboBoxGroups.Items.Count - 1; - - btnDeleteGroup.Enabled = atLeastOneSelected; - btnCopyGroup.Enabled = atLeastOneSelected; - btnMoveGroupUp.Enabled = atLeastOneSelected && moreThanOne && !firstSelected; - btnMoveGroupDown.Enabled = atLeastOneSelected && moreThanOne && !lastSelected; - } - - private void ReEvaluateHighlightButtonStates() - { - // Refresh button states based on the selection in the combobox - bool atLeastOneSelected = listBoxHighlight.SelectedItem != null; - bool moreThanOne = listBoxHighlight.Items.Count > 1; - bool firstSelected = atLeastOneSelected && listBoxHighlight.SelectedIndex == 0; - bool lastSelected = atLeastOneSelected && listBoxHighlight.SelectedIndex == listBoxHighlight.Items.Count - 1; - - btnDelete.Enabled = atLeastOneSelected; - btnMoveUp.Enabled = atLeastOneSelected && moreThanOne && !firstSelected; - btnMoveDown.Enabled = atLeastOneSelected && moreThanOne && !lastSelected; - } - - private void SaveEntry() - { - try - { - CheckRegex(); - - HilightEntry entry = (HilightEntry)listBoxHighlight.SelectedItem; - - entry.ForegroundColor = (Color)colorBoxForeground.SelectedItem; - entry.BackgroundColor = (Color)colorBoxBackground.SelectedItem; - entry.SearchText = textBoxSearchString.Text; - entry.IsRegEx = checkBoxRegex.Checked; - entry.IsCaseSensitive = checkBoxCaseSensitive.Checked; - btnApply.Enabled = false; - btnApply.Image = null; - entry.IsLedSwitch = checkBoxDontDirtyLed.Checked; - entry.IsSetBookmark = checkBoxBookmark.Checked; - entry.IsStopTail = checkBoxStopTail.Checked; - entry.IsActionEntry = checkBoxPlugin.Checked; - entry.ActionEntry = (ActionEntry)_currentActionEntry.Clone(); - entry.BookmarkComment = _bookmarkComment; - entry.IsWordMatch = checkBoxWordMatch.Checked; - entry.IsBold = checkBoxBold.Checked; - entry.NoBackground = checkBoxNoBackground.Checked; - listBoxHighlight.Refresh(); - } - catch (Exception ex) - { - _logger.Error(ex, "Error during save of save highlight entry"); - MessageBox.Show($"Error during save of entry.\r\n{ex.Message}"); - } - } - - private void SelectGroup(int index) - { - if (index >= 0 && index < HighlightGroupList.Count) - { - _currentGroup = HighlightGroupList[index]; - comboBoxGroups.Items[index] = _currentGroup; - comboBoxGroups.SelectedIndex = index; - comboBoxGroups.SelectedItem = _currentGroup; - FillHighlightListBox(); - } - else - { - comboBoxGroups.SelectedItem = null; - _currentGroup = null; - listBoxHighlight.Items.Clear(); - } - - ReEvaluateHighlightButtonStates(); - ReEvaluateGroupButtonStates(); - } - - private void StartEditEntry() - { - HilightEntry entry = (HilightEntry)listBoxHighlight.SelectedItem; - - if (entry != null) - { - textBoxSearchString.Text = entry.SearchText; - - colorBoxForeground.CustomColor = entry.ForegroundColor; - colorBoxBackground.CustomColor = entry.BackgroundColor; - - if (colorBoxForeground.Items.Contains(entry.ForegroundColor)) - { - colorBoxForeground.SelectedIndex = colorBoxForeground.Items.Cast().ToList().LastIndexOf(entry.ForegroundColor); - } - else - { - colorBoxForeground.SelectedItem = entry.ForegroundColor; - } - - if (colorBoxForeground.Items.Contains(entry.ForegroundColor)) - { - colorBoxBackground.SelectedIndex = colorBoxBackground.Items.Cast().ToList().LastIndexOf(entry.BackgroundColor); - } - else - { - colorBoxBackground.SelectedItem = entry.BackgroundColor; - } - - checkBoxRegex.Checked = entry.IsRegEx; - checkBoxCaseSensitive.Checked = entry.IsCaseSensitive; - checkBoxDontDirtyLed.Checked = entry.IsLedSwitch; - checkBoxBookmark.Checked = entry.IsSetBookmark; - checkBoxStopTail.Checked = entry.IsStopTail; - checkBoxPlugin.Checked = entry.IsActionEntry; - btnSelectPlugin.Enabled = checkBoxPlugin.Checked; - btnBookmarkComment.Enabled = checkBoxBookmark.Checked; - _currentActionEntry = entry.ActionEntry != null ? (ActionEntry)entry.ActionEntry.Clone() : new ActionEntry(); - _bookmarkComment = entry.BookmarkComment; - checkBoxWordMatch.Checked = entry.IsWordMatch; - checkBoxBold.Checked = entry.IsBold; - checkBoxNoBackground.Checked = entry.NoBackground; - } - - btnApply.Enabled = false; - btnApply.Image = null; - - ReEvaluateHighlightButtonStates(); - } - - #endregion - } -} diff --git a/src/LogExpert/Dialogs/ImportSettingsDialog.Designer.cs b/src/LogExpert/Dialogs/ImportSettingsDialog.Designer.cs deleted file mode 100644 index 2203a049..00000000 --- a/src/LogExpert/Dialogs/ImportSettingsDialog.Designer.cs +++ /dev/null @@ -1,226 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class ImportSettingsDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ImportSettingsDialog)); - this.buttonFile = new System.Windows.Forms.Button(); - this.textBoxFileName = new System.Windows.Forms.TextBox(); - this.labelSettingsFileToImport = new System.Windows.Forms.Label(); - this.groupBoxImportOptions = new System.Windows.Forms.GroupBox(); - this.checkBoxKeepExistingSettings = new System.Windows.Forms.CheckBox(); - this.checkBoxOther = new System.Windows.Forms.CheckBox(); - this.checkBoxExternalTools = new System.Windows.Forms.CheckBox(); - this.checkBoxColumnizerFileMasks = new System.Windows.Forms.CheckBox(); - this.checkBoxHighlightFileMasks = new System.Windows.Forms.CheckBox(); - this.checkBoxHighlightSettings = new System.Windows.Forms.CheckBox(); - this.buttonOk = new System.Windows.Forms.Button(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.groupBoxImportOptions.SuspendLayout(); - this.SuspendLayout(); - // - // buttonFile - // - this.buttonFile.Location = new System.Drawing.Point(306, 25); - this.buttonFile.Name = "buttonFile"; - this.buttonFile.Size = new System.Drawing.Size(94, 23); - this.buttonFile.TabIndex = 0; - this.buttonFile.Text = "Choose file..."; - this.buttonFile.UseVisualStyleBackColor = true; - this.buttonFile.Click += new System.EventHandler(this.OnFileButtonClick); - // - // textBoxFileName - // - this.textBoxFileName.Location = new System.Drawing.Point(13, 27); - this.textBoxFileName.Name = "textBoxFileName"; - this.textBoxFileName.Size = new System.Drawing.Size(287, 20); - this.textBoxFileName.TabIndex = 1; - // - // labelSettingsFileToImport - // - this.labelSettingsFileToImport.AutoSize = true; - this.labelSettingsFileToImport.Location = new System.Drawing.Point(13, 8); - this.labelSettingsFileToImport.Name = "labelSettingsFileToImport"; - this.labelSettingsFileToImport.Size = new System.Drawing.Size(107, 13); - this.labelSettingsFileToImport.TabIndex = 2; - this.labelSettingsFileToImport.Text = "Settings file to import:"; - // - // groupBoxImportOptions - // - this.groupBoxImportOptions.Controls.Add(this.checkBoxKeepExistingSettings); - this.groupBoxImportOptions.Controls.Add(this.checkBoxOther); - this.groupBoxImportOptions.Controls.Add(this.checkBoxExternalTools); - this.groupBoxImportOptions.Controls.Add(this.checkBoxColumnizerFileMasks); - this.groupBoxImportOptions.Controls.Add(this.checkBoxHighlightFileMasks); - this.groupBoxImportOptions.Controls.Add(this.checkBoxHighlightSettings); - this.groupBoxImportOptions.Location = new System.Drawing.Point(16, 67); - this.groupBoxImportOptions.Name = "groupBoxImportOptions"; - this.groupBoxImportOptions.Size = new System.Drawing.Size(284, 143); - this.groupBoxImportOptions.TabIndex = 3; - this.groupBoxImportOptions.TabStop = false; - this.groupBoxImportOptions.Text = "Import options"; - // - // checkBoxKeepExistingSettings - // - this.checkBoxKeepExistingSettings.AutoSize = true; - this.checkBoxKeepExistingSettings.Location = new System.Drawing.Point(141, 20); - this.checkBoxKeepExistingSettings.Name = "checkBoxKeepExistingSettings"; - this.checkBoxKeepExistingSettings.Size = new System.Drawing.Size(128, 17); - this.checkBoxKeepExistingSettings.TabIndex = 1; - this.checkBoxKeepExistingSettings.Tag = "32"; - this.checkBoxKeepExistingSettings.Text = "Keep existing settings"; - this.checkBoxKeepExistingSettings.UseVisualStyleBackColor = true; - // - // checkBoxOther - // - this.checkBoxOther.AutoSize = true; - this.checkBoxOther.Checked = true; - this.checkBoxOther.CheckState = System.Windows.Forms.CheckState.Checked; - this.checkBoxOther.Location = new System.Drawing.Point(7, 112); - this.checkBoxOther.Name = "checkBoxOther"; - this.checkBoxOther.Size = new System.Drawing.Size(52, 17); - this.checkBoxOther.TabIndex = 0; - this.checkBoxOther.Tag = "16"; - this.checkBoxOther.Text = "Other"; - this.checkBoxOther.UseVisualStyleBackColor = true; - // - // checkBoxExternalTools - // - this.checkBoxExternalTools.AutoSize = true; - this.checkBoxExternalTools.Checked = true; - this.checkBoxExternalTools.CheckState = System.Windows.Forms.CheckState.Checked; - this.checkBoxExternalTools.Location = new System.Drawing.Point(7, 89); - this.checkBoxExternalTools.Name = "checkBoxExternalTools"; - this.checkBoxExternalTools.Size = new System.Drawing.Size(89, 17); - this.checkBoxExternalTools.TabIndex = 0; - this.checkBoxExternalTools.Tag = "8"; - this.checkBoxExternalTools.Text = "External tools"; - this.checkBoxExternalTools.UseVisualStyleBackColor = true; - // - // checkBoxColumnizerFileMasks - // - this.checkBoxColumnizerFileMasks.AutoSize = true; - this.checkBoxColumnizerFileMasks.Checked = true; - this.checkBoxColumnizerFileMasks.CheckState = System.Windows.Forms.CheckState.Checked; - this.checkBoxColumnizerFileMasks.Location = new System.Drawing.Point(7, 66); - this.checkBoxColumnizerFileMasks.Name = "checkBoxColumnizerFileMasks"; - this.checkBoxColumnizerFileMasks.Size = new System.Drawing.Size(126, 17); - this.checkBoxColumnizerFileMasks.TabIndex = 0; - this.checkBoxColumnizerFileMasks.Tag = "2"; - this.checkBoxColumnizerFileMasks.Text = "Columnizer file masks"; - this.checkBoxColumnizerFileMasks.UseVisualStyleBackColor = true; - // - // checkBoxHighlightFileMasks - // - this.checkBoxHighlightFileMasks.AutoSize = true; - this.checkBoxHighlightFileMasks.Checked = true; - this.checkBoxHighlightFileMasks.CheckState = System.Windows.Forms.CheckState.Checked; - this.checkBoxHighlightFileMasks.Location = new System.Drawing.Point(7, 43); - this.checkBoxHighlightFileMasks.Name = "checkBoxHighlightFileMasks"; - this.checkBoxHighlightFileMasks.Size = new System.Drawing.Size(116, 17); - this.checkBoxHighlightFileMasks.TabIndex = 0; - this.checkBoxHighlightFileMasks.Tag = "4"; - this.checkBoxHighlightFileMasks.Text = "Highlight file masks"; - this.checkBoxHighlightFileMasks.UseVisualStyleBackColor = true; - // - // checkBoxHighlightSettings - // - this.checkBoxHighlightSettings.AutoSize = true; - this.checkBoxHighlightSettings.Checked = true; - this.checkBoxHighlightSettings.CheckState = System.Windows.Forms.CheckState.Checked; - this.checkBoxHighlightSettings.Location = new System.Drawing.Point(7, 20); - this.checkBoxHighlightSettings.Name = "checkBoxHighlightSettings"; - this.checkBoxHighlightSettings.Size = new System.Drawing.Size(106, 17); - this.checkBoxHighlightSettings.TabIndex = 0; - this.checkBoxHighlightSettings.Tag = "1"; - this.checkBoxHighlightSettings.Text = "Highlight settings"; - this.checkBoxHighlightSettings.UseVisualStyleBackColor = true; - // - // buttonOk - // - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(325, 187); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 4; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnOkButtonClick); - // - // buttonCancel - // - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(325, 154); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 5; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // ImportSettingsDialog - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(412, 224); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.groupBoxImportOptions); - this.Controls.Add(this.labelSettingsFileToImport); - this.Controls.Add(this.textBoxFileName); - this.Controls.Add(this.buttonFile); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "ImportSettingsDialog"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Import Settings"; - this.Load += new System.EventHandler(this.OnImportSettingsDialogLoad); - this.groupBoxImportOptions.ResumeLayout(false); - this.groupBoxImportOptions.PerformLayout(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button buttonFile; - private System.Windows.Forms.TextBox textBoxFileName; - private System.Windows.Forms.Label labelSettingsFileToImport; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Button buttonCancel; - public System.Windows.Forms.CheckBox checkBoxExternalTools; - public System.Windows.Forms.CheckBox checkBoxColumnizerFileMasks; - public System.Windows.Forms.CheckBox checkBoxHighlightFileMasks; - public System.Windows.Forms.CheckBox checkBoxHighlightSettings; - public System.Windows.Forms.CheckBox checkBoxOther; - public System.Windows.Forms.CheckBox checkBoxKeepExistingSettings; - public System.Windows.Forms.GroupBox groupBoxImportOptions; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ImportSettingsDialog.cs b/src/LogExpert/Dialogs/ImportSettingsDialog.cs deleted file mode 100644 index 985d9d30..00000000 --- a/src/LogExpert/Dialogs/ImportSettingsDialog.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using LogExpert.Config; - -namespace LogExpert.Dialogs -{ - public partial class ImportSettingsDialog : Form - { - #region Fields - - #endregion - - #region cTor - - public ImportSettingsDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - } - - #endregion - - #region Properties - - public string FileName { get; private set; } - - public ExportImportFlags ImportFlags { get; private set; } - - #endregion - - #region Events handler - - private void OnImportSettingsDialogLoad(object sender, EventArgs e) - { - } - - private void OnFileButtonClick(object sender, EventArgs e) - { - OpenFileDialog dlg = new(); - dlg.Title = "Load Settings from file"; - dlg.DefaultExt = "json"; - dlg.AddExtension = false; - dlg.Filter = "Settings (*.json)|*.json|All files (*.*)|*.*"; - - if (dlg.ShowDialog() == DialogResult.OK) - { - textBoxFileName.Text = dlg.FileName; - } - } - - private void OnOkButtonClick(object sender, EventArgs e) - { - ImportFlags = ExportImportFlags.None; - FileName = textBoxFileName.Text; - - foreach (Control ctl in groupBoxImportOptions.Controls) - { - if (ctl.Tag != null) - { - if (((CheckBox)ctl).Checked) - { - ImportFlags |= (ExportImportFlags) long.Parse(ctl.Tag as string ?? string.Empty); - } - } - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/KeywordActionDlg.Designer.cs b/src/LogExpert/Dialogs/KeywordActionDlg.Designer.cs deleted file mode 100644 index 6788e495..00000000 --- a/src/LogExpert/Dialogs/KeywordActionDlg.Designer.cs +++ /dev/null @@ -1,139 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class KeywordActionDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(KeywordActionDlg)); - this.actionComboBox = new System.Windows.Forms.ComboBox(); - this.label1 = new System.Windows.Forms.Label(); - this.parameterTextBox = new System.Windows.Forms.TextBox(); - this.label2 = new System.Windows.Forms.Label(); - this.buttonOk = new System.Windows.Forms.Button(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.commentTextBox = new System.Windows.Forms.TextBox(); - this.SuspendLayout(); - // - // actionComboBox - // - this.actionComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - this.actionComboBox.FormattingEnabled = true; - this.actionComboBox.Location = new System.Drawing.Point(12, 36); - this.actionComboBox.Name = "actionComboBox"; - this.actionComboBox.Size = new System.Drawing.Size(329, 28); - this.actionComboBox.TabIndex = 0; - this.actionComboBox.SelectedIndexChanged += new System.EventHandler(this.OnActionComboBoxSelectedIndexChanged); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(12, 20); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(166, 20); - this.label1.TabIndex = 1; - this.label1.Text = "Keyword action plugin:"; - // - // parameterTextBox - // - this.parameterTextBox.Location = new System.Drawing.Point(12, 188); - this.parameterTextBox.Name = "parameterTextBox"; - this.parameterTextBox.Size = new System.Drawing.Size(331, 26); - this.parameterTextBox.TabIndex = 2; - // - // label2 - // - this.label2.AutoSize = true; - this.label2.Location = new System.Drawing.Point(12, 172); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(83, 20); - this.label2.TabIndex = 3; - this.label2.Text = "Parameter"; - // - // buttonOk - // - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(166, 223); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 4; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnOkButtonClick); - // - // buttonCancel - // - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(264, 223); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 5; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // commentTextBox - // - this.commentTextBox.Location = new System.Drawing.Point(15, 64); - this.commentTextBox.Multiline = true; - this.commentTextBox.Name = "commentTextBox"; - this.commentTextBox.ReadOnly = true; - this.commentTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.commentTextBox.Size = new System.Drawing.Size(326, 95); - this.commentTextBox.TabIndex = 6; - // - // KeywordActionDlg - // - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(353, 258); - this.Controls.Add(this.commentTextBox); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.label2); - this.Controls.Add(this.parameterTextBox); - this.Controls.Add(this.label1); - this.Controls.Add(this.actionComboBox); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "KeywordActionDlg"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Keyword Action"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.ComboBox actionComboBox; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.TextBox parameterTextBox; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.TextBox commentTextBox; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/KeywordActionDlg.cs b/src/LogExpert/Dialogs/KeywordActionDlg.cs deleted file mode 100644 index 43981c7c..00000000 --- a/src/LogExpert/Dialogs/KeywordActionDlg.cs +++ /dev/null @@ -1,93 +0,0 @@ -using LogExpert.Classes.Highlight; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public struct ActEntry - { - public string Name { get; set; } - - public IKeywordAction Plugin { get; set; } - } - - - public partial class KeywordActionDlg : Form - { - #region Fields - - private readonly IDictionary _actionDict = new Dictionary(); - - private IList _keywordActionList; - - #endregion - - #region cTor - - public KeywordActionDlg(ActionEntry entry, IList actionList) - { - _keywordActionList = actionList; - ActionEntry = entry; - - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - actionComboBox.Items.Clear(); - - foreach (IKeywordAction action in actionList) - { - actionComboBox.Items.Add(action.GetName()); - _actionDict[action.GetName()] = action; - } - - if (actionComboBox.Items.Count > 0) - { - if (ActionEntry.PluginName != null && _actionDict.ContainsKey(ActionEntry.PluginName)) - { - actionComboBox.SelectedItem = ActionEntry.PluginName; - } - else - { - actionComboBox.SelectedIndex = 0; - } - } - - parameterTextBox.Text = ActionEntry.ActionParam; - } - - #endregion - - #region Properties - - public ActionEntry ActionEntry { get; private set; } - - #endregion - - #region Events handler - - private void OnOkButtonClick(object sender, EventArgs e) - { - ActionEntry = new ActionEntry - { - ActionParam = parameterTextBox.Text - }; - - if (_actionDict.ContainsKey((string)actionComboBox.SelectedItem)) - { - ActionEntry.PluginName = (string)actionComboBox.SelectedItem; - } - } - - private void OnActionComboBoxSelectedIndexChanged(object sender, EventArgs e) - { - commentTextBox.Text = _actionDict[(string)actionComboBox.SelectedItem].GetDescription(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/LogCellEditingControl.cs b/src/LogExpert/Dialogs/LogCellEditingControl.cs deleted file mode 100644 index 24a68ae0..00000000 --- a/src/LogExpert/Dialogs/LogCellEditingControl.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public class LogCellEditingControl : DataGridViewTextBoxEditingControl - { - #region Public methods - - public override bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey) - { - switch (key & Keys.KeyCode) - { - case Keys.Left: - case Keys.Up: - case Keys.Down: - case Keys.Right: - case Keys.Home: - case Keys.End: - case Keys.PageDown: - case Keys.PageUp: - { - return true; - } - } - - return !dataGridViewWantsInputKey; - } - - #endregion - } -} diff --git a/src/LogExpert/Dialogs/LogGridCell.cs b/src/LogExpert/Dialogs/LogGridCell.cs deleted file mode 100644 index c63cb1f8..00000000 --- a/src/LogExpert/Dialogs/LogGridCell.cs +++ /dev/null @@ -1,14 +0,0 @@ -using System; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public class LogGridCell : DataGridViewTextBoxCell - { - #region Properties - - public override Type EditType => typeof(LogCellEditingControl); - - #endregion - } -} diff --git a/src/LogExpert/Dialogs/LogTextColumn.cs b/src/LogExpert/Dialogs/LogTextColumn.cs deleted file mode 100644 index 03b5839f..00000000 --- a/src/LogExpert/Dialogs/LogTextColumn.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public class LogTextColumn : DataGridViewColumn - { - #region cTor - - public LogTextColumn() : base(new LogGridCell()) - { - } - - #endregion - } -} diff --git a/src/LogExpert/Dialogs/MultiFileMaskDialog.Designer.cs b/src/LogExpert/Dialogs/MultiFileMaskDialog.Designer.cs deleted file mode 100644 index c6f7f554..00000000 --- a/src/LogExpert/Dialogs/MultiFileMaskDialog.Designer.cs +++ /dev/null @@ -1,192 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class MultiFileMaskDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MultiFileMaskDialog)); - this.labelMultiSettingsFor = new System.Windows.Forms.Label(); - this.labelFileName = new System.Windows.Forms.Label(); - this.labelFileNamePattern = new System.Windows.Forms.Label(); - this.upDownMaxDays = new System.Windows.Forms.NumericUpDown(); - this.fileNamePatternTextBox = new System.Windows.Forms.TextBox(); - this.labelMaxDays = new System.Windows.Forms.Label(); - this.Settings = new System.Windows.Forms.GroupBox(); - this.syntaxHelpLabel = new System.Windows.Forms.Label(); - this.buttonOk = new System.Windows.Forms.Button(); - this.buttonCancel = new System.Windows.Forms.Button(); - ((System.ComponentModel.ISupportInitialize)(this.upDownMaxDays)).BeginInit(); - this.Settings.SuspendLayout(); - this.SuspendLayout(); - // - // labelMultiSettingsFor - // - this.labelMultiSettingsFor.AutoSize = true; - this.labelMultiSettingsFor.Location = new System.Drawing.Point(12, 13); - this.labelMultiSettingsFor.Name = "labelMultiSettingsFor"; - this.labelMultiSettingsFor.Size = new System.Drawing.Size(154, 20); - this.labelMultiSettingsFor.TabIndex = 0; - this.labelMultiSettingsFor.Text = "MultiFile settings for:"; - // - // labelFileName - // - this.labelFileName.AutoSize = true; - this.labelFileName.Location = new System.Drawing.Point(172, 13); - this.labelFileName.Name = "labelFileName"; - this.labelFileName.Size = new System.Drawing.Size(91, 20); - this.labelFileName.TabIndex = 1; - this.labelFileName.Text = ""; - // - // labelFileNamePattern - // - this.labelFileNamePattern.AutoSize = true; - this.labelFileNamePattern.Location = new System.Drawing.Point(6, 28); - this.labelFileNamePattern.Name = "labelFileNamePattern"; - this.labelFileNamePattern.Size = new System.Drawing.Size(137, 20); - this.labelFileNamePattern.TabIndex = 2; - this.labelFileNamePattern.Text = "File name pattern:"; - // - // upDownMaxDays - // - this.upDownMaxDays.Location = new System.Drawing.Point(91, 55); - this.upDownMaxDays.Maximum = new decimal(new int[] { - 40, - 0, - 0, - 0}); - this.upDownMaxDays.Name = "upDownMaxDays"; - this.upDownMaxDays.Size = new System.Drawing.Size(49, 26); - this.upDownMaxDays.TabIndex = 3; - this.upDownMaxDays.Value = new decimal(new int[] { - 1, - 0, - 0, - 0}); - // - // fileNamePatternTextBox - // - this.fileNamePatternTextBox.Location = new System.Drawing.Point(149, 25); - this.fileNamePatternTextBox.Name = "fileNamePatternTextBox"; - this.fileNamePatternTextBox.Size = new System.Drawing.Size(247, 26); - this.fileNamePatternTextBox.TabIndex = 4; - // - // labelMaxDays - // - this.labelMaxDays.AutoSize = true; - this.labelMaxDays.Location = new System.Drawing.Point(6, 57); - this.labelMaxDays.Name = "labelMaxDays"; - this.labelMaxDays.Size = new System.Drawing.Size(79, 20); - this.labelMaxDays.TabIndex = 5; - this.labelMaxDays.Text = "Max days:"; - // - // Settings - // - this.Settings.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.Settings.Controls.Add(this.labelFileNamePattern); - this.Settings.Controls.Add(this.labelMaxDays); - this.Settings.Controls.Add(this.upDownMaxDays); - this.Settings.Controls.Add(this.fileNamePatternTextBox); - this.Settings.Location = new System.Drawing.Point(15, 39); - this.Settings.Name = "Settings"; - this.Settings.Size = new System.Drawing.Size(402, 98); - this.Settings.TabIndex = 6; - this.Settings.TabStop = false; - // - // syntaxHelpLabel - // - this.syntaxHelpLabel.Location = new System.Drawing.Point(15, 140); - this.syntaxHelpLabel.Name = "syntaxHelpLabel"; - this.syntaxHelpLabel.Size = new System.Drawing.Size(402, 194); - this.syntaxHelpLabel.TabIndex = 7; - this.syntaxHelpLabel.Text = "Syntax Help Label"; - // - // buttonOk - // - this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(261, 347); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 8; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnButtonOKClick); - // - // buttonCancel - // - this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(342, 347); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 9; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // MultiFileMaskDialog - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(434, 386); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.syntaxHelpLabel); - this.Controls.Add(this.Settings); - this.Controls.Add(this.labelFileName); - this.Controls.Add(this.labelMultiSettingsFor); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.MinimumSize = new System.Drawing.Size(329, 420); - this.Name = "MultiFileMaskDialog"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "MultiFile settings"; - this.TopMost = true; - this.Load += new System.EventHandler(this.OnMultiFileMaskDialogLoad); - ((System.ComponentModel.ISupportInitialize)(this.upDownMaxDays)).EndInit(); - this.Settings.ResumeLayout(false); - this.Settings.PerformLayout(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Label labelMultiSettingsFor; - private System.Windows.Forms.Label labelFileName; - private System.Windows.Forms.Label labelFileNamePattern; - private System.Windows.Forms.NumericUpDown upDownMaxDays; - private System.Windows.Forms.TextBox fileNamePatternTextBox; - private System.Windows.Forms.Label labelMaxDays; - private System.Windows.Forms.GroupBox Settings; - private System.Windows.Forms.Label syntaxHelpLabel; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Button buttonCancel; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/MultiFileMaskDialog.cs b/src/LogExpert/Dialogs/MultiFileMaskDialog.cs deleted file mode 100644 index c8c7ff8b..00000000 --- a/src/LogExpert/Dialogs/MultiFileMaskDialog.cs +++ /dev/null @@ -1,67 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class MultiFileMaskDialog : Form - { - #region Fields - - #endregion - - #region cTor - - public MultiFileMaskDialog(Form parent, string fileName) - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - syntaxHelpLabel.Text = "" + - "Pattern syntax:\n\n" + - "* = any characters (wildcard)\n" + - "$D() = Date pattern\n" + - "$I = File index number\n" + - "$J = File index number, hidden when zero\n" + - "$J() = Like $J, but adding when non-zero\n" + - "\n" + - ":\n" + - "DD = day\n" + - "MM = month\n" + - "YY[YY] = year\n" + - "all other chars will be used as given"; - labelFileName.Text = fileName; - } - - #endregion - - #region Properties - - public string FileNamePattern { get; set; } - - public int MaxDays { get; set; } - - #endregion - - #region Events handler - - private void OnButtonOKClick(object sender, EventArgs e) - { - FileNamePattern = fileNamePatternTextBox.Text; - MaxDays = (int) upDownMaxDays.Value; - } - - private void OnMultiFileMaskDialogLoad(object sender, EventArgs e) - { - fileNamePatternTextBox.Text = FileNamePattern; - upDownMaxDays.Value = MaxDays; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/MultiLoadRequestDialog.Designer.cs b/src/LogExpert/Dialogs/MultiLoadRequestDialog.Designer.cs deleted file mode 100644 index e6dadd63..00000000 --- a/src/LogExpert/Dialogs/MultiLoadRequestDialog.Designer.cs +++ /dev/null @@ -1,89 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class MultiLoadRequestDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.buttonSingleMode = new System.Windows.Forms.Button(); - this.buttonMultiMode = new System.Windows.Forms.Button(); - this.labelChooseLoadingMode = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // buttonSingleMode - // - this.buttonSingleMode.DialogResult = System.Windows.Forms.DialogResult.Yes; - this.buttonSingleMode.Location = new System.Drawing.Point(12, 59); - this.buttonSingleMode.Name = "buttonSingleMode"; - this.buttonSingleMode.Size = new System.Drawing.Size(75, 23); - this.buttonSingleMode.TabIndex = 1; - this.buttonSingleMode.Text = "Single files"; - this.buttonSingleMode.UseVisualStyleBackColor = true; - // - // buttonMultiMode - // - this.buttonMultiMode.DialogResult = System.Windows.Forms.DialogResult.No; - this.buttonMultiMode.Location = new System.Drawing.Point(114, 59); - this.buttonMultiMode.Name = "buttonMultiMode"; - this.buttonMultiMode.Size = new System.Drawing.Size(75, 23); - this.buttonMultiMode.TabIndex = 2; - this.buttonMultiMode.Text = "Multi file"; - this.buttonMultiMode.UseVisualStyleBackColor = true; - // - // labelChooseLoadingMode - // - this.labelChooseLoadingMode.AutoSize = true; - this.labelChooseLoadingMode.Location = new System.Drawing.Point(48, 18); - this.labelChooseLoadingMode.Name = "labelChooseLoadingMode"; - this.labelChooseLoadingMode.Size = new System.Drawing.Size(167, 20); - this.labelChooseLoadingMode.TabIndex = 4; - this.labelChooseLoadingMode.Text = "Choose loading mode:"; - // - // MultiLoadRequestDialog - // - this.ClientSize = new System.Drawing.Size(237, 103); - this.Controls.Add(this.labelChooseLoadingMode); - this.Controls.Add(this.buttonMultiMode); - this.Controls.Add(this.buttonSingleMode); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "MultiLoadRequestDialog"; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Loading multiple files"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button buttonSingleMode; - private System.Windows.Forms.Button buttonMultiMode; - private System.Windows.Forms.Label labelChooseLoadingMode; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/MultiLoadRequestDialog.cs b/src/LogExpert/Dialogs/MultiLoadRequestDialog.cs deleted file mode 100644 index 1e9c94fb..00000000 --- a/src/LogExpert/Dialogs/MultiLoadRequestDialog.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class MultiLoadRequestDialog : Form - { - #region cTor - - public MultiLoadRequestDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/OpenUriDialog.Designer.cs b/src/LogExpert/Dialogs/OpenUriDialog.Designer.cs deleted file mode 100644 index 1d0235f6..00000000 --- a/src/LogExpert/Dialogs/OpenUriDialog.Designer.cs +++ /dev/null @@ -1,122 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class OpenUriDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OpenUriDialog)); - this.cmbUri = new System.Windows.Forms.ComboBox(); - this.label1 = new System.Windows.Forms.Label(); - this.okButton = new System.Windows.Forms.Button(); - this.cancelButton = new System.Windows.Forms.Button(); - this.label2 = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // uriComboBox - // - this.cmbUri.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.cmbUri.FormattingEnabled = true; - this.cmbUri.Location = new System.Drawing.Point(12, 37); - this.cmbUri.Name = "cmbUri"; - this.cmbUri.Size = new System.Drawing.Size(449, 21); - this.cmbUri.TabIndex = 0; - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(12, 21); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(32, 13); - this.label1.TabIndex = 1; - this.label1.Text = "URL:"; - // - // okButton - // - this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.okButton.DialogResult = System.Windows.Forms.DialogResult.OK; - this.okButton.Location = new System.Drawing.Point(305, 127); - this.okButton.Name = "okButton"; - this.okButton.Size = new System.Drawing.Size(75, 23); - this.okButton.TabIndex = 2; - this.okButton.Text = "OK"; - this.okButton.UseVisualStyleBackColor = true; - this.okButton.Click += new System.EventHandler(this.OnBtnOkClick); - // - // cancelButton - // - this.cancelButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.cancelButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.cancelButton.Location = new System.Drawing.Point(386, 127); - this.cancelButton.Name = "cancelButton"; - this.cancelButton.Size = new System.Drawing.Size(75, 23); - this.cancelButton.TabIndex = 3; - this.cancelButton.Text = "Cancel"; - this.cancelButton.UseVisualStyleBackColor = true; - // - // label2 - // - this.label2.AutoSize = true; - this.label2.Location = new System.Drawing.Point(12, 84); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(410, 13); - this.label2.TabIndex = 4; - this.label2.Text = "Enter a URL which is supported by an installed file system plugin (e.g. file:// o" + - "r sftp://)"; - // - // OpenUriDialog - // - this.AcceptButton = this.okButton; - this.CancelButton = this.cancelButton; - this.ClientSize = new System.Drawing.Size(475, 162); - this.Controls.Add(this.label2); - this.Controls.Add(this.cancelButton); - this.Controls.Add(this.okButton); - this.Controls.Add(this.label1); - this.Controls.Add(this.cmbUri); - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MaximumSize = new System.Drawing.Size(800, 260); - this.MinimizeBox = false; - this.MinimumSize = new System.Drawing.Size(491, 200); - this.Name = "OpenUriDialog"; - this.Text = "Open URL"; - this.Load += new System.EventHandler(this.OnOpenUriDialogLoad); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.ComboBox cmbUri; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Button okButton; - private System.Windows.Forms.Button cancelButton; - private System.Windows.Forms.Label label2; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/OpenUriDialog.cs b/src/LogExpert/Dialogs/OpenUriDialog.cs deleted file mode 100644 index 9c364f96..00000000 --- a/src/LogExpert/Dialogs/OpenUriDialog.cs +++ /dev/null @@ -1,69 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class OpenUriDialog : Form - { - #region Fields - - #endregion - - #region cTor - - public OpenUriDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - } - - #endregion - - #region Properties - - public string Uri => cmbUri.Text; - - public IList UriHistory { get; set; } - - #endregion - - #region Events handler - - private void OnOpenUriDialogLoad(object sender, EventArgs e) - { - if (UriHistory != null) - { - cmbUri.Items.Clear(); - foreach (string uri in UriHistory) - { - cmbUri.Items.Add(uri); - } - } - } - - private void OnBtnOkClick(object sender, EventArgs e) - { - UriHistory = new List(); - foreach (object item in cmbUri.Items) - { - UriHistory.Add(item.ToString()); - } - if (UriHistory.Contains(cmbUri.Text)) - { - UriHistory.Remove(cmbUri.Text); - } - UriHistory.Insert(0, cmbUri.Text); - - while (UriHistory.Count > 20) - { - UriHistory.RemoveAt(UriHistory.Count - 1); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/OverlayEventArgs.cs b/src/LogExpert/Dialogs/OverlayEventArgs.cs deleted file mode 100644 index c2a9d0ca..00000000 --- a/src/LogExpert/Dialogs/OverlayEventArgs.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System; -using LogExpert.Entities; - -namespace LogExpert.Dialogs -{ - public class OverlayEventArgs : EventArgs - { - #region Fields - - #endregion - - #region cTor - - public OverlayEventArgs(BookmarkOverlay overlay) - { - BookmarkOverlay = overlay; - } - - #endregion - - #region Properties - - public BookmarkOverlay BookmarkOverlay { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ParamRequesterDialog.Designer.cs b/src/LogExpert/Dialogs/ParamRequesterDialog.Designer.cs deleted file mode 100644 index 48fbbbba..00000000 --- a/src/LogExpert/Dialogs/ParamRequesterDialog.Designer.cs +++ /dev/null @@ -1,105 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class ParamRequesterDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.labelValueForParameter = new System.Windows.Forms.Label(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.buttonOk = new System.Windows.Forms.Button(); - this.comboBoxValue = new System.Windows.Forms.ComboBox(); - this.SuspendLayout(); - // - // labelValueForParameter - // - this.labelValueForParameter.AutoSize = true; - this.labelValueForParameter.Location = new System.Drawing.Point(13, 25); - this.labelValueForParameter.Name = "labelValueForParameter"; - this.labelValueForParameter.Size = new System.Drawing.Size(154, 20); - this.labelValueForParameter.TabIndex = 0; - this.labelValueForParameter.Text = "&Value for parameter:"; - // - // buttonCancel - // - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(238, 88); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 3; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // buttonOk - // - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(148, 88); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 2; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.okButton_Click); - // - // comboBoxValue - // - this.comboBoxValue.FormattingEnabled = true; - this.comboBoxValue.Location = new System.Drawing.Point(16, 48); - this.comboBoxValue.Name = "comboBoxValue"; - this.comboBoxValue.Size = new System.Drawing.Size(297, 28); - this.comboBoxValue.TabIndex = 1; - // - // ParamRequesterDialog - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(332, 130); - this.Controls.Add(this.comboBoxValue); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.labelValueForParameter); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "ParamRequesterDialog"; - this.ShowIcon = false; - this.ShowInTaskbar = false; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Tool parameter"; - this.Shown += new System.EventHandler(this.ParamRequesterDialog_Shown); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Label labelValueForParameter; - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.ComboBox comboBoxValue; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ParamRequesterDialog.cs b/src/LogExpert/Dialogs/ParamRequesterDialog.cs deleted file mode 100644 index 21dca01e..00000000 --- a/src/LogExpert/Dialogs/ParamRequesterDialog.cs +++ /dev/null @@ -1,62 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class ParamRequesterDialog : Form - { - #region Fields - - #endregion - - #region cTor - - public ParamRequesterDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - } - - #endregion - - #region Properties - - public string ParamName { get; set; } - - public string ParamValue { get; set; } - - public string[] Values { get; set; } - - #endregion - - #region Events handler - - private void ParamRequesterDialog_Shown(object sender, EventArgs e) - { - labelValueForParameter.Text = ParamName; - - if (Values != null) - { - foreach (string value in Values) - { - comboBoxValue.Items.Add(value); - } - comboBoxValue.SelectedIndex = 0; - } - } - - private void okButton_Click(object sender, EventArgs e) - { - ParamValue = comboBoxValue.Text; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ProjectLoadDlg.Designer.cs b/src/LogExpert/Dialogs/ProjectLoadDlg.Designer.cs deleted file mode 100644 index 66d59c89..00000000 --- a/src/LogExpert/Dialogs/ProjectLoadDlg.Designer.cs +++ /dev/null @@ -1,120 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class ProjectLoadDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ProjectLoadDlg)); - this.labelInformational = new System.Windows.Forms.Label(); - this.buttonCloseTabs = new System.Windows.Forms.Button(); - this.buttonNewWindow = new System.Windows.Forms.Button(); - this.buttonIgnore = new System.Windows.Forms.Button(); - this.labelChooseHowToProceed = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // labelInformational - // - this.labelInformational.Location = new System.Drawing.Point(12, 9); - this.labelInformational.Name = "labelInformational"; - this.labelInformational.Size = new System.Drawing.Size(178, 41); - this.labelInformational.TabIndex = 0; - this.labelInformational.Text = "Restoring layout requires an empty workbench. \r\n\r\n"; - // - // buttonCloseTabs - // - this.buttonCloseTabs.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonCloseTabs.Location = new System.Drawing.Point(43, 94); - this.buttonCloseTabs.Name = "buttonCloseTabs"; - this.buttonCloseTabs.Size = new System.Drawing.Size(113, 23); - this.buttonCloseTabs.TabIndex = 1; - this.buttonCloseTabs.Text = "Close existing tabs"; - this.buttonCloseTabs.UseVisualStyleBackColor = true; - this.buttonCloseTabs.Click += new System.EventHandler(this.OnButtonCloseTabsClick); - // - // buttonNewWindow - // - this.buttonNewWindow.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonNewWindow.Location = new System.Drawing.Point(43, 124); - this.buttonNewWindow.Name = "buttonNewWindow"; - this.buttonNewWindow.Size = new System.Drawing.Size(113, 23); - this.buttonNewWindow.TabIndex = 2; - this.buttonNewWindow.Text = "Open new window"; - this.buttonNewWindow.UseVisualStyleBackColor = true; - this.buttonNewWindow.Click += new System.EventHandler(this.OnButtonNewWindowClick); - // - // buttonIgnore - // - this.buttonIgnore.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonIgnore.Location = new System.Drawing.Point(43, 154); - this.buttonIgnore.Name = "buttonIgnore"; - this.buttonIgnore.Size = new System.Drawing.Size(113, 23); - this.buttonIgnore.TabIndex = 3; - this.buttonIgnore.Text = "Ignore layout data"; - this.buttonIgnore.UseVisualStyleBackColor = true; - this.buttonIgnore.Click += new System.EventHandler(this.OnButtonIgnoreClick); - // - // labelChooseHowToProceed - // - this.labelChooseHowToProceed.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) - | System.Windows.Forms.AnchorStyles.Right))); - this.labelChooseHowToProceed.AutoSize = true; - this.labelChooseHowToProceed.Location = new System.Drawing.Point(21, 66); - this.labelChooseHowToProceed.Name = "labelChooseHowToProceed"; - this.labelChooseHowToProceed.Size = new System.Drawing.Size(230, 20); - this.labelChooseHowToProceed.TabIndex = 4; - this.labelChooseHowToProceed.Text = "Please choose how to proceed:"; - // - // ProjectLoadDlg - // - this.ClientSize = new System.Drawing.Size(258, 196); - this.Controls.Add(this.labelChooseHowToProceed); - this.Controls.Add(this.buttonIgnore); - this.Controls.Add(this.buttonNewWindow); - this.Controls.Add(this.buttonCloseTabs); - this.Controls.Add(this.labelInformational); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "ProjectLoadDlg"; - this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Loading Session"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Label labelInformational; - private System.Windows.Forms.Button buttonCloseTabs; - private System.Windows.Forms.Button buttonNewWindow; - private System.Windows.Forms.Button buttonIgnore; - private System.Windows.Forms.Label labelChooseHowToProceed; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ProjectLoadDlg.cs b/src/LogExpert/Dialogs/ProjectLoadDlg.cs deleted file mode 100644 index 2a53437b..00000000 --- a/src/LogExpert/Dialogs/ProjectLoadDlg.cs +++ /dev/null @@ -1,65 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public enum ProjectLoadDlgResult - { - Cancel, - CloseTabs, - NewWindow, - IgnoreLayout - } - - public partial class ProjectLoadDlg : Form - { - #region Fields - - #endregion - - #region cTor - - public ProjectLoadDlg() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - } - - #endregion - - #region Properties - - public ProjectLoadDlgResult ProjectLoadResult { get; set; } = ProjectLoadDlgResult.Cancel; - - #endregion - - #region Events handler - - private void OnButtonCloseTabsClick(object sender, EventArgs e) - { - ProjectLoadResult = ProjectLoadDlgResult.CloseTabs; - Close(); - } - - private void OnButtonNewWindowClick(object sender, EventArgs e) - { - ProjectLoadResult = ProjectLoadDlgResult.NewWindow; - Close(); - } - - private void OnButtonIgnoreClick(object sender, EventArgs e) - { - ProjectLoadResult = ProjectLoadDlgResult.IgnoreLayout; - Close(); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/RegexHelperDialog.Designer.cs b/src/LogExpert/Dialogs/RegexHelperDialog.Designer.cs deleted file mode 100644 index 05fda035..00000000 --- a/src/LogExpert/Dialogs/RegexHelperDialog.Designer.cs +++ /dev/null @@ -1,195 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class RegexHelperDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.buttonCancel = new System.Windows.Forms.Button(); - this.buttonOk = new System.Windows.Forms.Button(); - this.labelRegex = new System.Windows.Forms.Label(); - this.labelTestText = new System.Windows.Forms.Label(); - this.labelMatches = new System.Windows.Forms.Label(); - this.textBoxMatches = new System.Windows.Forms.TextBox(); - this.checkBoxCaseSensitive = new System.Windows.Forms.CheckBox(); - this.comboBoxRegex = new System.Windows.Forms.ComboBox(); - this.comboBoxTestText = new System.Windows.Forms.ComboBox(); - this.helpProvider1 = new System.Windows.Forms.HelpProvider(); - this.buttonHelp = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // buttonCancel - // - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(365, 371); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 0; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // buttonOk - // - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(284, 371); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 1; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); - // - // labelRegex - // - this.labelRegex.AutoSize = true; - this.labelRegex.Location = new System.Drawing.Point(14, 14); - this.labelRegex.Name = "labelRegex"; - this.labelRegex.Size = new System.Drawing.Size(151, 20); - this.labelRegex.TabIndex = 3; - this.labelRegex.Text = "Regular Expression:"; - // - // labelTestText - // - this.labelTestText.AutoSize = true; - this.labelTestText.Location = new System.Drawing.Point(14, 98); - this.labelTestText.Name = "labelTestText"; - this.labelTestText.Size = new System.Drawing.Size(74, 20); - this.labelTestText.TabIndex = 5; - this.labelTestText.Text = "Test text:"; - // - // labelMatches - // - this.labelMatches.AutoSize = true; - this.labelMatches.Location = new System.Drawing.Point(14, 152); - this.labelMatches.Name = "labelMatches"; - this.labelMatches.Size = new System.Drawing.Size(74, 20); - this.labelMatches.TabIndex = 6; - this.labelMatches.Text = "Matches:"; - // - // textBoxMatches - // - this.textBoxMatches.Location = new System.Drawing.Point(12, 175); - this.textBoxMatches.Multiline = true; - this.textBoxMatches.Name = "textBoxMatches"; - this.textBoxMatches.ReadOnly = true; - this.textBoxMatches.ScrollBars = System.Windows.Forms.ScrollBars.Both; - this.textBoxMatches.Size = new System.Drawing.Size(428, 190); - this.textBoxMatches.TabIndex = 7; - // - // checkBoxCaseSensitive - // - this.checkBoxCaseSensitive.AutoSize = true; - this.checkBoxCaseSensitive.Location = new System.Drawing.Point(12, 71); - this.checkBoxCaseSensitive.Name = "checkBoxCaseSensitive"; - this.checkBoxCaseSensitive.Size = new System.Drawing.Size(137, 24); - this.checkBoxCaseSensitive.TabIndex = 8; - this.checkBoxCaseSensitive.Text = "Case sensitive"; - this.checkBoxCaseSensitive.UseVisualStyleBackColor = true; - this.checkBoxCaseSensitive.CheckedChanged += new System.EventHandler(this.OnCaseSensitiveCheckBoxCheckedChanged); - // - // comboBoxRegex - // - this.comboBoxRegex.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; - this.comboBoxRegex.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; - this.comboBoxRegex.FormattingEnabled = true; - this.comboBoxRegex.Location = new System.Drawing.Point(12, 37); - this.comboBoxRegex.Name = "comboBoxRegex"; - this.comboBoxRegex.Size = new System.Drawing.Size(428, 28); - this.comboBoxRegex.TabIndex = 10; - this.comboBoxRegex.TextChanged += new System.EventHandler(this.OnComboBoxRegexTextChanged); - // - // comboBoxTestText - // - this.comboBoxTestText.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; - this.comboBoxTestText.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems; - this.comboBoxTestText.FormattingEnabled = true; - this.comboBoxTestText.Location = new System.Drawing.Point(12, 121); - this.comboBoxTestText.Name = "comboBoxTestText"; - this.comboBoxTestText.Size = new System.Drawing.Size(428, 28); - this.comboBoxTestText.TabIndex = 11; - this.comboBoxTestText.TextChanged += new System.EventHandler(this.OnComboBoxTestTextTextChanged); - // - // helpProvider1 - // - this.helpProvider1.HelpNamespace = "LogExpert.chm"; - // - // buttonHelp - // - this.helpProvider1.SetHelpKeyword(this.buttonHelp, "RegEx.htm"); - this.helpProvider1.SetHelpNavigator(this.buttonHelp, System.Windows.Forms.HelpNavigator.Topic); - this.buttonHelp.Location = new System.Drawing.Point(13, 371); - this.buttonHelp.Name = "buttonHelp"; - this.helpProvider1.SetShowHelp(this.buttonHelp, true); - this.buttonHelp.Size = new System.Drawing.Size(75, 23); - this.buttonHelp.TabIndex = 12; - this.buttonHelp.Text = "Help"; - this.buttonHelp.UseVisualStyleBackColor = true; - this.buttonHelp.Click += new System.EventHandler(this.OnButtonHelpClick); - // - // RegexHelperDialog - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(452, 403); - this.Controls.Add(this.buttonHelp); - this.Controls.Add(this.comboBoxTestText); - this.Controls.Add(this.comboBoxRegex); - this.Controls.Add(this.checkBoxCaseSensitive); - this.Controls.Add(this.textBoxMatches); - this.Controls.Add(this.labelMatches); - this.Controls.Add(this.labelTestText); - this.Controls.Add(this.labelRegex); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.buttonCancel); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.helpProvider1.SetHelpKeyword(this, "RegEx.htm"); - this.helpProvider1.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "RegexHelperDialog"; - this.helpProvider1.SetShowHelp(this, true); - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Regex-Helper"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Label labelRegex; - private System.Windows.Forms.Label labelTestText; - private System.Windows.Forms.Label labelMatches; - private System.Windows.Forms.TextBox textBoxMatches; - private System.Windows.Forms.CheckBox checkBoxCaseSensitive; - private System.Windows.Forms.ComboBox comboBoxRegex; - private System.Windows.Forms.ComboBox comboBoxTestText; - private System.Windows.Forms.HelpProvider helpProvider1; - private System.Windows.Forms.Button buttonHelp; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/RegexHelperDialog.cs b/src/LogExpert/Dialogs/RegexHelperDialog.cs deleted file mode 100644 index 83921af1..00000000 --- a/src/LogExpert/Dialogs/RegexHelperDialog.cs +++ /dev/null @@ -1,168 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using System.Text.RegularExpressions; -using LogExpert.Config; - -namespace LogExpert.Dialogs -{ - public partial class RegexHelperDialog : Form - { - #region Fields - - private static readonly int MAX_HISTORY = 30; - private bool _caseSensitive; - - #endregion - - #region cTor - - public RegexHelperDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - Load += OnRegexHelperDialogLoad; - } - - #endregion - - #region Properties - - public bool CaseSensitive - { - get => _caseSensitive; - set - { - _caseSensitive = value; - checkBoxCaseSensitive.Checked = value; - } - } - - public string Pattern - { - get => comboBoxRegex.Text; - set => comboBoxRegex.Text = value; - } - - #endregion - - #region Private Methods - - private void UpdateMatches() - { - textBoxMatches.Text = ""; - try - { - Regex rex = new(comboBoxRegex.Text, _caseSensitive ? RegexOptions.None : RegexOptions.IgnoreCase); - MatchCollection matches = rex.Matches(comboBoxTestText.Text); - - foreach (Match match in matches) - { - textBoxMatches.Text += $"{match.Value}\r\n"; - } - } - catch (ArgumentException) - { - textBoxMatches.Text = "No valid regex pattern"; - } - } - - private void LoadHistory() - { - RegexHistory history = ConfigManager.Settings.regexHistory; - - if (history == null) - { - return; - } - - comboBoxRegex.Items.Clear(); - foreach (string item in history.expressionHistoryList) - { - comboBoxRegex.Items.Add(item); - } - - comboBoxTestText.Items.Clear(); - foreach (string item in history.testtextHistoryList) - { - comboBoxTestText.Items.Add(item); - } - } - - private void SaveHistory() - { - RegexHistory history = new(); - - foreach (string item in comboBoxRegex.Items) - { - history.expressionHistoryList.Add(item); - } - - foreach (string item in comboBoxTestText.Items) - { - history.testtextHistoryList.Add(item); - } - - ConfigManager.Settings.regexHistory = history; - ConfigManager.Save(SettingsFlags.RegexHistory); - } - - #endregion - - #region Events handler - - private void OnRegexHelperDialogLoad(object sender, EventArgs e) - { - LoadHistory(); - } - - private void OnCaseSensitiveCheckBoxCheckedChanged(object sender, EventArgs e) - { - _caseSensitive = checkBoxCaseSensitive.Checked; - UpdateMatches(); - } - - - private void OnButtonOkClick(object sender, EventArgs e) - { - string text = comboBoxRegex.Text; - comboBoxRegex.Items.Remove(text); - comboBoxRegex.Items.Insert(0, text); - - text = comboBoxTestText.Text; - comboBoxTestText.Items.Remove(text); - comboBoxTestText.Items.Insert(0, text); - - if (comboBoxRegex.Items.Count > MAX_HISTORY) - { - comboBoxRegex.Items.Remove(comboBoxRegex.Items.Count - 1); - } - if (comboBoxTestText.Items.Count > MAX_HISTORY) - { - comboBoxTestText.Items.Remove(comboBoxTestText.Items.Count - 1); - } - - SaveHistory(); - } - - private void OnComboBoxRegexTextChanged(object sender, EventArgs e) - { - UpdateMatches(); - } - - private void OnComboBoxTestTextTextChanged(object sender, EventArgs e) - { - UpdateMatches(); - } - - private void OnButtonHelpClick(object sender, EventArgs e) - { - Help.ShowHelp(this, "LogExpert.chm", HelpNavigator.Topic, "RegEx.htm"); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SearchDialog.Designer.cs b/src/LogExpert/Dialogs/SearchDialog.Designer.cs deleted file mode 100644 index 8e93d131..00000000 --- a/src/LogExpert/Dialogs/SearchDialog.Designer.cs +++ /dev/null @@ -1,254 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class SearchDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.buttonOk = new System.Windows.Forms.Button(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.labelSearchFor = new System.Windows.Forms.Label(); - this.checkBoxCaseSensitive = new System.Windows.Forms.CheckBox(); - this.checkBoxRegex = new System.Windows.Forms.CheckBox(); - this.buttonRegexHelper = new System.Windows.Forms.Button(); - this.radioButtonFromTop = new System.Windows.Forms.RadioButton(); - this.radioButtonFromSelected = new System.Windows.Forms.RadioButton(); - this.groupBoxSearchStart = new System.Windows.Forms.GroupBox(); - this.groupBoxOptions = new System.Windows.Forms.GroupBox(); - this.groupBoxDirection = new System.Windows.Forms.GroupBox(); - this.radioButtonBackward = new System.Windows.Forms.RadioButton(); - this.radioButtonForward = new System.Windows.Forms.RadioButton(); - this.comboBoxSearchFor = new System.Windows.Forms.ComboBox(); - this.helpProvider1 = new System.Windows.Forms.HelpProvider(); - this.groupBoxSearchStart.SuspendLayout(); - this.groupBoxOptions.SuspendLayout(); - this.groupBoxDirection.SuspendLayout(); - this.SuspendLayout(); - // - // buttonOk - // - this.buttonOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(317, 215); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 5; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); - // - // buttonCancel - // - this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(398, 215); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 6; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - this.buttonCancel.Click += new System.EventHandler(this.OnButtonCancelClick); - // - // labelSearchFor - // - this.labelSearchFor.AutoSize = true; - this.labelSearchFor.Location = new System.Drawing.Point(10, 9); - this.labelSearchFor.Name = "labelSearchFor"; - this.labelSearchFor.Size = new System.Drawing.Size(87, 20); - this.labelSearchFor.TabIndex = 0; - this.labelSearchFor.Text = "&Search for:"; - // - // checkBoxCaseSensitive - // - this.checkBoxCaseSensitive.AutoSize = true; - this.checkBoxCaseSensitive.Location = new System.Drawing.Point(6, 19); - this.checkBoxCaseSensitive.Name = "checkBoxCaseSensitive"; - this.checkBoxCaseSensitive.Size = new System.Drawing.Size(137, 24); - this.checkBoxCaseSensitive.TabIndex = 4; - this.checkBoxCaseSensitive.Text = "&Case sensitive"; - this.checkBoxCaseSensitive.UseVisualStyleBackColor = true; - // - // checkBoxRegex - // - this.checkBoxRegex.AutoSize = true; - this.checkBoxRegex.Location = new System.Drawing.Point(6, 43); - this.checkBoxRegex.Name = "checkBoxRegex"; - this.checkBoxRegex.Size = new System.Drawing.Size(171, 24); - this.checkBoxRegex.TabIndex = 5; - this.checkBoxRegex.Text = "&Regular expression"; - this.checkBoxRegex.UseVisualStyleBackColor = true; - // - // buttonRegexHelper - // - this.buttonRegexHelper.Location = new System.Drawing.Point(6, 72); - this.buttonRegexHelper.Name = "buttonRegexHelper"; - this.buttonRegexHelper.Size = new System.Drawing.Size(84, 26); - this.buttonRegexHelper.TabIndex = 3; - this.buttonRegexHelper.Text = "Regex-&Helper"; - this.buttonRegexHelper.UseVisualStyleBackColor = true; - this.buttonRegexHelper.Click += new System.EventHandler(this.OnButtonRegexClick); - // - // radioButtonFromTop - // - this.radioButtonFromTop.AutoSize = true; - this.radioButtonFromTop.Location = new System.Drawing.Point(6, 19); - this.radioButtonFromTop.Name = "radioButtonFromTop"; - this.radioButtonFromTop.Size = new System.Drawing.Size(98, 24); - this.radioButtonFromTop.TabIndex = 7; - this.radioButtonFromTop.TabStop = true; - this.radioButtonFromTop.Text = "From top"; - this.radioButtonFromTop.UseVisualStyleBackColor = true; - // - // radioButtonFromSelected - // - this.radioButtonFromSelected.AutoSize = true; - this.radioButtonFromSelected.Location = new System.Drawing.Point(6, 42); - this.radioButtonFromSelected.Name = "radioButtonFromSelected"; - this.radioButtonFromSelected.Size = new System.Drawing.Size(163, 24); - this.radioButtonFromSelected.TabIndex = 8; - this.radioButtonFromSelected.TabStop = true; - this.radioButtonFromSelected.Text = "From selected line"; - this.radioButtonFromSelected.UseVisualStyleBackColor = true; - // - // groupBoxSearchStart - // - this.groupBoxSearchStart.Controls.Add(this.radioButtonFromTop); - this.groupBoxSearchStart.Controls.Add(this.radioButtonFromSelected); - this.groupBoxSearchStart.Location = new System.Drawing.Point(12, 74); - this.groupBoxSearchStart.Name = "groupBoxSearchStart"; - this.groupBoxSearchStart.Size = new System.Drawing.Size(179, 79); - this.groupBoxSearchStart.TabIndex = 1; - this.groupBoxSearchStart.TabStop = false; - this.groupBoxSearchStart.Text = "Search start"; - // - // groupBoxOptions - // - this.groupBoxOptions.Controls.Add(this.checkBoxCaseSensitive); - this.groupBoxOptions.Controls.Add(this.checkBoxRegex); - this.groupBoxOptions.Controls.Add(this.buttonRegexHelper); - this.groupBoxOptions.Location = new System.Drawing.Point(198, 74); - this.groupBoxOptions.Name = "groupBoxOptions"; - this.groupBoxOptions.Size = new System.Drawing.Size(275, 104); - this.groupBoxOptions.TabIndex = 2; - this.groupBoxOptions.TabStop = false; - this.groupBoxOptions.Text = "Options"; - // - // groupBoxDirection - // - this.groupBoxDirection.Controls.Add(this.radioButtonBackward); - this.groupBoxDirection.Controls.Add(this.radioButtonForward); - this.groupBoxDirection.Location = new System.Drawing.Point(13, 159); - this.groupBoxDirection.Name = "groupBoxDirection"; - this.groupBoxDirection.Size = new System.Drawing.Size(122, 79); - this.groupBoxDirection.TabIndex = 4; - this.groupBoxDirection.TabStop = false; - this.groupBoxDirection.Text = "Direction"; - // - // radioButtonBackward - // - this.radioButtonBackward.AutoSize = true; - this.radioButtonBackward.Location = new System.Drawing.Point(7, 44); - this.radioButtonBackward.Name = "radioButtonBackward"; - this.radioButtonBackward.Size = new System.Drawing.Size(104, 24); - this.radioButtonBackward.TabIndex = 1; - this.radioButtonBackward.TabStop = true; - this.radioButtonBackward.Text = "Backward"; - this.radioButtonBackward.UseVisualStyleBackColor = true; - // - // radioButtonForward - // - this.radioButtonForward.AutoSize = true; - this.radioButtonForward.Location = new System.Drawing.Point(7, 20); - this.radioButtonForward.Name = "radioButtonForward"; - this.radioButtonForward.Size = new System.Drawing.Size(92, 24); - this.radioButtonForward.TabIndex = 0; - this.radioButtonForward.TabStop = true; - this.radioButtonForward.Text = "Forward"; - this.radioButtonForward.UseVisualStyleBackColor = true; - // - // comboBoxSearchFor - // - this.comboBoxSearchFor.FormattingEnabled = true; - this.comboBoxSearchFor.Location = new System.Drawing.Point(13, 34); - this.comboBoxSearchFor.Name = "comboBoxSearchFor"; - this.comboBoxSearchFor.Size = new System.Drawing.Size(460, 28); - this.comboBoxSearchFor.TabIndex = 0; - // - // helpProvider1 - // - this.helpProvider1.HelpNamespace = "LogExpert.chm"; - // - // SearchDialog - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(488, 250); - this.Controls.Add(this.comboBoxSearchFor); - this.Controls.Add(this.groupBoxDirection); - this.Controls.Add(this.groupBoxOptions); - this.Controls.Add(this.groupBoxSearchStart); - this.Controls.Add(this.labelSearchFor); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.buttonOk); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.helpProvider1.SetHelpKeyword(this, "Search and Navigation.htm"); - this.helpProvider1.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "SearchDialog"; - this.helpProvider1.SetShowHelp(this, true); - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Search"; - this.groupBoxSearchStart.ResumeLayout(false); - this.groupBoxSearchStart.PerformLayout(); - this.groupBoxOptions.ResumeLayout(false); - this.groupBoxOptions.PerformLayout(); - this.groupBoxDirection.ResumeLayout(false); - this.groupBoxDirection.PerformLayout(); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.Label labelSearchFor; - private System.Windows.Forms.CheckBox checkBoxCaseSensitive; - private System.Windows.Forms.CheckBox checkBoxRegex; - private System.Windows.Forms.Button buttonRegexHelper; - private System.Windows.Forms.RadioButton radioButtonFromTop; - private System.Windows.Forms.RadioButton radioButtonFromSelected; - private System.Windows.Forms.GroupBox groupBoxSearchStart; - private System.Windows.Forms.GroupBox groupBoxOptions; - private System.Windows.Forms.GroupBox groupBoxDirection; - private System.Windows.Forms.RadioButton radioButtonBackward; - private System.Windows.Forms.RadioButton radioButtonForward; - private System.Windows.Forms.ComboBox comboBoxSearchFor; - private System.Windows.Forms.HelpProvider helpProvider1; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SearchDialog.cs b/src/LogExpert/Dialogs/SearchDialog.cs deleted file mode 100644 index 9e2f90d3..00000000 --- a/src/LogExpert/Dialogs/SearchDialog.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Drawing; -using System.Text.RegularExpressions; -using System.Windows.Forms; -using LogExpert.Entities; -using NLog; - -namespace LogExpert.Dialogs -{ - public partial class SearchDialog : Form - { - #region Fields - - private static readonly int MAX_HISTORY = 30; - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - - #endregion - - #region cTor - - public SearchDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - Load += OnSearchDialogLoad; - } - - #endregion - - #region Properties - - public SearchParams SearchParams { get; set; } - - #endregion - - #region Events handler - - private void OnSearchDialogLoad(object sender, EventArgs e) - { - if (SearchParams != null) - { - if (SearchParams.isFromTop) - { - radioButtonFromTop.Checked = true; - } - else - { - radioButtonFromSelected.Checked = true; - } - - if (SearchParams.isForward) - { - radioButtonForward.Checked = true; - } - else - { - radioButtonBackward.Checked = true; - } - - checkBoxRegex.Checked = SearchParams.isRegex; - checkBoxCaseSensitive.Checked = SearchParams.isCaseSensitive; - foreach (string item in SearchParams.historyList) - { - comboBoxSearchFor.Items.Add(item); - } - - if (comboBoxSearchFor.Items.Count > 0) - { - comboBoxSearchFor.SelectedIndex = 0; - } - } - else - { - radioButtonFromSelected.Checked = true; - radioButtonForward.Checked = true; - SearchParams = new SearchParams(); - } - } - - private void OnButtonRegexClick(object sender, EventArgs e) - { - RegexHelperDialog dlg = new(); - dlg.Owner = this; - dlg.CaseSensitive = checkBoxCaseSensitive.Checked; - dlg.Pattern = comboBoxSearchFor.Text; - - DialogResult res = dlg.ShowDialog(); - if (res == DialogResult.OK) - { - checkBoxCaseSensitive.Checked = dlg.CaseSensitive; - comboBoxSearchFor.Text = dlg.Pattern; - } - } - - private void OnButtonOkClick(object sender, EventArgs e) - { - try - { - if (checkBoxRegex.Checked) - { - if (string.IsNullOrWhiteSpace(comboBoxSearchFor.Text)) - { - throw new ArgumentException("Search text is empty"); - } - - // ReSharper disable once ReturnValueOfPureMethodIsNotUsed - Regex.IsMatch("", comboBoxSearchFor.Text); - } - - SearchParams.searchText = comboBoxSearchFor.Text; - SearchParams.isCaseSensitive = checkBoxCaseSensitive.Checked; - SearchParams.isForward = radioButtonForward.Checked; - SearchParams.isFromTop = radioButtonFromTop.Checked; - SearchParams.isRegex = checkBoxRegex.Checked; - SearchParams.historyList.Remove(comboBoxSearchFor.Text); - SearchParams.historyList.Insert(0, comboBoxSearchFor.Text); - if (SearchParams.historyList.Count > MAX_HISTORY) - { - SearchParams.historyList.RemoveAt(SearchParams.historyList.Count - 1); - } - } - catch (Exception ex) - { - _logger.Error(ex, "Error during ok click"); - MessageBox.Show($"Error during creation of search parameter\r\n{ex.Message}"); - } - } - - #endregion - - private void OnButtonCancelClick(object sender, EventArgs e) - { - Close(); - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SearchProgressDialog.Designer.cs b/src/LogExpert/Dialogs/SearchProgressDialog.Designer.cs deleted file mode 100644 index c0532607..00000000 --- a/src/LogExpert/Dialogs/SearchProgressDialog.Designer.cs +++ /dev/null @@ -1,75 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class SearchProgressDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.buttonCancel = new System.Windows.Forms.Button(); - this.labelSearchProgress = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // buttonCancel - // - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(159, 40); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(90, 23); - this.buttonCancel.TabIndex = 0; - this.buttonCancel.Text = "Cancel search"; - this.buttonCancel.UseVisualStyleBackColor = true; - this.buttonCancel.Click += new System.EventHandler(this.OnButtonCancelClick); - // - // labelSearchProgress - // - this.labelSearchProgress.AutoSize = true; - this.labelSearchProgress.Location = new System.Drawing.Point(13, 13); - this.labelSearchProgress.Name = "labelSearchProgress"; - this.labelSearchProgress.Size = new System.Drawing.Size(175, 20); - this.labelSearchProgress.TabIndex = 1; - this.labelSearchProgress.Text = "Searching in progress..."; - // - // SearchProgressDialog - // - this.ClientSize = new System.Drawing.Size(261, 80); - this.ControlBox = false; - this.Controls.Add(this.labelSearchProgress); - this.Controls.Add(this.buttonCancel); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.Name = "SearchProgressDialog"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Searching..."; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.Label labelSearchProgress; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SearchProgressDialog.cs b/src/LogExpert/Dialogs/SearchProgressDialog.cs deleted file mode 100644 index 8e4ea303..00000000 --- a/src/LogExpert/Dialogs/SearchProgressDialog.cs +++ /dev/null @@ -1,42 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class SearchProgressDialog : Form - { - #region Fields - - #endregion - - #region cTor - - public SearchProgressDialog() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - ShouldStop = false; - } - - #endregion - - #region Properties - - public bool ShouldStop { get; private set; } - - #endregion - - #region Events handler - - private void OnButtonCancelClick(object sender, EventArgs e) - { - ShouldStop = true; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SelectLineEventArgs.cs b/src/LogExpert/Dialogs/SelectLineEventArgs.cs deleted file mode 100644 index 4f2fa88b..00000000 --- a/src/LogExpert/Dialogs/SelectLineEventArgs.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -namespace LogExpert.Dialogs -{ - public class SelectLineEventArgs : EventArgs - { - #region Fields - - #endregion - - #region cTor - - public SelectLineEventArgs(int line) - { - Line = line; - } - - #endregion - - #region Properties - - public int Line { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/SettingsDialog.Designer.cs b/src/LogExpert/Dialogs/SettingsDialog.Designer.cs deleted file mode 100644 index 3ccc13f5..00000000 --- a/src/LogExpert/Dialogs/SettingsDialog.Designer.cs +++ /dev/null @@ -1,1846 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class SettingsDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - components = new System.ComponentModel.Container(); - System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsDialog)); - tabControlSettings = new System.Windows.Forms.TabControl(); - tabPageViewSettings = new System.Windows.Forms.TabPage(); - labelWarningMaximumLineLenght = new System.Windows.Forms.Label(); - upDownMaximumLineLength = new System.Windows.Forms.NumericUpDown(); - labelMaximumLineLength = new System.Windows.Forms.Label(); - upDownMaximumFilterEntriesDisplayed = new System.Windows.Forms.NumericUpDown(); - labelMaximumFilterEntriesDisplayed = new System.Windows.Forms.Label(); - upDownMaximumFilterEntries = new System.Windows.Forms.NumericUpDown(); - labelMaximumFilterEntries = new System.Windows.Forms.Label(); - labelDefaultEncoding = new System.Windows.Forms.Label(); - comboBoxEncoding = new System.Windows.Forms.ComboBox(); - groupBoxMisc = new System.Windows.Forms.GroupBox(); - checkBoxShowErrorMessageOnlyOneInstance = new System.Windows.Forms.CheckBox(); - cpDownColumnWidth = new System.Windows.Forms.NumericUpDown(); - checkBoxColumnSize = new System.Windows.Forms.CheckBox(); - buttonTailColor = new System.Windows.Forms.Button(); - checkBoxTailState = new System.Windows.Forms.CheckBox(); - checkBoxOpenLastFiles = new System.Windows.Forms.CheckBox(); - checkBoxSingleInstance = new System.Windows.Forms.CheckBox(); - checkBoxAskCloseTabs = new System.Windows.Forms.CheckBox(); - groupBoxDefaults = new System.Windows.Forms.GroupBox(); - checkBoxDarkMode = new System.Windows.Forms.CheckBox(); - checkBoxFollowTail = new System.Windows.Forms.CheckBox(); - checkBoxColumnFinder = new System.Windows.Forms.CheckBox(); - checkBoxSyncFilter = new System.Windows.Forms.CheckBox(); - checkBoxFilterTail = new System.Windows.Forms.CheckBox(); - groupBoxFont = new System.Windows.Forms.GroupBox(); - buttonChangeFont = new System.Windows.Forms.Button(); - labelFont = new System.Windows.Forms.Label(); - tabPageTimeStampFeatures = new System.Windows.Forms.TabPage(); - groupBoxTimeSpreadDisplay = new System.Windows.Forms.GroupBox(); - groupBoxDisplayMode = new System.Windows.Forms.GroupBox(); - radioButtonLineView = new System.Windows.Forms.RadioButton(); - radioButtonTimeView = new System.Windows.Forms.RadioButton(); - checkBoxReverseAlpha = new System.Windows.Forms.CheckBox(); - buttonTimespreadColor = new System.Windows.Forms.Button(); - checkBoxTimeSpread = new System.Windows.Forms.CheckBox(); - groupBoxTimeStampNavigationControl = new System.Windows.Forms.GroupBox(); - checkBoxTimestamp = new System.Windows.Forms.CheckBox(); - groupBoxMouseDragDefaults = new System.Windows.Forms.GroupBox(); - radioButtonVerticalMouseDragInverted = new System.Windows.Forms.RadioButton(); - radioButtonHorizMouseDrag = new System.Windows.Forms.RadioButton(); - radioButtonVerticalMouseDrag = new System.Windows.Forms.RadioButton(); - tabPageExternalTools = new System.Windows.Forms.TabPage(); - labelToolsDescription = new System.Windows.Forms.Label(); - buttonToolDelete = new System.Windows.Forms.Button(); - buttonToolAdd = new System.Windows.Forms.Button(); - buttonToolDown = new System.Windows.Forms.Button(); - buttonToolUp = new System.Windows.Forms.Button(); - listBoxTools = new System.Windows.Forms.CheckedListBox(); - groupBoxToolSettings = new System.Windows.Forms.GroupBox(); - labelWorkingDir = new System.Windows.Forms.Label(); - buttonWorkingDir = new System.Windows.Forms.Button(); - textBoxWorkingDir = new System.Windows.Forms.TextBox(); - buttonIcon = new System.Windows.Forms.Button(); - labelToolName = new System.Windows.Forms.Label(); - labelToolColumnizerForOutput = new System.Windows.Forms.Label(); - comboBoxColumnizer = new System.Windows.Forms.ComboBox(); - textBoxToolName = new System.Windows.Forms.TextBox(); - checkBoxSysout = new System.Windows.Forms.CheckBox(); - buttonArguments = new System.Windows.Forms.Button(); - labelTool = new System.Windows.Forms.Label(); - buttonTool = new System.Windows.Forms.Button(); - textBoxTool = new System.Windows.Forms.TextBox(); - labelArguments = new System.Windows.Forms.Label(); - textBoxArguments = new System.Windows.Forms.TextBox(); - tabPageColumnizers = new System.Windows.Forms.TabPage(); - checkBoxAutoPick = new System.Windows.Forms.CheckBox(); - checkBoxMaskPrio = new System.Windows.Forms.CheckBox(); - buttonDelete = new System.Windows.Forms.Button(); - dataGridViewColumnizer = new System.Windows.Forms.DataGridView(); - columnFileMask = new System.Windows.Forms.DataGridViewTextBoxColumn(); - columnColumnizer = new System.Windows.Forms.DataGridViewComboBoxColumn(); - tabPageHighlightMask = new System.Windows.Forms.TabPage(); - dataGridViewHighlightMask = new System.Windows.Forms.DataGridView(); - columnFileName = new System.Windows.Forms.DataGridViewTextBoxColumn(); - columnHighlightGroup = new System.Windows.Forms.DataGridViewComboBoxColumn(); - tabPageMultiFile = new System.Windows.Forms.TabPage(); - groupBoxDefaultFileNamePattern = new System.Windows.Forms.GroupBox(); - labelMaxDays = new System.Windows.Forms.Label(); - labelPattern = new System.Windows.Forms.Label(); - upDownMultifileDays = new System.Windows.Forms.NumericUpDown(); - textBoxMultifilePattern = new System.Windows.Forms.TextBox(); - labelHintMultiFile = new System.Windows.Forms.Label(); - labelNoteMultiFile = new System.Windows.Forms.Label(); - groupBoxWhenOpeningMultiFile = new System.Windows.Forms.GroupBox(); - radioButtonAskWhatToDo = new System.Windows.Forms.RadioButton(); - radioButtonTreatAllFilesAsOneMultifile = new System.Windows.Forms.RadioButton(); - radioButtonLoadEveryFileIntoSeperatedTab = new System.Windows.Forms.RadioButton(); - tabPagePlugins = new System.Windows.Forms.TabPage(); - groupBoxPlugins = new System.Windows.Forms.GroupBox(); - listBoxPlugin = new System.Windows.Forms.ListBox(); - groupBoxSettings = new System.Windows.Forms.GroupBox(); - panelPlugin = new System.Windows.Forms.Panel(); - buttonConfigPlugin = new System.Windows.Forms.Button(); - tabPageSessions = new System.Windows.Forms.TabPage(); - checkBoxPortableMode = new System.Windows.Forms.CheckBox(); - checkBoxSaveFilter = new System.Windows.Forms.CheckBox(); - groupBoxPersistantFileLocation = new System.Windows.Forms.GroupBox(); - labelSessionSaveOwnDir = new System.Windows.Forms.Label(); - buttonSessionSaveDir = new System.Windows.Forms.Button(); - radioButtonSessionSaveOwn = new System.Windows.Forms.RadioButton(); - radioButtonsessionSaveDocuments = new System.Windows.Forms.RadioButton(); - radioButtonSessionSameDir = new System.Windows.Forms.RadioButton(); - radioButtonSessionApplicationStartupDir = new System.Windows.Forms.RadioButton(); - checkBoxSaveSessions = new System.Windows.Forms.CheckBox(); - tabPageMemory = new System.Windows.Forms.TabPage(); - groupBoxCPUAndStuff = new System.Windows.Forms.GroupBox(); - checkBoxLegacyReader = new System.Windows.Forms.CheckBox(); - checkBoxMultiThread = new System.Windows.Forms.CheckBox(); - labelFilePollingInterval = new System.Windows.Forms.Label(); - upDownPollingInterval = new System.Windows.Forms.NumericUpDown(); - groupBoxLineBufferUsage = new System.Windows.Forms.GroupBox(); - labelInfo = new System.Windows.Forms.Label(); - labelNumberOfBlocks = new System.Windows.Forms.Label(); - upDownLinesPerBlock = new System.Windows.Forms.NumericUpDown(); - upDownBlockCount = new System.Windows.Forms.NumericUpDown(); - labelLinesPerBlock = new System.Windows.Forms.Label(); - buttonCancel = new System.Windows.Forms.Button(); - buttonOk = new System.Windows.Forms.Button(); - helpProvider = new System.Windows.Forms.HelpProvider(); - toolTip = new System.Windows.Forms.ToolTip(components); - buttonExport = new System.Windows.Forms.Button(); - buttonImport = new System.Windows.Forms.Button(); - dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); - dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); - tabControlSettings.SuspendLayout(); - tabPageViewSettings.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)upDownMaximumLineLength).BeginInit(); - ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntriesDisplayed).BeginInit(); - ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntries).BeginInit(); - groupBoxMisc.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)cpDownColumnWidth).BeginInit(); - groupBoxDefaults.SuspendLayout(); - groupBoxFont.SuspendLayout(); - tabPageTimeStampFeatures.SuspendLayout(); - groupBoxTimeSpreadDisplay.SuspendLayout(); - groupBoxDisplayMode.SuspendLayout(); - groupBoxTimeStampNavigationControl.SuspendLayout(); - groupBoxMouseDragDefaults.SuspendLayout(); - tabPageExternalTools.SuspendLayout(); - groupBoxToolSettings.SuspendLayout(); - tabPageColumnizers.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridViewColumnizer).BeginInit(); - tabPageHighlightMask.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridViewHighlightMask).BeginInit(); - tabPageMultiFile.SuspendLayout(); - groupBoxDefaultFileNamePattern.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)upDownMultifileDays).BeginInit(); - groupBoxWhenOpeningMultiFile.SuspendLayout(); - tabPagePlugins.SuspendLayout(); - groupBoxPlugins.SuspendLayout(); - groupBoxSettings.SuspendLayout(); - panelPlugin.SuspendLayout(); - tabPageSessions.SuspendLayout(); - groupBoxPersistantFileLocation.SuspendLayout(); - tabPageMemory.SuspendLayout(); - groupBoxCPUAndStuff.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)upDownPollingInterval).BeginInit(); - groupBoxLineBufferUsage.SuspendLayout(); - ((System.ComponentModel.ISupportInitialize)upDownLinesPerBlock).BeginInit(); - ((System.ComponentModel.ISupportInitialize)upDownBlockCount).BeginInit(); - SuspendLayout(); - // - // tabControlSettings - // - tabControlSettings.Controls.Add(tabPageViewSettings); - tabControlSettings.Controls.Add(tabPageTimeStampFeatures); - tabControlSettings.Controls.Add(tabPageExternalTools); - tabControlSettings.Controls.Add(tabPageColumnizers); - tabControlSettings.Controls.Add(tabPageHighlightMask); - tabControlSettings.Controls.Add(tabPageMultiFile); - tabControlSettings.Controls.Add(tabPagePlugins); - tabControlSettings.Controls.Add(tabPageSessions); - tabControlSettings.Controls.Add(tabPageMemory); - tabControlSettings.Location = new System.Drawing.Point(2, 3); - tabControlSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabControlSettings.Name = "tabControlSettings"; - tabControlSettings.SelectedIndex = 0; - tabControlSettings.Size = new System.Drawing.Size(950, 468); - tabControlSettings.TabIndex = 0; - // - // tabPageViewSettings - // - tabPageViewSettings.Controls.Add(labelWarningMaximumLineLenght); - tabPageViewSettings.Controls.Add(upDownMaximumLineLength); - tabPageViewSettings.Controls.Add(labelMaximumLineLength); - tabPageViewSettings.Controls.Add(upDownMaximumFilterEntriesDisplayed); - tabPageViewSettings.Controls.Add(labelMaximumFilterEntriesDisplayed); - tabPageViewSettings.Controls.Add(upDownMaximumFilterEntries); - tabPageViewSettings.Controls.Add(labelMaximumFilterEntries); - tabPageViewSettings.Controls.Add(labelDefaultEncoding); - tabPageViewSettings.Controls.Add(comboBoxEncoding); - tabPageViewSettings.Controls.Add(groupBoxMisc); - tabPageViewSettings.Controls.Add(groupBoxDefaults); - tabPageViewSettings.Controls.Add(groupBoxFont); - tabPageViewSettings.Location = new System.Drawing.Point(4, 24); - tabPageViewSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageViewSettings.Name = "tabPageViewSettings"; - tabPageViewSettings.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageViewSettings.Size = new System.Drawing.Size(942, 440); - tabPageViewSettings.TabIndex = 0; - tabPageViewSettings.Text = "View settings"; - tabPageViewSettings.UseVisualStyleBackColor = true; - // - // labelWarningMaximumLineLenght - // - labelWarningMaximumLineLenght.AutoSize = true; - labelWarningMaximumLineLenght.Location = new System.Drawing.Point(446, 118); - labelWarningMaximumLineLenght.Name = "labelWarningMaximumLineLenght"; - labelWarningMaximumLineLenght.Size = new System.Drawing.Size(482, 15); - labelWarningMaximumLineLenght.TabIndex = 16; - labelWarningMaximumLineLenght.Text = "! Changing the Maximum Line Length can impact performance and is not recommended !"; - // - // upDownMaximumLineLength - // - upDownMaximumLineLength.Location = new System.Drawing.Point(762, 138); - upDownMaximumLineLength.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - upDownMaximumLineLength.Maximum = new decimal(new int[] { 1000000, 0, 0, 0 }); - upDownMaximumLineLength.Minimum = new decimal(new int[] { 20000, 0, 0, 0 }); - upDownMaximumLineLength.Name = "upDownMaximumLineLength"; - upDownMaximumLineLength.Size = new System.Drawing.Size(106, 23); - upDownMaximumLineLength.TabIndex = 15; - upDownMaximumLineLength.Value = new decimal(new int[] { 20000, 0, 0, 0 }); - // - // labelMaximumLineLength - // - labelMaximumLineLength.AutoSize = true; - labelMaximumLineLength.Location = new System.Drawing.Point(467, 140); - labelMaximumLineLength.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelMaximumLineLength.Name = "labelMaximumLineLength"; - labelMaximumLineLength.Size = new System.Drawing.Size(217, 15); - labelMaximumLineLength.TabIndex = 14; - labelMaximumLineLength.Text = "Maximum Line Length (restart required)"; - // - // upDownMaximumFilterEntriesDisplayed - // - upDownMaximumFilterEntriesDisplayed.Location = new System.Drawing.Point(762, 86); - upDownMaximumFilterEntriesDisplayed.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - upDownMaximumFilterEntriesDisplayed.Maximum = new decimal(new int[] { 30, 0, 0, 0 }); - upDownMaximumFilterEntriesDisplayed.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); - upDownMaximumFilterEntriesDisplayed.Name = "upDownMaximumFilterEntriesDisplayed"; - upDownMaximumFilterEntriesDisplayed.Size = new System.Drawing.Size(106, 23); - upDownMaximumFilterEntriesDisplayed.TabIndex = 13; - upDownMaximumFilterEntriesDisplayed.Value = new decimal(new int[] { 20, 0, 0, 0 }); - // - // labelMaximumFilterEntriesDisplayed - // - labelMaximumFilterEntriesDisplayed.AutoSize = true; - labelMaximumFilterEntriesDisplayed.Location = new System.Drawing.Point(467, 88); - labelMaximumFilterEntriesDisplayed.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelMaximumFilterEntriesDisplayed.Name = "labelMaximumFilterEntriesDisplayed"; - labelMaximumFilterEntriesDisplayed.Size = new System.Drawing.Size(179, 15); - labelMaximumFilterEntriesDisplayed.TabIndex = 12; - labelMaximumFilterEntriesDisplayed.Text = "Maximum filter entries displayed"; - // - // upDownMaximumFilterEntries - // - upDownMaximumFilterEntries.Location = new System.Drawing.Point(762, 59); - upDownMaximumFilterEntries.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - upDownMaximumFilterEntries.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); - upDownMaximumFilterEntries.Name = "upDownMaximumFilterEntries"; - upDownMaximumFilterEntries.Size = new System.Drawing.Size(106, 23); - upDownMaximumFilterEntries.TabIndex = 11; - upDownMaximumFilterEntries.Value = new decimal(new int[] { 30, 0, 0, 0 }); - // - // labelMaximumFilterEntries - // - labelMaximumFilterEntries.AutoSize = true; - labelMaximumFilterEntries.Location = new System.Drawing.Point(467, 61); - labelMaximumFilterEntries.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelMaximumFilterEntries.Name = "labelMaximumFilterEntries"; - labelMaximumFilterEntries.Size = new System.Drawing.Size(126, 15); - labelMaximumFilterEntries.TabIndex = 10; - labelMaximumFilterEntries.Text = "Maximum filter entries"; - // - // labelDefaultEncoding - // - labelDefaultEncoding.AutoSize = true; - labelDefaultEncoding.Location = new System.Drawing.Point(467, 34); - labelDefaultEncoding.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelDefaultEncoding.Name = "labelDefaultEncoding"; - labelDefaultEncoding.Size = new System.Drawing.Size(98, 15); - labelDefaultEncoding.TabIndex = 9; - labelDefaultEncoding.Text = "Default encoding"; - // - // comboBoxEncoding - // - comboBoxEncoding.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; - comboBoxEncoding.FormattingEnabled = true; - comboBoxEncoding.Location = new System.Drawing.Point(691, 26); - comboBoxEncoding.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - comboBoxEncoding.Name = "comboBoxEncoding"; - comboBoxEncoding.Size = new System.Drawing.Size(177, 23); - comboBoxEncoding.TabIndex = 8; - toolTip.SetToolTip(comboBoxEncoding, "Encoding to be used when no BOM header and no persistence data is available."); - // - // groupBoxMisc - // - groupBoxMisc.Controls.Add(checkBoxShowErrorMessageOnlyOneInstance); - groupBoxMisc.Controls.Add(cpDownColumnWidth); - groupBoxMisc.Controls.Add(checkBoxColumnSize); - groupBoxMisc.Controls.Add(buttonTailColor); - groupBoxMisc.Controls.Add(checkBoxTailState); - groupBoxMisc.Controls.Add(checkBoxOpenLastFiles); - groupBoxMisc.Controls.Add(checkBoxSingleInstance); - groupBoxMisc.Controls.Add(checkBoxAskCloseTabs); - groupBoxMisc.Location = new System.Drawing.Point(458, 171); - groupBoxMisc.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxMisc.Name = "groupBoxMisc"; - groupBoxMisc.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxMisc.Size = new System.Drawing.Size(410, 226); - groupBoxMisc.TabIndex = 7; - groupBoxMisc.TabStop = false; - groupBoxMisc.Text = "Misc"; - // - // checkBoxShowErrorMessageOnlyOneInstance - // - checkBoxShowErrorMessageOnlyOneInstance.AutoSize = true; - checkBoxShowErrorMessageOnlyOneInstance.Location = new System.Drawing.Point(210, 66); - checkBoxShowErrorMessageOnlyOneInstance.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxShowErrorMessageOnlyOneInstance.Name = "checkBoxShowErrorMessageOnlyOneInstance"; - checkBoxShowErrorMessageOnlyOneInstance.Size = new System.Drawing.Size(137, 19); - checkBoxShowErrorMessageOnlyOneInstance.TabIndex = 7; - checkBoxShowErrorMessageOnlyOneInstance.Text = "Show Error Message?"; - checkBoxShowErrorMessageOnlyOneInstance.UseVisualStyleBackColor = true; - // - // cpDownColumnWidth - // - cpDownColumnWidth.Location = new System.Drawing.Point(304, 175); - cpDownColumnWidth.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - cpDownColumnWidth.Maximum = new decimal(new int[] { 9000, 0, 0, 0 }); - cpDownColumnWidth.Minimum = new decimal(new int[] { 300, 0, 0, 0 }); - cpDownColumnWidth.Name = "cpDownColumnWidth"; - cpDownColumnWidth.Size = new System.Drawing.Size(84, 23); - cpDownColumnWidth.TabIndex = 6; - cpDownColumnWidth.Value = new decimal(new int[] { 2000, 0, 0, 0 }); - // - // checkBoxColumnSize - // - checkBoxColumnSize.AutoSize = true; - checkBoxColumnSize.Location = new System.Drawing.Point(9, 177); - checkBoxColumnSize.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxColumnSize.Name = "checkBoxColumnSize"; - checkBoxColumnSize.Size = new System.Drawing.Size(140, 19); - checkBoxColumnSize.TabIndex = 5; - checkBoxColumnSize.Text = "Set last column width"; - checkBoxColumnSize.UseVisualStyleBackColor = true; - checkBoxColumnSize.CheckedChanged += OnChkBoxColumnSizeCheckedChanged; - // - // buttonTailColor - // - buttonTailColor.Location = new System.Drawing.Point(304, 135); - buttonTailColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonTailColor.Name = "buttonTailColor"; - buttonTailColor.Size = new System.Drawing.Size(84, 32); - buttonTailColor.TabIndex = 4; - buttonTailColor.Text = "Color..."; - buttonTailColor.UseVisualStyleBackColor = true; - buttonTailColor.Click += OnBtnTailColorClick; - // - // checkBoxTailState - // - checkBoxTailState.AutoSize = true; - checkBoxTailState.Location = new System.Drawing.Point(9, 140); - checkBoxTailState.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxTailState.Name = "checkBoxTailState"; - checkBoxTailState.Size = new System.Drawing.Size(144, 19); - checkBoxTailState.TabIndex = 3; - checkBoxTailState.Text = "Show tail state on tabs"; - checkBoxTailState.UseVisualStyleBackColor = true; - // - // checkBoxOpenLastFiles - // - checkBoxOpenLastFiles.AutoSize = true; - checkBoxOpenLastFiles.Location = new System.Drawing.Point(9, 103); - checkBoxOpenLastFiles.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxOpenLastFiles.Name = "checkBoxOpenLastFiles"; - checkBoxOpenLastFiles.Size = new System.Drawing.Size(144, 19); - checkBoxOpenLastFiles.TabIndex = 2; - checkBoxOpenLastFiles.Text = "Re-open last used files"; - checkBoxOpenLastFiles.UseVisualStyleBackColor = true; - // - // checkBoxSingleInstance - // - checkBoxSingleInstance.AutoSize = true; - checkBoxSingleInstance.Location = new System.Drawing.Point(9, 66); - checkBoxSingleInstance.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxSingleInstance.Name = "checkBoxSingleInstance"; - checkBoxSingleInstance.Size = new System.Drawing.Size(138, 19); - checkBoxSingleInstance.TabIndex = 1; - checkBoxSingleInstance.Text = "Allow only 1 Instance"; - checkBoxSingleInstance.UseVisualStyleBackColor = true; - // - // checkBoxAskCloseTabs - // - checkBoxAskCloseTabs.AutoSize = true; - checkBoxAskCloseTabs.Location = new System.Drawing.Point(9, 29); - checkBoxAskCloseTabs.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxAskCloseTabs.Name = "checkBoxAskCloseTabs"; - checkBoxAskCloseTabs.Size = new System.Drawing.Size(148, 19); - checkBoxAskCloseTabs.TabIndex = 0; - checkBoxAskCloseTabs.Text = "Ask before closing tabs"; - checkBoxAskCloseTabs.UseVisualStyleBackColor = true; - // - // groupBoxDefaults - // - groupBoxDefaults.Controls.Add(checkBoxDarkMode); - groupBoxDefaults.Controls.Add(checkBoxFollowTail); - groupBoxDefaults.Controls.Add(checkBoxColumnFinder); - groupBoxDefaults.Controls.Add(checkBoxSyncFilter); - groupBoxDefaults.Controls.Add(checkBoxFilterTail); - groupBoxDefaults.Location = new System.Drawing.Point(10, 171); - groupBoxDefaults.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxDefaults.Name = "groupBoxDefaults"; - groupBoxDefaults.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxDefaults.Size = new System.Drawing.Size(411, 226); - groupBoxDefaults.TabIndex = 6; - groupBoxDefaults.TabStop = false; - groupBoxDefaults.Text = "Defaults"; - // - // checkBoxDarkMode - // - checkBoxDarkMode.AutoSize = true; - checkBoxDarkMode.Location = new System.Drawing.Point(7, 141); - checkBoxDarkMode.Margin = new System.Windows.Forms.Padding(4); - checkBoxDarkMode.Name = "checkBoxDarkMode"; - checkBoxDarkMode.Size = new System.Drawing.Size(175, 19); - checkBoxDarkMode.TabIndex = 6; - checkBoxDarkMode.Text = "Dark Mode (restart required)"; - checkBoxDarkMode.UseVisualStyleBackColor = true; - // - // checkBoxFollowTail - // - checkBoxFollowTail.AutoSize = true; - checkBoxFollowTail.Location = new System.Drawing.Point(9, 29); - checkBoxFollowTail.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxFollowTail.Name = "checkBoxFollowTail"; - checkBoxFollowTail.Size = new System.Drawing.Size(125, 19); - checkBoxFollowTail.TabIndex = 3; - checkBoxFollowTail.Text = "Follow tail enabled"; - checkBoxFollowTail.UseVisualStyleBackColor = true; - // - // checkBoxColumnFinder - // - checkBoxColumnFinder.AutoSize = true; - checkBoxColumnFinder.Location = new System.Drawing.Point(9, 140); - checkBoxColumnFinder.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxColumnFinder.Name = "checkBoxColumnFinder"; - checkBoxColumnFinder.Size = new System.Drawing.Size(133, 19); - checkBoxColumnFinder.TabIndex = 5; - checkBoxColumnFinder.Text = "Show column finder"; - checkBoxColumnFinder.UseVisualStyleBackColor = true; - // - // checkBoxSyncFilter - // - checkBoxSyncFilter.AutoSize = true; - checkBoxSyncFilter.Location = new System.Drawing.Point(9, 103); - checkBoxSyncFilter.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxSyncFilter.Name = "checkBoxSyncFilter"; - checkBoxSyncFilter.Size = new System.Drawing.Size(141, 19); - checkBoxSyncFilter.TabIndex = 5; - checkBoxSyncFilter.Text = "Sync filter list enabled"; - checkBoxSyncFilter.UseVisualStyleBackColor = true; - // - // checkBoxFilterTail - // - checkBoxFilterTail.AutoSize = true; - checkBoxFilterTail.Location = new System.Drawing.Point(9, 66); - checkBoxFilterTail.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxFilterTail.Name = "checkBoxFilterTail"; - checkBoxFilterTail.Size = new System.Drawing.Size(116, 19); - checkBoxFilterTail.TabIndex = 4; - checkBoxFilterTail.Text = "Filter tail enabled"; - checkBoxFilterTail.UseVisualStyleBackColor = true; - // - // groupBoxFont - // - groupBoxFont.Controls.Add(buttonChangeFont); - groupBoxFont.Controls.Add(labelFont); - groupBoxFont.Location = new System.Drawing.Point(10, 9); - groupBoxFont.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxFont.Name = "groupBoxFont"; - groupBoxFont.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxFont.Size = new System.Drawing.Size(408, 128); - groupBoxFont.TabIndex = 1; - groupBoxFont.TabStop = false; - groupBoxFont.Text = "Font"; - // - // buttonChangeFont - // - buttonChangeFont.Location = new System.Drawing.Point(9, 77); - buttonChangeFont.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonChangeFont.Name = "buttonChangeFont"; - buttonChangeFont.Size = new System.Drawing.Size(112, 35); - buttonChangeFont.TabIndex = 1; - buttonChangeFont.Text = "Change..."; - buttonChangeFont.UseVisualStyleBackColor = true; - buttonChangeFont.Click += OnBtnChangeFontClick; - // - // labelFont - // - labelFont.Location = new System.Drawing.Point(9, 25); - labelFont.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelFont.Name = "labelFont"; - labelFont.Size = new System.Drawing.Size(312, 48); - labelFont.TabIndex = 0; - labelFont.Text = "Font"; - labelFont.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; - // - // tabPageTimeStampFeatures - // - tabPageTimeStampFeatures.Controls.Add(groupBoxTimeSpreadDisplay); - tabPageTimeStampFeatures.Controls.Add(groupBoxTimeStampNavigationControl); - tabPageTimeStampFeatures.Location = new System.Drawing.Point(4, 24); - tabPageTimeStampFeatures.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageTimeStampFeatures.Name = "tabPageTimeStampFeatures"; - tabPageTimeStampFeatures.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageTimeStampFeatures.Size = new System.Drawing.Size(942, 440); - tabPageTimeStampFeatures.TabIndex = 1; - tabPageTimeStampFeatures.Text = "Timestamp features"; - tabPageTimeStampFeatures.UseVisualStyleBackColor = true; - // - // groupBoxTimeSpreadDisplay - // - groupBoxTimeSpreadDisplay.Controls.Add(groupBoxDisplayMode); - groupBoxTimeSpreadDisplay.Controls.Add(checkBoxReverseAlpha); - groupBoxTimeSpreadDisplay.Controls.Add(buttonTimespreadColor); - groupBoxTimeSpreadDisplay.Controls.Add(checkBoxTimeSpread); - groupBoxTimeSpreadDisplay.Location = new System.Drawing.Point(490, 25); - groupBoxTimeSpreadDisplay.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxTimeSpreadDisplay.Name = "groupBoxTimeSpreadDisplay"; - groupBoxTimeSpreadDisplay.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxTimeSpreadDisplay.Size = new System.Drawing.Size(300, 246); - groupBoxTimeSpreadDisplay.TabIndex = 8; - groupBoxTimeSpreadDisplay.TabStop = false; - groupBoxTimeSpreadDisplay.Text = "Time spread display"; - // - // groupBoxDisplayMode - // - groupBoxDisplayMode.Controls.Add(radioButtonLineView); - groupBoxDisplayMode.Controls.Add(radioButtonTimeView); - groupBoxDisplayMode.Location = new System.Drawing.Point(22, 109); - groupBoxDisplayMode.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxDisplayMode.Name = "groupBoxDisplayMode"; - groupBoxDisplayMode.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxDisplayMode.Size = new System.Drawing.Size(188, 118); - groupBoxDisplayMode.TabIndex = 11; - groupBoxDisplayMode.TabStop = false; - groupBoxDisplayMode.Text = "Display mode"; - // - // radioButtonLineView - // - radioButtonLineView.AutoSize = true; - radioButtonLineView.Location = new System.Drawing.Point(9, 65); - radioButtonLineView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonLineView.Name = "radioButtonLineView"; - radioButtonLineView.Size = new System.Drawing.Size(74, 19); - radioButtonLineView.TabIndex = 9; - radioButtonLineView.TabStop = true; - radioButtonLineView.Text = "Line view"; - radioButtonLineView.UseVisualStyleBackColor = true; - // - // radioButtonTimeView - // - radioButtonTimeView.AutoSize = true; - radioButtonTimeView.Location = new System.Drawing.Point(9, 29); - radioButtonTimeView.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonTimeView.Name = "radioButtonTimeView"; - radioButtonTimeView.Size = new System.Drawing.Size(79, 19); - radioButtonTimeView.TabIndex = 10; - radioButtonTimeView.TabStop = true; - radioButtonTimeView.Text = "Time view"; - radioButtonTimeView.UseVisualStyleBackColor = true; - // - // checkBoxReverseAlpha - // - checkBoxReverseAlpha.AutoSize = true; - checkBoxReverseAlpha.Location = new System.Drawing.Point(22, 74); - checkBoxReverseAlpha.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxReverseAlpha.Name = "checkBoxReverseAlpha"; - checkBoxReverseAlpha.Size = new System.Drawing.Size(98, 19); - checkBoxReverseAlpha.TabIndex = 8; - checkBoxReverseAlpha.Text = "Reverse alpha"; - checkBoxReverseAlpha.UseVisualStyleBackColor = true; - // - // buttonTimespreadColor - // - buttonTimespreadColor.Location = new System.Drawing.Point(207, 32); - buttonTimespreadColor.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonTimespreadColor.Name = "buttonTimespreadColor"; - buttonTimespreadColor.Size = new System.Drawing.Size(84, 32); - buttonTimespreadColor.TabIndex = 7; - buttonTimespreadColor.Text = "Color..."; - buttonTimespreadColor.UseVisualStyleBackColor = true; - buttonTimespreadColor.Click += OnBtnTimespreadColorClick; - // - // checkBoxTimeSpread - // - checkBoxTimeSpread.AutoSize = true; - checkBoxTimeSpread.Location = new System.Drawing.Point(22, 37); - checkBoxTimeSpread.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxTimeSpread.Name = "checkBoxTimeSpread"; - checkBoxTimeSpread.Size = new System.Drawing.Size(120, 19); - checkBoxTimeSpread.TabIndex = 6; - checkBoxTimeSpread.Text = "Show time spread"; - checkBoxTimeSpread.UseVisualStyleBackColor = true; - // - // groupBoxTimeStampNavigationControl - // - groupBoxTimeStampNavigationControl.Controls.Add(checkBoxTimestamp); - groupBoxTimeStampNavigationControl.Controls.Add(groupBoxMouseDragDefaults); - groupBoxTimeStampNavigationControl.Location = new System.Drawing.Point(10, 25); - groupBoxTimeStampNavigationControl.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxTimeStampNavigationControl.Name = "groupBoxTimeStampNavigationControl"; - groupBoxTimeStampNavigationControl.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxTimeStampNavigationControl.Size = new System.Drawing.Size(450, 246); - groupBoxTimeStampNavigationControl.TabIndex = 7; - groupBoxTimeStampNavigationControl.TabStop = false; - groupBoxTimeStampNavigationControl.Text = "Timestamp navigation control"; - // - // checkBoxTimestamp - // - checkBoxTimestamp.AutoSize = true; - checkBoxTimestamp.Location = new System.Drawing.Point(27, 37); - checkBoxTimestamp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxTimestamp.Name = "checkBoxTimestamp"; - checkBoxTimestamp.Size = new System.Drawing.Size(304, 19); - checkBoxTimestamp.TabIndex = 3; - checkBoxTimestamp.Text = "Show timestamp control, if supported by columnizer"; - checkBoxTimestamp.UseVisualStyleBackColor = true; - // - // groupBoxMouseDragDefaults - // - groupBoxMouseDragDefaults.Controls.Add(radioButtonVerticalMouseDragInverted); - groupBoxMouseDragDefaults.Controls.Add(radioButtonHorizMouseDrag); - groupBoxMouseDragDefaults.Controls.Add(radioButtonVerticalMouseDrag); - groupBoxMouseDragDefaults.Location = new System.Drawing.Point(27, 80); - groupBoxMouseDragDefaults.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxMouseDragDefaults.Name = "groupBoxMouseDragDefaults"; - groupBoxMouseDragDefaults.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxMouseDragDefaults.Size = new System.Drawing.Size(186, 148); - groupBoxMouseDragDefaults.TabIndex = 5; - groupBoxMouseDragDefaults.TabStop = false; - groupBoxMouseDragDefaults.Text = "Mouse Drag Default"; - // - // radioButtonVerticalMouseDragInverted - // - radioButtonVerticalMouseDragInverted.AutoSize = true; - radioButtonVerticalMouseDragInverted.Location = new System.Drawing.Point(9, 102); - radioButtonVerticalMouseDragInverted.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonVerticalMouseDragInverted.Name = "radioButtonVerticalMouseDragInverted"; - radioButtonVerticalMouseDragInverted.Size = new System.Drawing.Size(109, 19); - radioButtonVerticalMouseDragInverted.TabIndex = 6; - radioButtonVerticalMouseDragInverted.TabStop = true; - radioButtonVerticalMouseDragInverted.Text = "Vertical Inverted"; - radioButtonVerticalMouseDragInverted.UseVisualStyleBackColor = true; - // - // radioButtonHorizMouseDrag - // - radioButtonHorizMouseDrag.AutoSize = true; - radioButtonHorizMouseDrag.Location = new System.Drawing.Point(9, 29); - radioButtonHorizMouseDrag.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonHorizMouseDrag.Name = "radioButtonHorizMouseDrag"; - radioButtonHorizMouseDrag.Size = new System.Drawing.Size(80, 19); - radioButtonHorizMouseDrag.TabIndex = 5; - radioButtonHorizMouseDrag.TabStop = true; - radioButtonHorizMouseDrag.Text = "Horizontal"; - radioButtonHorizMouseDrag.UseVisualStyleBackColor = true; - // - // radioButtonVerticalMouseDrag - // - radioButtonVerticalMouseDrag.AutoSize = true; - radioButtonVerticalMouseDrag.Location = new System.Drawing.Point(9, 65); - radioButtonVerticalMouseDrag.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonVerticalMouseDrag.Name = "radioButtonVerticalMouseDrag"; - radioButtonVerticalMouseDrag.Size = new System.Drawing.Size(63, 19); - radioButtonVerticalMouseDrag.TabIndex = 4; - radioButtonVerticalMouseDrag.TabStop = true; - radioButtonVerticalMouseDrag.Text = "Vertical"; - radioButtonVerticalMouseDrag.UseVisualStyleBackColor = true; - // - // tabPageExternalTools - // - tabPageExternalTools.Controls.Add(labelToolsDescription); - tabPageExternalTools.Controls.Add(buttonToolDelete); - tabPageExternalTools.Controls.Add(buttonToolAdd); - tabPageExternalTools.Controls.Add(buttonToolDown); - tabPageExternalTools.Controls.Add(buttonToolUp); - tabPageExternalTools.Controls.Add(listBoxTools); - tabPageExternalTools.Controls.Add(groupBoxToolSettings); - tabPageExternalTools.Location = new System.Drawing.Point(4, 24); - tabPageExternalTools.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageExternalTools.Name = "tabPageExternalTools"; - tabPageExternalTools.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageExternalTools.Size = new System.Drawing.Size(942, 440); - tabPageExternalTools.TabIndex = 2; - tabPageExternalTools.Text = "External Tools"; - tabPageExternalTools.UseVisualStyleBackColor = true; - // - // labelToolsDescription - // - labelToolsDescription.Location = new System.Drawing.Point(546, 102); - labelToolsDescription.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelToolsDescription.Name = "labelToolsDescription"; - labelToolsDescription.Size = new System.Drawing.Size(376, 80); - labelToolsDescription.TabIndex = 6; - labelToolsDescription.Text = "You can configure as many tools as you want. \r\nChecked tools will appear in the icon bar. All other tools are available in the tools menu."; - // - // buttonToolDelete - // - buttonToolDelete.Location = new System.Drawing.Point(550, 14); - buttonToolDelete.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonToolDelete.Name = "buttonToolDelete"; - buttonToolDelete.Size = new System.Drawing.Size(112, 35); - buttonToolDelete.TabIndex = 2; - buttonToolDelete.Text = "Remove"; - buttonToolDelete.UseVisualStyleBackColor = true; - buttonToolDelete.Click += OnToolDeleteButtonClick; - // - // buttonToolAdd - // - buttonToolAdd.Location = new System.Drawing.Point(429, 14); - buttonToolAdd.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonToolAdd.Name = "buttonToolAdd"; - buttonToolAdd.Size = new System.Drawing.Size(112, 35); - buttonToolAdd.TabIndex = 1; - buttonToolAdd.Text = "Add new"; - buttonToolAdd.UseVisualStyleBackColor = true; - buttonToolAdd.Click += OnBtnToolAddClick; - // - // buttonToolDown - // - buttonToolDown.Location = new System.Drawing.Point(429, 146); - buttonToolDown.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonToolDown.Name = "buttonToolDown"; - buttonToolDown.Size = new System.Drawing.Size(64, 35); - buttonToolDown.TabIndex = 4; - buttonToolDown.Text = "Down"; - buttonToolDown.UseVisualStyleBackColor = true; - buttonToolDown.Click += OnBtnToolDownClick; - // - // buttonToolUp - // - buttonToolUp.Location = new System.Drawing.Point(429, 102); - buttonToolUp.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonToolUp.Name = "buttonToolUp"; - buttonToolUp.Size = new System.Drawing.Size(64, 35); - buttonToolUp.TabIndex = 3; - buttonToolUp.Text = "Up"; - buttonToolUp.UseVisualStyleBackColor = true; - buttonToolUp.Click += OnBtnToolUpClick; - // - // listBoxTools - // - listBoxTools.FormattingEnabled = true; - listBoxTools.Location = new System.Drawing.Point(10, 14); - listBoxTools.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - listBoxTools.Name = "listBoxTools"; - listBoxTools.Size = new System.Drawing.Size(406, 148); - listBoxTools.TabIndex = 0; - listBoxTools.SelectedIndexChanged += OnListBoxToolSelectedIndexChanged; - // - // groupBoxToolSettings - // - groupBoxToolSettings.Controls.Add(labelWorkingDir); - groupBoxToolSettings.Controls.Add(buttonWorkingDir); - groupBoxToolSettings.Controls.Add(textBoxWorkingDir); - groupBoxToolSettings.Controls.Add(buttonIcon); - groupBoxToolSettings.Controls.Add(labelToolName); - groupBoxToolSettings.Controls.Add(labelToolColumnizerForOutput); - groupBoxToolSettings.Controls.Add(comboBoxColumnizer); - groupBoxToolSettings.Controls.Add(textBoxToolName); - groupBoxToolSettings.Controls.Add(checkBoxSysout); - groupBoxToolSettings.Controls.Add(buttonArguments); - groupBoxToolSettings.Controls.Add(labelTool); - groupBoxToolSettings.Controls.Add(buttonTool); - groupBoxToolSettings.Controls.Add(textBoxTool); - groupBoxToolSettings.Controls.Add(labelArguments); - groupBoxToolSettings.Controls.Add(textBoxArguments); - groupBoxToolSettings.Location = new System.Drawing.Point(10, 191); - groupBoxToolSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxToolSettings.Name = "groupBoxToolSettings"; - groupBoxToolSettings.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxToolSettings.Size = new System.Drawing.Size(912, 228); - groupBoxToolSettings.TabIndex = 0; - groupBoxToolSettings.TabStop = false; - groupBoxToolSettings.Text = "Tool settings"; - // - // labelWorkingDir - // - labelWorkingDir.AutoSize = true; - labelWorkingDir.Location = new System.Drawing.Point(474, 86); - labelWorkingDir.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelWorkingDir.Name = "labelWorkingDir"; - labelWorkingDir.Size = new System.Drawing.Size(72, 15); - labelWorkingDir.TabIndex = 11; - labelWorkingDir.Text = "Working dir:"; - // - // buttonWorkingDir - // - buttonWorkingDir.Location = new System.Drawing.Point(856, 80); - buttonWorkingDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonWorkingDir.Name = "buttonWorkingDir"; - buttonWorkingDir.Size = new System.Drawing.Size(45, 31); - buttonWorkingDir.TabIndex = 10; - buttonWorkingDir.Text = "..."; - buttonWorkingDir.UseVisualStyleBackColor = true; - buttonWorkingDir.Click += OnBtnWorkingDirClick; - // - // textBoxWorkingDir - // - textBoxWorkingDir.Location = new System.Drawing.Point(576, 82); - textBoxWorkingDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - textBoxWorkingDir.Name = "textBoxWorkingDir"; - textBoxWorkingDir.Size = new System.Drawing.Size(270, 23); - textBoxWorkingDir.TabIndex = 9; - // - // buttonIcon - // - buttonIcon.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; - buttonIcon.Location = new System.Drawing.Point(418, 26); - buttonIcon.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonIcon.Name = "buttonIcon"; - buttonIcon.Size = new System.Drawing.Size(112, 35); - buttonIcon.TabIndex = 1; - buttonIcon.Text = " Icon..."; - buttonIcon.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText; - buttonIcon.UseVisualStyleBackColor = true; - buttonIcon.Click += OnBtnIconClick; - // - // labelToolName - // - labelToolName.AutoSize = true; - labelToolName.Location = new System.Drawing.Point(9, 34); - labelToolName.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelToolName.Name = "labelToolName"; - labelToolName.Size = new System.Drawing.Size(42, 15); - labelToolName.TabIndex = 8; - labelToolName.Text = "Name:"; - // - // labelToolColumnizerForOutput - // - labelToolColumnizerForOutput.AutoSize = true; - labelToolColumnizerForOutput.Location = new System.Drawing.Point(404, 185); - labelToolColumnizerForOutput.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelToolColumnizerForOutput.Name = "labelToolColumnizerForOutput"; - labelToolColumnizerForOutput.Size = new System.Drawing.Size(128, 15); - labelToolColumnizerForOutput.TabIndex = 6; - labelToolColumnizerForOutput.Text = "Columnizer for output:"; - // - // comboBoxColumnizer - // - comboBoxColumnizer.FormattingEnabled = true; - comboBoxColumnizer.Location = new System.Drawing.Point(576, 180); - comboBoxColumnizer.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - comboBoxColumnizer.Name = "comboBoxColumnizer"; - comboBoxColumnizer.Size = new System.Drawing.Size(270, 23); - comboBoxColumnizer.TabIndex = 7; - // - // textBoxToolName - // - textBoxToolName.Location = new System.Drawing.Point(108, 29); - textBoxToolName.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - textBoxToolName.Name = "textBoxToolName"; - textBoxToolName.Size = new System.Drawing.Size(298, 23); - textBoxToolName.TabIndex = 0; - // - // checkBoxSysout - // - checkBoxSysout.AutoSize = true; - checkBoxSysout.Location = new System.Drawing.Point(108, 183); - checkBoxSysout.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxSysout.Name = "checkBoxSysout"; - checkBoxSysout.Size = new System.Drawing.Size(120, 19); - checkBoxSysout.TabIndex = 6; - checkBoxSysout.Text = "Pipe sysout to tab"; - checkBoxSysout.UseVisualStyleBackColor = true; - checkBoxSysout.CheckedChanged += OnChkBoxSysoutCheckedChanged; - // - // buttonArguments - // - buttonArguments.Location = new System.Drawing.Point(856, 128); - buttonArguments.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonArguments.Name = "buttonArguments"; - buttonArguments.Size = new System.Drawing.Size(46, 32); - buttonArguments.TabIndex = 5; - buttonArguments.Text = "..."; - buttonArguments.UseVisualStyleBackColor = true; - buttonArguments.Click += OnBtnArgClick; - // - // labelTool - // - labelTool.AutoSize = true; - labelTool.Location = new System.Drawing.Point(9, 86); - labelTool.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelTool.Name = "labelTool"; - labelTool.Size = new System.Drawing.Size(56, 15); - labelTool.TabIndex = 4; - labelTool.Text = "Program:"; - // - // buttonTool - // - buttonTool.Location = new System.Drawing.Point(418, 78); - buttonTool.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonTool.Name = "buttonTool"; - buttonTool.Size = new System.Drawing.Size(45, 31); - buttonTool.TabIndex = 3; - buttonTool.Text = "..."; - buttonTool.UseVisualStyleBackColor = true; - buttonTool.Click += OnBtnToolClick; - // - // textBoxTool - // - textBoxTool.Location = new System.Drawing.Point(108, 80); - textBoxTool.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - textBoxTool.Name = "textBoxTool"; - textBoxTool.Size = new System.Drawing.Size(298, 23); - textBoxTool.TabIndex = 2; - // - // labelArguments - // - labelArguments.AutoSize = true; - labelArguments.Location = new System.Drawing.Point(9, 134); - labelArguments.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelArguments.Name = "labelArguments"; - labelArguments.Size = new System.Drawing.Size(69, 15); - labelArguments.TabIndex = 1; - labelArguments.Text = "Arguments:"; - // - // textBoxArguments - // - textBoxArguments.Location = new System.Drawing.Point(108, 129); - textBoxArguments.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - textBoxArguments.Name = "textBoxArguments"; - textBoxArguments.Size = new System.Drawing.Size(738, 23); - textBoxArguments.TabIndex = 4; - // - // tabPageColumnizers - // - tabPageColumnizers.Controls.Add(checkBoxAutoPick); - tabPageColumnizers.Controls.Add(checkBoxMaskPrio); - tabPageColumnizers.Controls.Add(buttonDelete); - tabPageColumnizers.Controls.Add(dataGridViewColumnizer); - tabPageColumnizers.Location = new System.Drawing.Point(4, 24); - tabPageColumnizers.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageColumnizers.Name = "tabPageColumnizers"; - tabPageColumnizers.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageColumnizers.Size = new System.Drawing.Size(942, 440); - tabPageColumnizers.TabIndex = 3; - tabPageColumnizers.Text = "Columnizers"; - tabPageColumnizers.UseVisualStyleBackColor = true; - // - // checkBoxAutoPick - // - checkBoxAutoPick.AutoSize = true; - checkBoxAutoPick.Checked = true; - checkBoxAutoPick.CheckState = System.Windows.Forms.CheckState.Checked; - checkBoxAutoPick.Location = new System.Drawing.Point(530, 386); - checkBoxAutoPick.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxAutoPick.Name = "checkBoxAutoPick"; - checkBoxAutoPick.Size = new System.Drawing.Size(192, 19); - checkBoxAutoPick.TabIndex = 5; - checkBoxAutoPick.Text = "Automatically pick for new files"; - checkBoxAutoPick.UseVisualStyleBackColor = true; - // - // checkBoxMaskPrio - // - checkBoxMaskPrio.AutoSize = true; - checkBoxMaskPrio.Location = new System.Drawing.Point(213, 388); - checkBoxMaskPrio.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxMaskPrio.Name = "checkBoxMaskPrio"; - checkBoxMaskPrio.Size = new System.Drawing.Size(192, 19); - checkBoxMaskPrio.TabIndex = 4; - checkBoxMaskPrio.Text = "Mask has priority before history"; - checkBoxMaskPrio.UseVisualStyleBackColor = true; - // - // buttonDelete - // - buttonDelete.Location = new System.Drawing.Point(12, 380); - buttonDelete.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonDelete.Name = "buttonDelete"; - buttonDelete.Size = new System.Drawing.Size(112, 35); - buttonDelete.TabIndex = 3; - buttonDelete.Text = "Delete"; - buttonDelete.UseVisualStyleBackColor = true; - buttonDelete.Click += OnBtnDeleteClick; - // - // dataGridViewColumnizer - // - dataGridViewColumnizer.AllowUserToResizeRows = false; - dataGridViewColumnizer.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; - dataGridViewColumnizer.BackgroundColor = System.Drawing.SystemColors.ControlLight; - dataGridViewColumnizer.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridViewColumnizer.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { columnFileMask, columnColumnizer }); - dataGridViewColumnizer.Dock = System.Windows.Forms.DockStyle.Top; - dataGridViewColumnizer.EditMode = System.Windows.Forms.DataGridViewEditMode.EditOnEnter; - dataGridViewColumnizer.Location = new System.Drawing.Point(4, 5); - dataGridViewColumnizer.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - dataGridViewColumnizer.Name = "dataGridViewColumnizer"; - dataGridViewColumnizer.RowHeadersWidth = 62; - dataGridViewColumnizer.Size = new System.Drawing.Size(934, 365); - dataGridViewColumnizer.TabIndex = 2; - dataGridViewColumnizer.RowsAdded += OnDataGridViewColumnizerRowsAdded; - // - // columnFileMask - // - columnFileMask.HeaderText = "File name mask (RegEx)"; - columnFileMask.MinimumWidth = 40; - columnFileMask.Name = "columnFileMask"; - // - // columnColumnizer - // - columnColumnizer.HeaderText = "Columnizer"; - columnColumnizer.MinimumWidth = 230; - columnColumnizer.Name = "columnColumnizer"; - // - // tabPageHighlightMask - // - tabPageHighlightMask.Controls.Add(dataGridViewHighlightMask); - tabPageHighlightMask.Location = new System.Drawing.Point(4, 24); - tabPageHighlightMask.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageHighlightMask.Name = "tabPageHighlightMask"; - tabPageHighlightMask.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageHighlightMask.Size = new System.Drawing.Size(942, 440); - tabPageHighlightMask.TabIndex = 8; - tabPageHighlightMask.Text = "Highlight"; - tabPageHighlightMask.UseVisualStyleBackColor = true; - // - // dataGridViewHighlightMask - // - dataGridViewHighlightMask.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill; - dataGridViewHighlightMask.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; - dataGridViewHighlightMask.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { columnFileName, columnHighlightGroup }); - dataGridViewHighlightMask.Dock = System.Windows.Forms.DockStyle.Fill; - dataGridViewHighlightMask.Location = new System.Drawing.Point(4, 5); - dataGridViewHighlightMask.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - dataGridViewHighlightMask.Name = "dataGridViewHighlightMask"; - dataGridViewHighlightMask.RowHeadersWidth = 62; - dataGridViewHighlightMask.Size = new System.Drawing.Size(934, 430); - dataGridViewHighlightMask.TabIndex = 0; - // - // columnFileName - // - columnFileName.HeaderText = "File name mask (RegEx)"; - columnFileName.MinimumWidth = 40; - columnFileName.Name = "columnFileName"; - // - // columnHighlightGroup - // - columnHighlightGroup.HeaderText = "Highlight group"; - columnHighlightGroup.MinimumWidth = 50; - columnHighlightGroup.Name = "columnHighlightGroup"; - // - // tabPageMultiFile - // - tabPageMultiFile.Controls.Add(groupBoxDefaultFileNamePattern); - tabPageMultiFile.Controls.Add(labelHintMultiFile); - tabPageMultiFile.Controls.Add(labelNoteMultiFile); - tabPageMultiFile.Controls.Add(groupBoxWhenOpeningMultiFile); - tabPageMultiFile.Location = new System.Drawing.Point(4, 24); - tabPageMultiFile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageMultiFile.Name = "tabPageMultiFile"; - tabPageMultiFile.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageMultiFile.Size = new System.Drawing.Size(942, 440); - tabPageMultiFile.TabIndex = 4; - tabPageMultiFile.Text = "MultiFile"; - tabPageMultiFile.UseVisualStyleBackColor = true; - // - // groupBoxDefaultFileNamePattern - // - groupBoxDefaultFileNamePattern.Controls.Add(labelMaxDays); - groupBoxDefaultFileNamePattern.Controls.Add(labelPattern); - groupBoxDefaultFileNamePattern.Controls.Add(upDownMultifileDays); - groupBoxDefaultFileNamePattern.Controls.Add(textBoxMultifilePattern); - groupBoxDefaultFileNamePattern.Location = new System.Drawing.Point(364, 28); - groupBoxDefaultFileNamePattern.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxDefaultFileNamePattern.Name = "groupBoxDefaultFileNamePattern"; - groupBoxDefaultFileNamePattern.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxDefaultFileNamePattern.Size = new System.Drawing.Size(436, 154); - groupBoxDefaultFileNamePattern.TabIndex = 3; - groupBoxDefaultFileNamePattern.TabStop = false; - groupBoxDefaultFileNamePattern.Text = "Default filename pattern"; - // - // labelMaxDays - // - labelMaxDays.AutoSize = true; - labelMaxDays.Location = new System.Drawing.Point(10, 75); - labelMaxDays.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelMaxDays.Name = "labelMaxDays"; - labelMaxDays.Size = new System.Drawing.Size(59, 15); - labelMaxDays.TabIndex = 3; - labelMaxDays.Text = "Max days:"; - // - // labelPattern - // - labelPattern.AutoSize = true; - labelPattern.Location = new System.Drawing.Point(10, 37); - labelPattern.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelPattern.Name = "labelPattern"; - labelPattern.Size = new System.Drawing.Size(48, 15); - labelPattern.TabIndex = 2; - labelPattern.Text = "Pattern:"; - // - // upDownMultifileDays - // - upDownMultifileDays.Location = new System.Drawing.Point(102, 72); - upDownMultifileDays.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - upDownMultifileDays.Maximum = new decimal(new int[] { 40, 0, 0, 0 }); - upDownMultifileDays.Name = "upDownMultifileDays"; - helpProvider.SetShowHelp(upDownMultifileDays, false); - upDownMultifileDays.Size = new System.Drawing.Size(92, 23); - upDownMultifileDays.TabIndex = 1; - upDownMultifileDays.Value = new decimal(new int[] { 1, 0, 0, 0 }); - // - // textBoxMultifilePattern - // - textBoxMultifilePattern.Location = new System.Drawing.Point(102, 32); - textBoxMultifilePattern.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - textBoxMultifilePattern.Name = "textBoxMultifilePattern"; - textBoxMultifilePattern.Size = new System.Drawing.Size(278, 23); - textBoxMultifilePattern.TabIndex = 0; - textBoxMultifilePattern.TextChanged += OnMultiFilePatternTextChanged; - // - // labelHintMultiFile - // - labelHintMultiFile.Location = new System.Drawing.Point(6, 203); - labelHintMultiFile.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelHintMultiFile.Name = "labelHintMultiFile"; - labelHintMultiFile.Size = new System.Drawing.Size(304, 111); - labelHintMultiFile.TabIndex = 2; - labelHintMultiFile.Text = "Hint: Pressing the Shift key while dropping files onto LogExpert will switch the behaviour from single to multi and vice versa."; - // - // labelNoteMultiFile - // - labelNoteMultiFile.Location = new System.Drawing.Point(6, 314); - labelNoteMultiFile.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelNoteMultiFile.Name = "labelNoteMultiFile"; - labelNoteMultiFile.Size = new System.Drawing.Size(705, 82); - labelNoteMultiFile.TabIndex = 1; - labelNoteMultiFile.Text = resources.GetString("labelNoteMultiFile.Text"); - // - // groupBoxWhenOpeningMultiFile - // - groupBoxWhenOpeningMultiFile.Controls.Add(radioButtonAskWhatToDo); - groupBoxWhenOpeningMultiFile.Controls.Add(radioButtonTreatAllFilesAsOneMultifile); - groupBoxWhenOpeningMultiFile.Controls.Add(radioButtonLoadEveryFileIntoSeperatedTab); - groupBoxWhenOpeningMultiFile.Location = new System.Drawing.Point(10, 28); - groupBoxWhenOpeningMultiFile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxWhenOpeningMultiFile.Name = "groupBoxWhenOpeningMultiFile"; - groupBoxWhenOpeningMultiFile.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxWhenOpeningMultiFile.Size = new System.Drawing.Size(300, 154); - groupBoxWhenOpeningMultiFile.TabIndex = 0; - groupBoxWhenOpeningMultiFile.TabStop = false; - groupBoxWhenOpeningMultiFile.Text = "When opening multiple files..."; - // - // radioButtonAskWhatToDo - // - radioButtonAskWhatToDo.AutoSize = true; - radioButtonAskWhatToDo.Location = new System.Drawing.Point(10, 105); - radioButtonAskWhatToDo.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonAskWhatToDo.Name = "radioButtonAskWhatToDo"; - radioButtonAskWhatToDo.Size = new System.Drawing.Size(104, 19); - radioButtonAskWhatToDo.TabIndex = 2; - radioButtonAskWhatToDo.TabStop = true; - radioButtonAskWhatToDo.Text = "Ask what to do"; - radioButtonAskWhatToDo.UseVisualStyleBackColor = true; - // - // radioButtonTreatAllFilesAsOneMultifile - // - radioButtonTreatAllFilesAsOneMultifile.AutoSize = true; - radioButtonTreatAllFilesAsOneMultifile.Location = new System.Drawing.Point(10, 68); - radioButtonTreatAllFilesAsOneMultifile.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonTreatAllFilesAsOneMultifile.Name = "radioButtonTreatAllFilesAsOneMultifile"; - radioButtonTreatAllFilesAsOneMultifile.Size = new System.Drawing.Size(182, 19); - radioButtonTreatAllFilesAsOneMultifile.TabIndex = 1; - radioButtonTreatAllFilesAsOneMultifile.TabStop = true; - radioButtonTreatAllFilesAsOneMultifile.Text = "Treat all files as one 'MultiFile'"; - radioButtonTreatAllFilesAsOneMultifile.UseVisualStyleBackColor = true; - // - // radioButtonLoadEveryFileIntoSeperatedTab - // - radioButtonLoadEveryFileIntoSeperatedTab.AutoSize = true; - radioButtonLoadEveryFileIntoSeperatedTab.Location = new System.Drawing.Point(10, 31); - radioButtonLoadEveryFileIntoSeperatedTab.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonLoadEveryFileIntoSeperatedTab.Name = "radioButtonLoadEveryFileIntoSeperatedTab"; - radioButtonLoadEveryFileIntoSeperatedTab.Size = new System.Drawing.Size(201, 19); - radioButtonLoadEveryFileIntoSeperatedTab.TabIndex = 0; - radioButtonLoadEveryFileIntoSeperatedTab.TabStop = true; - radioButtonLoadEveryFileIntoSeperatedTab.Text = "Load every file into a separate tab"; - radioButtonLoadEveryFileIntoSeperatedTab.UseVisualStyleBackColor = true; - // - // tabPagePlugins - // - tabPagePlugins.Controls.Add(groupBoxPlugins); - tabPagePlugins.Controls.Add(groupBoxSettings); - tabPagePlugins.Location = new System.Drawing.Point(4, 24); - tabPagePlugins.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPagePlugins.Name = "tabPagePlugins"; - tabPagePlugins.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPagePlugins.Size = new System.Drawing.Size(942, 440); - tabPagePlugins.TabIndex = 5; - tabPagePlugins.Text = "Plugins"; - tabPagePlugins.UseVisualStyleBackColor = true; - // - // groupBoxPlugins - // - groupBoxPlugins.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - groupBoxPlugins.Controls.Add(listBoxPlugin); - groupBoxPlugins.Location = new System.Drawing.Point(10, 23); - groupBoxPlugins.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxPlugins.Name = "groupBoxPlugins"; - groupBoxPlugins.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxPlugins.Size = new System.Drawing.Size(342, 400); - groupBoxPlugins.TabIndex = 3; - groupBoxPlugins.TabStop = false; - groupBoxPlugins.Text = "Plugins"; - // - // listBoxPlugin - // - listBoxPlugin.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - listBoxPlugin.DisplayMember = "Text"; - listBoxPlugin.FormattingEnabled = true; - listBoxPlugin.ItemHeight = 15; - listBoxPlugin.Location = new System.Drawing.Point(9, 29); - listBoxPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - listBoxPlugin.Name = "listBoxPlugin"; - listBoxPlugin.Size = new System.Drawing.Size(322, 349); - listBoxPlugin.TabIndex = 0; - listBoxPlugin.ValueMember = "Text"; - listBoxPlugin.SelectedIndexChanged += OnListBoxPluginSelectedIndexChanged; - // - // groupBoxSettings - // - groupBoxSettings.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - groupBoxSettings.Controls.Add(panelPlugin); - groupBoxSettings.Location = new System.Drawing.Point(362, 23); - groupBoxSettings.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxSettings.Name = "groupBoxSettings"; - groupBoxSettings.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxSettings.Size = new System.Drawing.Size(567, 400); - groupBoxSettings.TabIndex = 2; - groupBoxSettings.TabStop = false; - groupBoxSettings.Text = "Settings"; - // - // panelPlugin - // - panelPlugin.Anchor = System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left | System.Windows.Forms.AnchorStyles.Right; - panelPlugin.AutoScroll = true; - panelPlugin.Controls.Add(buttonConfigPlugin); - panelPlugin.Location = new System.Drawing.Point(9, 29); - panelPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - panelPlugin.Name = "panelPlugin"; - panelPlugin.Size = new System.Drawing.Size(549, 362); - panelPlugin.TabIndex = 1; - // - // buttonConfigPlugin - // - buttonConfigPlugin.Location = new System.Drawing.Point(164, 163); - buttonConfigPlugin.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonConfigPlugin.Name = "buttonConfigPlugin"; - buttonConfigPlugin.Size = new System.Drawing.Size(170, 35); - buttonConfigPlugin.TabIndex = 0; - buttonConfigPlugin.Text = "Configure..."; - buttonConfigPlugin.UseVisualStyleBackColor = true; - buttonConfigPlugin.Click += OnBtnConfigPluginClick; - // - // tabPageSessions - // - tabPageSessions.Controls.Add(checkBoxPortableMode); - tabPageSessions.Controls.Add(checkBoxSaveFilter); - tabPageSessions.Controls.Add(groupBoxPersistantFileLocation); - tabPageSessions.Controls.Add(checkBoxSaveSessions); - tabPageSessions.Location = new System.Drawing.Point(4, 24); - tabPageSessions.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageSessions.Name = "tabPageSessions"; - tabPageSessions.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageSessions.Size = new System.Drawing.Size(942, 440); - tabPageSessions.TabIndex = 6; - tabPageSessions.Text = "Persistence"; - tabPageSessions.UseVisualStyleBackColor = true; - // - // checkBoxPortableMode - // - checkBoxPortableMode.AutoSize = true; - checkBoxPortableMode.Location = new System.Drawing.Point(34, 377); - checkBoxPortableMode.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxPortableMode.Name = "checkBoxPortableMode"; - checkBoxPortableMode.Size = new System.Drawing.Size(150, 19); - checkBoxPortableMode.TabIndex = 3; - checkBoxPortableMode.Text = "Activate Portable Mode"; - toolTip.SetToolTip(checkBoxPortableMode, "If this mode is activated, the save file will be loaded from the Executable Location"); - checkBoxPortableMode.UseVisualStyleBackColor = true; - checkBoxPortableMode.CheckedChanged += OnPortableModeCheckedChanged; - // - // checkBoxSaveFilter - // - checkBoxSaveFilter.AutoSize = true; - checkBoxSaveFilter.Location = new System.Drawing.Point(34, 74); - checkBoxSaveFilter.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxSaveFilter.Name = "checkBoxSaveFilter"; - checkBoxSaveFilter.Size = new System.Drawing.Size(217, 19); - checkBoxSaveFilter.TabIndex = 2; - checkBoxSaveFilter.Text = " Save and restore filter and filter tabs"; - checkBoxSaveFilter.UseVisualStyleBackColor = true; - // - // groupBoxPersistantFileLocation - // - groupBoxPersistantFileLocation.Controls.Add(labelSessionSaveOwnDir); - groupBoxPersistantFileLocation.Controls.Add(buttonSessionSaveDir); - groupBoxPersistantFileLocation.Controls.Add(radioButtonSessionSaveOwn); - groupBoxPersistantFileLocation.Controls.Add(radioButtonsessionSaveDocuments); - groupBoxPersistantFileLocation.Controls.Add(radioButtonSessionSameDir); - groupBoxPersistantFileLocation.Controls.Add(radioButtonSessionApplicationStartupDir); - groupBoxPersistantFileLocation.Location = new System.Drawing.Point(34, 134); - groupBoxPersistantFileLocation.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxPersistantFileLocation.Name = "groupBoxPersistantFileLocation"; - groupBoxPersistantFileLocation.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxPersistantFileLocation.Size = new System.Drawing.Size(411, 211); - groupBoxPersistantFileLocation.TabIndex = 1; - groupBoxPersistantFileLocation.TabStop = false; - groupBoxPersistantFileLocation.Text = "Persistence file location"; - // - // labelSessionSaveOwnDir - // - labelSessionSaveOwnDir.Location = new System.Drawing.Point(39, 142); - labelSessionSaveOwnDir.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelSessionSaveOwnDir.Name = "labelSessionSaveOwnDir"; - labelSessionSaveOwnDir.Size = new System.Drawing.Size(252, 31); - labelSessionSaveOwnDir.TabIndex = 4; - labelSessionSaveOwnDir.Text = "sessionSaveOwnDirLabel"; - // - // buttonSessionSaveDir - // - buttonSessionSaveDir.Location = new System.Drawing.Point(357, 102); - buttonSessionSaveDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonSessionSaveDir.Name = "buttonSessionSaveDir"; - buttonSessionSaveDir.Size = new System.Drawing.Size(45, 31); - buttonSessionSaveDir.TabIndex = 3; - buttonSessionSaveDir.Text = "..."; - buttonSessionSaveDir.UseVisualStyleBackColor = true; - buttonSessionSaveDir.Click += OnBtnSessionSaveDirClick; - // - // radioButtonSessionSaveOwn - // - radioButtonSessionSaveOwn.AutoSize = true; - radioButtonSessionSaveOwn.Location = new System.Drawing.Point(10, 105); - radioButtonSessionSaveOwn.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonSessionSaveOwn.Name = "radioButtonSessionSaveOwn"; - radioButtonSessionSaveOwn.Size = new System.Drawing.Size(100, 19); - radioButtonSessionSaveOwn.TabIndex = 2; - radioButtonSessionSaveOwn.TabStop = true; - radioButtonSessionSaveOwn.Text = "Own directory"; - radioButtonSessionSaveOwn.UseVisualStyleBackColor = true; - // - // radioButtonsessionSaveDocuments - // - radioButtonsessionSaveDocuments.AutoSize = true; - radioButtonsessionSaveDocuments.Location = new System.Drawing.Point(10, 68); - radioButtonsessionSaveDocuments.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonsessionSaveDocuments.Name = "radioButtonsessionSaveDocuments"; - radioButtonsessionSaveDocuments.Size = new System.Drawing.Size(160, 19); - radioButtonsessionSaveDocuments.TabIndex = 1; - radioButtonsessionSaveDocuments.TabStop = true; - radioButtonsessionSaveDocuments.Text = "MyDocuments/LogExpert"; - radioButtonsessionSaveDocuments.UseVisualStyleBackColor = true; - // - // radioButtonSessionSameDir - // - radioButtonSessionSameDir.AutoSize = true; - radioButtonSessionSameDir.Location = new System.Drawing.Point(10, 31); - radioButtonSessionSameDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonSessionSameDir.Name = "radioButtonSessionSameDir"; - radioButtonSessionSameDir.Size = new System.Drawing.Size(157, 19); - radioButtonSessionSameDir.TabIndex = 0; - radioButtonSessionSameDir.TabStop = true; - radioButtonSessionSameDir.Text = "Same directory as log file"; - radioButtonSessionSameDir.UseVisualStyleBackColor = true; - // - // radioButtonSessionApplicationStartupDir - // - radioButtonSessionApplicationStartupDir.AutoSize = true; - radioButtonSessionApplicationStartupDir.Location = new System.Drawing.Point(8, 177); - radioButtonSessionApplicationStartupDir.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - radioButtonSessionApplicationStartupDir.Name = "radioButtonSessionApplicationStartupDir"; - radioButtonSessionApplicationStartupDir.Size = new System.Drawing.Size(176, 19); - radioButtonSessionApplicationStartupDir.TabIndex = 5; - radioButtonSessionApplicationStartupDir.TabStop = true; - radioButtonSessionApplicationStartupDir.Text = "Application startup directory"; - toolTip.SetToolTip(radioButtonSessionApplicationStartupDir, "This path is based on the executable and where it has been started from."); - radioButtonSessionApplicationStartupDir.UseVisualStyleBackColor = true; - // - // checkBoxSaveSessions - // - checkBoxSaveSessions.AutoSize = true; - checkBoxSaveSessions.Location = new System.Drawing.Point(34, 38); - checkBoxSaveSessions.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxSaveSessions.Name = "checkBoxSaveSessions"; - checkBoxSaveSessions.Size = new System.Drawing.Size(241, 19); - checkBoxSaveSessions.TabIndex = 0; - checkBoxSaveSessions.Text = "Automatically save persistence files (.lxp)"; - checkBoxSaveSessions.UseVisualStyleBackColor = true; - // - // tabPageMemory - // - tabPageMemory.Controls.Add(groupBoxCPUAndStuff); - tabPageMemory.Controls.Add(groupBoxLineBufferUsage); - tabPageMemory.Location = new System.Drawing.Point(4, 24); - tabPageMemory.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageMemory.Name = "tabPageMemory"; - tabPageMemory.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - tabPageMemory.Size = new System.Drawing.Size(942, 440); - tabPageMemory.TabIndex = 7; - tabPageMemory.Text = "Memory/CPU"; - tabPageMemory.UseVisualStyleBackColor = true; - // - // groupBoxCPUAndStuff - // - groupBoxCPUAndStuff.Controls.Add(checkBoxLegacyReader); - groupBoxCPUAndStuff.Controls.Add(checkBoxMultiThread); - groupBoxCPUAndStuff.Controls.Add(labelFilePollingInterval); - groupBoxCPUAndStuff.Controls.Add(upDownPollingInterval); - groupBoxCPUAndStuff.Location = new System.Drawing.Point(408, 29); - groupBoxCPUAndStuff.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxCPUAndStuff.Name = "groupBoxCPUAndStuff"; - groupBoxCPUAndStuff.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxCPUAndStuff.Size = new System.Drawing.Size(300, 197); - groupBoxCPUAndStuff.TabIndex = 8; - groupBoxCPUAndStuff.TabStop = false; - groupBoxCPUAndStuff.Text = "CPU and stuff"; - // - // checkBoxLegacyReader - // - checkBoxLegacyReader.AutoSize = true; - checkBoxLegacyReader.Location = new System.Drawing.Point(14, 138); - checkBoxLegacyReader.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxLegacyReader.Name = "checkBoxLegacyReader"; - checkBoxLegacyReader.Size = new System.Drawing.Size(182, 19); - checkBoxLegacyReader.TabIndex = 9; - checkBoxLegacyReader.Text = "Use legacy file reader (slower)"; - toolTip.SetToolTip(checkBoxLegacyReader, "Slower but more compatible with strange linefeeds and encodings"); - checkBoxLegacyReader.UseVisualStyleBackColor = true; - // - // checkBoxMultiThread - // - checkBoxMultiThread.AutoSize = true; - checkBoxMultiThread.Location = new System.Drawing.Point(14, 103); - checkBoxMultiThread.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - checkBoxMultiThread.Name = "checkBoxMultiThread"; - checkBoxMultiThread.Size = new System.Drawing.Size(131, 19); - checkBoxMultiThread.TabIndex = 5; - checkBoxMultiThread.Text = "Multi threaded filter"; - checkBoxMultiThread.UseVisualStyleBackColor = true; - // - // labelFilePollingInterval - // - labelFilePollingInterval.AutoSize = true; - labelFilePollingInterval.Location = new System.Drawing.Point(9, 52); - labelFilePollingInterval.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelFilePollingInterval.Name = "labelFilePollingInterval"; - labelFilePollingInterval.Size = new System.Drawing.Size(137, 15); - labelFilePollingInterval.TabIndex = 7; - labelFilePollingInterval.Text = "File polling interval (ms):"; - // - // upDownPollingInterval - // - upDownPollingInterval.Location = new System.Drawing.Point(190, 49); - upDownPollingInterval.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - upDownPollingInterval.Maximum = new decimal(new int[] { 5000, 0, 0, 0 }); - upDownPollingInterval.Minimum = new decimal(new int[] { 20, 0, 0, 0 }); - upDownPollingInterval.Name = "upDownPollingInterval"; - upDownPollingInterval.Size = new System.Drawing.Size(86, 23); - upDownPollingInterval.TabIndex = 6; - upDownPollingInterval.Value = new decimal(new int[] { 20, 0, 0, 0 }); - // - // groupBoxLineBufferUsage - // - groupBoxLineBufferUsage.Controls.Add(labelInfo); - groupBoxLineBufferUsage.Controls.Add(labelNumberOfBlocks); - groupBoxLineBufferUsage.Controls.Add(upDownLinesPerBlock); - groupBoxLineBufferUsage.Controls.Add(upDownBlockCount); - groupBoxLineBufferUsage.Controls.Add(labelLinesPerBlock); - groupBoxLineBufferUsage.Location = new System.Drawing.Point(10, 29); - groupBoxLineBufferUsage.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxLineBufferUsage.Name = "groupBoxLineBufferUsage"; - groupBoxLineBufferUsage.Padding = new System.Windows.Forms.Padding(4, 5, 4, 5); - groupBoxLineBufferUsage.Size = new System.Drawing.Size(326, 197); - groupBoxLineBufferUsage.TabIndex = 4; - groupBoxLineBufferUsage.TabStop = false; - groupBoxLineBufferUsage.Text = "Line buffer usage"; - // - // labelInfo - // - labelInfo.AutoSize = true; - labelInfo.Location = new System.Drawing.Point(9, 145); - labelInfo.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelInfo.Name = "labelInfo"; - labelInfo.Size = new System.Drawing.Size(219, 15); - labelInfo.TabIndex = 4; - labelInfo.Text = "Changes will take effect on next file load"; - // - // labelNumberOfBlocks - // - labelNumberOfBlocks.AutoSize = true; - labelNumberOfBlocks.Location = new System.Drawing.Point(9, 52); - labelNumberOfBlocks.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelNumberOfBlocks.Name = "labelNumberOfBlocks"; - labelNumberOfBlocks.Size = new System.Drawing.Size(102, 15); - labelNumberOfBlocks.TabIndex = 1; - labelNumberOfBlocks.Text = "Number of blocks"; - // - // upDownLinesPerBlock - // - upDownLinesPerBlock.Location = new System.Drawing.Point(210, 102); - upDownLinesPerBlock.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - upDownLinesPerBlock.Maximum = new decimal(new int[] { 5000000, 0, 0, 0 }); - upDownLinesPerBlock.Minimum = new decimal(new int[] { 1, 0, 0, 0 }); - upDownLinesPerBlock.Name = "upDownLinesPerBlock"; - upDownLinesPerBlock.Size = new System.Drawing.Size(94, 23); - upDownLinesPerBlock.TabIndex = 3; - upDownLinesPerBlock.Value = new decimal(new int[] { 50000, 0, 0, 0 }); - upDownLinesPerBlock.ValueChanged += OnNumericUpDown1ValueChanged; - // - // upDownBlockCount - // - upDownBlockCount.Location = new System.Drawing.Point(210, 49); - upDownBlockCount.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - upDownBlockCount.Maximum = new decimal(new int[] { 5000, 0, 0, 0 }); - upDownBlockCount.Minimum = new decimal(new int[] { 10, 0, 0, 0 }); - upDownBlockCount.Name = "upDownBlockCount"; - upDownBlockCount.Size = new System.Drawing.Size(94, 23); - upDownBlockCount.TabIndex = 0; - upDownBlockCount.Value = new decimal(new int[] { 100, 0, 0, 0 }); - // - // labelLinesPerBlock - // - labelLinesPerBlock.AutoSize = true; - labelLinesPerBlock.Location = new System.Drawing.Point(9, 105); - labelLinesPerBlock.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); - labelLinesPerBlock.Name = "labelLinesPerBlock"; - labelLinesPerBlock.Size = new System.Drawing.Size(68, 15); - labelLinesPerBlock.TabIndex = 2; - labelLinesPerBlock.Text = "Lines/block"; - // - // buttonCancel - // - buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - buttonCancel.Location = new System.Drawing.Point(818, 509); - buttonCancel.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonCancel.Name = "buttonCancel"; - buttonCancel.Size = new System.Drawing.Size(112, 35); - buttonCancel.TabIndex = 1; - buttonCancel.Text = "Cancel"; - buttonCancel.UseVisualStyleBackColor = true; - buttonCancel.Click += OnBtnCancelClick; - // - // buttonOk - // - buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - buttonOk.Location = new System.Drawing.Point(696, 509); - buttonOk.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonOk.Name = "buttonOk"; - buttonOk.Size = new System.Drawing.Size(112, 35); - buttonOk.TabIndex = 0; - buttonOk.Text = "OK"; - buttonOk.UseVisualStyleBackColor = true; - buttonOk.Click += OnBtnOkClick; - // - // helpProvider - // - helpProvider.HelpNamespace = "LogExpert.chm"; - // - // buttonExport - // - buttonExport.Location = new System.Drawing.Point(20, 509); - buttonExport.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonExport.Name = "buttonExport"; - buttonExport.Size = new System.Drawing.Size(112, 35); - buttonExport.TabIndex = 2; - buttonExport.Text = "Export..."; - buttonExport.UseVisualStyleBackColor = true; - buttonExport.Click += OnBtnExportClick; - // - // buttonImport - // - buttonImport.Location = new System.Drawing.Point(142, 509); - buttonImport.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - buttonImport.Name = "buttonImport"; - buttonImport.Size = new System.Drawing.Size(112, 35); - buttonImport.TabIndex = 3; - buttonImport.Text = "Import..."; - buttonImport.UseVisualStyleBackColor = true; - buttonImport.Click += OnBtnImportClick; - // - // dataGridViewTextBoxColumn1 - // - dataGridViewTextBoxColumn1.HeaderText = "File name mask (RegEx)"; - dataGridViewTextBoxColumn1.MinimumWidth = 40; - dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; - dataGridViewTextBoxColumn1.Width = 99; - // - // dataGridViewTextBoxColumn2 - // - dataGridViewTextBoxColumn2.HeaderText = "File name mask (RegEx)"; - dataGridViewTextBoxColumn2.MinimumWidth = 40; - dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; - dataGridViewTextBoxColumn2.Width = 259; - // - // SettingsDialog - // - AcceptButton = buttonOk; - CancelButton = buttonCancel; - ClientSize = new System.Drawing.Size(956, 563); - Controls.Add(buttonImport); - Controls.Add(buttonExport); - Controls.Add(buttonOk); - Controls.Add(buttonCancel); - Controls.Add(tabControlSettings); - FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - helpProvider.SetHelpKeyword(this, "Settings.htm"); - helpProvider.SetHelpNavigator(this, System.Windows.Forms.HelpNavigator.Topic); - Icon = (System.Drawing.Icon)resources.GetObject("$this.Icon"); - Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); - MaximizeBox = false; - MinimizeBox = false; - Name = "SettingsDialog"; - helpProvider.SetShowHelp(this, true); - StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - Text = "Settings"; - Load += OnSettingsDialogLoad; - tabControlSettings.ResumeLayout(false); - tabPageViewSettings.ResumeLayout(false); - tabPageViewSettings.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)upDownMaximumLineLength).EndInit(); - ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntriesDisplayed).EndInit(); - ((System.ComponentModel.ISupportInitialize)upDownMaximumFilterEntries).EndInit(); - groupBoxMisc.ResumeLayout(false); - groupBoxMisc.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)cpDownColumnWidth).EndInit(); - groupBoxDefaults.ResumeLayout(false); - groupBoxDefaults.PerformLayout(); - groupBoxFont.ResumeLayout(false); - tabPageTimeStampFeatures.ResumeLayout(false); - groupBoxTimeSpreadDisplay.ResumeLayout(false); - groupBoxTimeSpreadDisplay.PerformLayout(); - groupBoxDisplayMode.ResumeLayout(false); - groupBoxDisplayMode.PerformLayout(); - groupBoxTimeStampNavigationControl.ResumeLayout(false); - groupBoxTimeStampNavigationControl.PerformLayout(); - groupBoxMouseDragDefaults.ResumeLayout(false); - groupBoxMouseDragDefaults.PerformLayout(); - tabPageExternalTools.ResumeLayout(false); - groupBoxToolSettings.ResumeLayout(false); - groupBoxToolSettings.PerformLayout(); - tabPageColumnizers.ResumeLayout(false); - tabPageColumnizers.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)dataGridViewColumnizer).EndInit(); - tabPageHighlightMask.ResumeLayout(false); - ((System.ComponentModel.ISupportInitialize)dataGridViewHighlightMask).EndInit(); - tabPageMultiFile.ResumeLayout(false); - groupBoxDefaultFileNamePattern.ResumeLayout(false); - groupBoxDefaultFileNamePattern.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)upDownMultifileDays).EndInit(); - groupBoxWhenOpeningMultiFile.ResumeLayout(false); - groupBoxWhenOpeningMultiFile.PerformLayout(); - tabPagePlugins.ResumeLayout(false); - groupBoxPlugins.ResumeLayout(false); - groupBoxSettings.ResumeLayout(false); - panelPlugin.ResumeLayout(false); - tabPageSessions.ResumeLayout(false); - tabPageSessions.PerformLayout(); - groupBoxPersistantFileLocation.ResumeLayout(false); - groupBoxPersistantFileLocation.PerformLayout(); - tabPageMemory.ResumeLayout(false); - groupBoxCPUAndStuff.ResumeLayout(false); - groupBoxCPUAndStuff.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)upDownPollingInterval).EndInit(); - groupBoxLineBufferUsage.ResumeLayout(false); - groupBoxLineBufferUsage.PerformLayout(); - ((System.ComponentModel.ISupportInitialize)upDownLinesPerBlock).EndInit(); - ((System.ComponentModel.ISupportInitialize)upDownBlockCount).EndInit(); - ResumeLayout(false); - } - - #endregion - - private System.Windows.Forms.TabControl tabControlSettings; - private System.Windows.Forms.TabPage tabPageViewSettings; - private System.Windows.Forms.Label labelFont; - private System.Windows.Forms.TabPage tabPageTimeStampFeatures; - private System.Windows.Forms.GroupBox groupBoxFont; - private System.Windows.Forms.Button buttonChangeFont; - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.CheckBox checkBoxFilterTail; - private System.Windows.Forms.CheckBox checkBoxFollowTail; - private System.Windows.Forms.CheckBox checkBoxSyncFilter; - private System.Windows.Forms.GroupBox groupBoxDefaults; - private System.Windows.Forms.CheckBox checkBoxTimestamp; - private System.Windows.Forms.GroupBox groupBoxMouseDragDefaults; - private System.Windows.Forms.RadioButton radioButtonHorizMouseDrag; - private System.Windows.Forms.RadioButton radioButtonVerticalMouseDrag; - private System.Windows.Forms.RadioButton radioButtonVerticalMouseDragInverted; - private System.Windows.Forms.TabPage tabPageExternalTools; - private System.Windows.Forms.GroupBox groupBoxToolSettings; - private System.Windows.Forms.TextBox textBoxArguments; - private System.Windows.Forms.Button buttonTool; - private System.Windows.Forms.TextBox textBoxTool; - private System.Windows.Forms.Label labelArguments; - private System.Windows.Forms.Label labelTool; - private System.Windows.Forms.Button buttonArguments; - private System.Windows.Forms.TabPage tabPageColumnizers; - private System.Windows.Forms.DataGridView dataGridViewColumnizer; - private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; - private System.Windows.Forms.Button buttonDelete; - private System.Windows.Forms.DataGridViewTextBoxColumn columnFileMask; - private System.Windows.Forms.DataGridViewComboBoxColumn columnColumnizer; - private System.Windows.Forms.CheckBox checkBoxSysout; - private System.Windows.Forms.CheckBox checkBoxMaskPrio; - private System.Windows.Forms.GroupBox groupBoxMisc; - private System.Windows.Forms.CheckBox checkBoxAskCloseTabs; - private System.Windows.Forms.TabPage tabPageMultiFile; - private System.Windows.Forms.GroupBox groupBoxWhenOpeningMultiFile; - private System.Windows.Forms.RadioButton radioButtonAskWhatToDo; - private System.Windows.Forms.RadioButton radioButtonTreatAllFilesAsOneMultifile; - private System.Windows.Forms.RadioButton radioButtonLoadEveryFileIntoSeperatedTab; - private System.Windows.Forms.Label labelNoteMultiFile; - private System.Windows.Forms.Label labelHintMultiFile; - private System.Windows.Forms.HelpProvider helpProvider; - private System.Windows.Forms.CheckBox checkBoxSingleInstance; - private System.Windows.Forms.ComboBox comboBoxColumnizer; - private System.Windows.Forms.CheckBox checkBoxOpenLastFiles; - private System.Windows.Forms.CheckBox checkBoxTailState; - private System.Windows.Forms.Button buttonTailColor; - private System.Windows.Forms.NumericUpDown cpDownColumnWidth; - private System.Windows.Forms.CheckBox checkBoxColumnSize; - private System.Windows.Forms.CheckBox checkBoxTimeSpread; - private System.Windows.Forms.GroupBox groupBoxTimeSpreadDisplay; - private System.Windows.Forms.GroupBox groupBoxTimeStampNavigationControl; - private System.Windows.Forms.Button buttonTimespreadColor; - private System.Windows.Forms.CheckBox checkBoxReverseAlpha; - private System.Windows.Forms.GroupBox groupBoxDisplayMode; - private System.Windows.Forms.RadioButton radioButtonLineView; - private System.Windows.Forms.RadioButton radioButtonTimeView; - private System.Windows.Forms.TabPage tabPagePlugins; - private System.Windows.Forms.ListBox listBoxPlugin; - private System.Windows.Forms.Panel panelPlugin; - private System.Windows.Forms.GroupBox groupBoxPlugins; - private System.Windows.Forms.GroupBox groupBoxSettings; - private System.Windows.Forms.Button buttonConfigPlugin; - private System.Windows.Forms.TabPage tabPageSessions; - private System.Windows.Forms.GroupBox groupBoxPersistantFileLocation; - private System.Windows.Forms.RadioButton radioButtonsessionSaveDocuments; - private System.Windows.Forms.RadioButton radioButtonSessionSameDir; - private System.Windows.Forms.CheckBox checkBoxSaveSessions; - private System.Windows.Forms.RadioButton radioButtonSessionSaveOwn; - private System.Windows.Forms.Label labelSessionSaveOwnDir; - private System.Windows.Forms.Button buttonSessionSaveDir; - private System.Windows.Forms.CheckBox checkBoxSaveFilter; - private System.Windows.Forms.TabPage tabPageMemory; - private System.Windows.Forms.Label labelNumberOfBlocks; - private System.Windows.Forms.NumericUpDown upDownBlockCount; - private System.Windows.Forms.NumericUpDown upDownLinesPerBlock; - private System.Windows.Forms.Label labelLinesPerBlock; - private System.Windows.Forms.GroupBox groupBoxLineBufferUsage; - private System.Windows.Forms.Label labelInfo; - private System.Windows.Forms.TabPage tabPageHighlightMask; - private System.Windows.Forms.DataGridView dataGridViewHighlightMask; - private System.Windows.Forms.DataGridViewTextBoxColumn columnFileName; - private System.Windows.Forms.DataGridViewComboBoxColumn columnHighlightGroup; - private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; - private System.Windows.Forms.CheckBox checkBoxMultiThread; - private System.Windows.Forms.Label labelFilePollingInterval; - private System.Windows.Forms.NumericUpDown upDownPollingInterval; - private System.Windows.Forms.GroupBox groupBoxCPUAndStuff; - private System.Windows.Forms.Label labelToolColumnizerForOutput; - private System.Windows.Forms.Label labelToolName; - private System.Windows.Forms.CheckedListBox listBoxTools; - private System.Windows.Forms.TextBox textBoxToolName; - private System.Windows.Forms.Button buttonToolDelete; - private System.Windows.Forms.Button buttonToolAdd; - private System.Windows.Forms.Button buttonToolDown; - private System.Windows.Forms.Button buttonToolUp; - private System.Windows.Forms.Label labelToolsDescription; - private System.Windows.Forms.Button buttonIcon; - private System.Windows.Forms.Label labelWorkingDir; - private System.Windows.Forms.Button buttonWorkingDir; - private System.Windows.Forms.TextBox textBoxWorkingDir; - private System.Windows.Forms.GroupBox groupBoxDefaultFileNamePattern; - private System.Windows.Forms.Label labelMaxDays; - private System.Windows.Forms.Label labelPattern; - private System.Windows.Forms.NumericUpDown upDownMultifileDays; - private System.Windows.Forms.TextBox textBoxMultifilePattern; - private System.Windows.Forms.Label labelDefaultEncoding; - private System.Windows.Forms.ComboBox comboBoxEncoding; - private System.Windows.Forms.ToolTip toolTip; - private System.Windows.Forms.CheckBox checkBoxColumnFinder; - private System.Windows.Forms.Button buttonExport; - private System.Windows.Forms.Button buttonImport; - private System.Windows.Forms.CheckBox checkBoxLegacyReader; - private System.Windows.Forms.Label labelMaximumFilterEntries; - private System.Windows.Forms.NumericUpDown upDownMaximumFilterEntries; - private System.Windows.Forms.NumericUpDown upDownMaximumFilterEntriesDisplayed; - private System.Windows.Forms.Label labelMaximumFilterEntriesDisplayed; - private System.Windows.Forms.CheckBox checkBoxAutoPick; - private System.Windows.Forms.CheckBox checkBoxPortableMode; - private System.Windows.Forms.RadioButton radioButtonSessionApplicationStartupDir; - private System.Windows.Forms.CheckBox checkBoxShowErrorMessageOnlyOneInstance; - private System.Windows.Forms.CheckBox checkBoxDarkMode; - private System.Windows.Forms.NumericUpDown upDownMaximumLineLength; - private System.Windows.Forms.Label labelMaximumLineLength; - private System.Windows.Forms.Label labelWarningMaximumLineLenght; - } -} diff --git a/src/LogExpert/Dialogs/SettingsDialog.cs b/src/LogExpert/Dialogs/SettingsDialog.cs deleted file mode 100644 index e96346e9..00000000 --- a/src/LogExpert/Dialogs/SettingsDialog.cs +++ /dev/null @@ -1,1035 +0,0 @@ -using LogExpert.Classes; -using LogExpert.Classes.Columnizer; -using LogExpert.Config; -using LogExpert.Controls.LogTabWindow; -using LogExpert.Entities; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.IO; -using System.Runtime.InteropServices; -using System.Text; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - internal partial class SettingsDialog : Form - { - #region Fields - - private readonly Image _emptyImage = new Bitmap(16, 16); - private readonly LogTabWindow _logTabWin; - - private ILogExpertPluginConfigurator _selectedPlugin; - private ToolEntry _selectedTool; - - #endregion - - #region cTor - - public SettingsDialog(Preferences prefs, LogTabWindow logTabWin) - { - Preferences = prefs; - _logTabWin = logTabWin; - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - } - - public SettingsDialog(Preferences prefs, LogTabWindow logTabWin, int tabToOpen) : this(prefs, logTabWin) - { - tabControlSettings.SelectedIndex = tabToOpen; - } - - #endregion - - #region Properties - - public Preferences Preferences { get; private set; } - - #endregion - - #region Private Methods - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - private static extern bool DestroyIcon(IntPtr handle); - - private void FillDialog() - { - Preferences ??= new Preferences(); - - if (Preferences.fontName == null) - { - Preferences.fontName = "Courier New"; - } - - if (Math.Abs(Preferences.fontSize) < 0.1) - { - Preferences.fontSize = 9.0f; - } - - FillPortableMode(); - - checkBoxDarkMode.Checked = Preferences.darkMode; - checkBoxTimestamp.Checked = Preferences.timestampControl; - checkBoxSyncFilter.Checked = Preferences.filterSync; - checkBoxFilterTail.Checked = Preferences.filterTail; - checkBoxFollowTail.Checked = Preferences.followTail; - - radioButtonHorizMouseDrag.Checked = Preferences.timestampControlDragOrientation == DateTimeDragControl.DragOrientations.Horizontal; - radioButtonVerticalMouseDrag.Checked = Preferences.timestampControlDragOrientation == DateTimeDragControl.DragOrientations.Vertical; - radioButtonVerticalMouseDragInverted.Checked = Preferences.timestampControlDragOrientation == DateTimeDragControl.DragOrientations.InvertedVertical; - - checkBoxSingleInstance.Checked = Preferences.allowOnlyOneInstance; - checkBoxOpenLastFiles.Checked = Preferences.openLastFiles; - checkBoxTailState.Checked = Preferences.showTailState; - checkBoxColumnSize.Checked = Preferences.setLastColumnWidth; - cpDownColumnWidth.Enabled = Preferences.setLastColumnWidth; - - if (Preferences.lastColumnWidth != 0) - { - if (Preferences.lastColumnWidth < cpDownColumnWidth.Minimum) - { - Preferences.lastColumnWidth = (int)cpDownColumnWidth.Minimum; - } - - if (Preferences.lastColumnWidth > cpDownColumnWidth.Maximum) - { - Preferences.lastColumnWidth = (int)cpDownColumnWidth.Maximum; - } - - cpDownColumnWidth.Value = Preferences.lastColumnWidth; - } - - checkBoxTimeSpread.Checked = Preferences.showTimeSpread; - checkBoxReverseAlpha.Checked = Preferences.reverseAlpha; - - radioButtonTimeView.Checked = Preferences.timeSpreadTimeMode; - radioButtonLineView.Checked = !Preferences.timeSpreadTimeMode; - - checkBoxSaveSessions.Checked = Preferences.saveSessions; - - switch (Preferences.saveLocation) - { - case SessionSaveLocation.OwnDir: - { - radioButtonSessionSaveOwn.Checked = true; - } - break; - case SessionSaveLocation.SameDir: - { - radioButtonSessionSameDir.Checked = true; - } - break; - case SessionSaveLocation.DocumentsDir: - { - radioButtonsessionSaveDocuments.Checked = true; - break; - } - case SessionSaveLocation.ApplicationStartupDir: - { - radioButtonSessionApplicationStartupDir.Checked = true; - break; - } - } - - //overwrite preferences save location in portable mode to always be application startup directory - if (checkBoxPortableMode.Checked) - { - radioButtonSessionApplicationStartupDir.Checked = true; - } - - upDownMaximumLineLength.Value = Preferences.MaxLineLength; - - upDownMaximumFilterEntriesDisplayed.Value = Preferences.maximumFilterEntriesDisplayed; - upDownMaximumFilterEntries.Value = Preferences.maximumFilterEntries; - - labelSessionSaveOwnDir.Text = Preferences.sessionSaveDirectory ?? string.Empty; - checkBoxSaveFilter.Checked = Preferences.saveFilters; - upDownBlockCount.Value = Preferences.bufferCount; - upDownLinesPerBlock.Value = Preferences.linesPerBuffer; - upDownPollingInterval.Value = Preferences.pollingInterval; - checkBoxMultiThread.Checked = Preferences.multiThreadFilter; - - dataGridViewColumnizer.DataError += OnDataGridViewColumnizerDataError; - - FillColumnizerList(); - FillPluginList(); - DisplayFontName(); - FillHighlightMaskList(); - FillToolListbox(); - FillMultifileSettings(); - FillEncodingList(); - - var temp = Encoding.GetEncoding(Preferences.defaultEncoding); - - comboBoxEncoding.SelectedItem = Encoding.GetEncoding(Preferences.defaultEncoding); - checkBoxMaskPrio.Checked = Preferences.maskPrio; - checkBoxAutoPick.Checked = Preferences.autoPick; - checkBoxAskCloseTabs.Checked = Preferences.askForClose; - checkBoxColumnFinder.Checked = Preferences.showColumnFinder; - checkBoxLegacyReader.Checked = Preferences.useLegacyReader; - checkBoxShowErrorMessageOnlyOneInstance.Checked = Preferences.ShowErrorMessageAllowOnlyOneInstances; - } - - private void FillPortableMode() - { - checkBoxPortableMode.CheckState = Preferences.PortableMode ? CheckState.Checked : CheckState.Unchecked; - } - - private void DisplayFontName() - { - labelFont.Text = Preferences.fontName + @" " + (int)Preferences.fontSize; - labelFont.Font = new Font(new FontFamily(Preferences.fontName), Preferences.fontSize); - } - - private void SaveMultifileData() - { - if (radioButtonLoadEveryFileIntoSeperatedTab.Checked) - { - Preferences.multiFileOption = MultiFileOption.SingleFiles; - } - - if (radioButtonTreatAllFilesAsOneMultifile.Checked) - { - Preferences.multiFileOption = MultiFileOption.MultiFile; - } - - if (radioButtonAskWhatToDo.Checked) - { - Preferences.multiFileOption = MultiFileOption.Ask; - } - - Preferences.multiFileOptions.FormatPattern = textBoxMultifilePattern.Text; - Preferences.multiFileOptions.MaxDayTry = (int)upDownMultifileDays.Value; - } - - private void OnBtnToolClickInternal(TextBox textBox) - { - OpenFileDialog dlg = new(); - dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); - - if (string.IsNullOrEmpty(textBox.Text) == false) - { - FileInfo info = new(textBox.Text); - if (info.Directory != null && info.Directory.Exists) - { - dlg.InitialDirectory = info.DirectoryName; - } - } - - if (dlg.ShowDialog() == DialogResult.OK) - { - textBox.Text = dlg.FileName; - } - } - - private void OnBtnArgsClickInternal(TextBox textBox) - { - ToolArgsDialog dlg = new(_logTabWin, this) - { - Arg = textBox.Text - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - textBox.Text = dlg.Arg; - } - } - - private void OnBtnWorkingDirClick(TextBox textBox) - { - FolderBrowserDialog dlg = new() - { - RootFolder = Environment.SpecialFolder.MyComputer, - Description = @"Select a working directory" - }; - - if (!string.IsNullOrEmpty(textBox.Text)) - { - DirectoryInfo info = new(textBox.Text); - if (info.Exists) - { - dlg.SelectedPath = info.FullName; - } - } - - if (dlg.ShowDialog() == DialogResult.OK) - { - textBox.Text = dlg.SelectedPath; - } - } - - private void FillColumnizerForToolsList() - { - if (_selectedTool != null) - { - FillColumnizerForToolsList(comboBoxColumnizer, _selectedTool.columnizerName); - } - } - - private void FillColumnizerForToolsList(ComboBox comboBox, string columnizerName) - { - int selIndex = 0; - comboBox.Items.Clear(); - IList columnizers = PluginRegistry.Instance.RegisteredColumnizers; - - foreach (ILogLineColumnizer columnizer in columnizers) - { - int index = comboBox.Items.Add(columnizer.GetName()); - if (columnizer.GetName().Equals(columnizerName)) - { - selIndex = index; - } - } - - //ILogLineColumnizer columnizer = Util.FindColumnizerByName(columnizerName, this.logTabWin.RegisteredColumnizers); - //if (columnizer == null) - // columnizer = this.logTabWin.RegisteredColumnizers[0]; - comboBox.SelectedIndex = selIndex; - } - - private void FillColumnizerList() - { - dataGridViewColumnizer.Rows.Clear(); - - DataGridViewComboBoxColumn comboColumn = (DataGridViewComboBoxColumn)dataGridViewColumnizer.Columns[1]; - comboColumn.Items.Clear(); - - DataGridViewTextBoxColumn textColumn = (DataGridViewTextBoxColumn)dataGridViewColumnizer.Columns[0]; - - IList columnizers = PluginRegistry.Instance.RegisteredColumnizers; - - foreach (ILogLineColumnizer columnizer in columnizers) - { - comboColumn.Items.Add(columnizer.GetName()); - } - //comboColumn.DisplayMember = "Name"; - //comboColumn.ValueMember = "Columnizer"; - - foreach (ColumnizerMaskEntry maskEntry in Preferences.columnizerMaskList) - { - DataGridViewRow row = new(); - row.Cells.Add(new DataGridViewTextBoxCell()); - DataGridViewComboBoxCell cell = new(); - - foreach (ILogLineColumnizer logColumnizer in columnizers) - { - cell.Items.Add(logColumnizer.GetName()); - } - - row.Cells.Add(cell); - row.Cells[0].Value = maskEntry.mask; - ILogLineColumnizer columnizer = ColumnizerPicker.DecideColumnizerByName(maskEntry.columnizerName, - PluginRegistry.Instance.RegisteredColumnizers); - - row.Cells[1].Value = columnizer.GetName(); - dataGridViewColumnizer.Rows.Add(row); - } - - int count = dataGridViewColumnizer.RowCount; - - if (count > 0 && !dataGridViewColumnizer.Rows[count - 1].IsNewRow) - { - DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridViewColumnizer.Rows[count - 1].Cells[1]; - comboCell.Value = comboCell.Items[0]; - } - } - - private void FillHighlightMaskList() - { - dataGridViewHighlightMask.Rows.Clear(); - - DataGridViewComboBoxColumn comboColumn = (DataGridViewComboBoxColumn)dataGridViewHighlightMask.Columns[1]; - comboColumn.Items.Clear(); - - //TODO Remove if not necessary - DataGridViewTextBoxColumn textColumn = (DataGridViewTextBoxColumn)dataGridViewHighlightMask.Columns[0]; - - foreach (HilightGroup group in (IList)_logTabWin.HilightGroupList) - { - comboColumn.Items.Add(group.GroupName); - } - - foreach (HighlightMaskEntry maskEntry in Preferences.highlightMaskList) - { - DataGridViewRow row = new(); - row.Cells.Add(new DataGridViewTextBoxCell()); - DataGridViewComboBoxCell cell = new(); - - foreach (HilightGroup group in (IList)_logTabWin.HilightGroupList) - { - cell.Items.Add(group.GroupName); - } - - row.Cells.Add(cell); - row.Cells[0].Value = maskEntry.mask; - - HilightGroup currentGroup = _logTabWin.FindHighlightGroup(maskEntry.highlightGroupName); - currentGroup ??= ((IList)_logTabWin.HilightGroupList)[0]; - currentGroup ??= new HilightGroup(); - - row.Cells[1].Value = currentGroup.GroupName; - dataGridViewHighlightMask.Rows.Add(row); - } - - int count = dataGridViewHighlightMask.RowCount; - - if (count > 0 && !dataGridViewHighlightMask.Rows[count - 1].IsNewRow) - { - DataGridViewComboBoxCell comboCell = - (DataGridViewComboBoxCell)dataGridViewHighlightMask.Rows[count - 1].Cells[1]; - comboCell.Value = comboCell.Items[0]; - } - } - - private void SaveColumnizerList() - { - Preferences.columnizerMaskList.Clear(); - - foreach (DataGridViewRow row in dataGridViewColumnizer.Rows) - { - if (!row.IsNewRow) - { - ColumnizerMaskEntry entry = new(); - entry.mask = (string)row.Cells[0].Value; - entry.columnizerName = (string)row.Cells[1].Value; - Preferences.columnizerMaskList.Add(entry); - } - } - } - - private void SaveHighlightMaskList() - { - Preferences.highlightMaskList.Clear(); - - foreach (DataGridViewRow row in dataGridViewHighlightMask.Rows) - { - if (!row.IsNewRow) - { - HighlightMaskEntry entry = new(); - entry.mask = (string)row.Cells[0].Value; - entry.highlightGroupName = (string)row.Cells[1].Value; - Preferences.highlightMaskList.Add(entry); - } - } - } - - private void FillPluginList() - { - listBoxPlugin.Items.Clear(); - - foreach (IContextMenuEntry entry in PluginRegistry.Instance.RegisteredContextMenuPlugins) - { - listBoxPlugin.Items.Add(entry); - if (entry is ILogExpertPluginConfigurator configurator) - { - configurator.StartConfig(); - } - } - - foreach (IKeywordAction entry in PluginRegistry.Instance.RegisteredKeywordActions) - { - listBoxPlugin.Items.Add(entry); - if (entry is ILogExpertPluginConfigurator configurator) - { - configurator.StartConfig(); - } - } - - foreach (IFileSystemPlugin entry in PluginRegistry.Instance.RegisteredFileSystemPlugins) - { - listBoxPlugin.Items.Add(entry); - if (entry is ILogExpertPluginConfigurator configurator) - { - configurator.StartConfig(); - } - } - - buttonConfigPlugin.Enabled = false; - } - - private void SavePluginSettings() - { - _selectedPlugin?.HideConfigForm(); - - foreach (IContextMenuEntry entry in PluginRegistry.Instance.RegisteredContextMenuPlugins) - { - if (entry is ILogExpertPluginConfigurator configurator) - { - configurator.SaveConfig(checkBoxPortableMode.Checked ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir); - } - } - - foreach (IKeywordAction entry in PluginRegistry.Instance.RegisteredKeywordActions) - { - if (entry is ILogExpertPluginConfigurator configurator) - { - configurator.SaveConfig(checkBoxPortableMode.Checked ? ConfigManager.PortableModeDir : ConfigManager.ConfigDir); - } - } - } - - private void FillToolListbox() - { - listBoxTools.Items.Clear(); - - foreach (ToolEntry tool in Preferences.toolEntries) - { - listBoxTools.Items.Add(tool.Clone(), tool.isFavourite); - } - - if (listBoxTools.Items.Count > 0) - { - listBoxTools.SelectedIndex = 0; - } - } - - private void FillMultifileSettings() - { - switch (Preferences.multiFileOption) - { - case MultiFileOption.SingleFiles: - { - radioButtonLoadEveryFileIntoSeperatedTab.Checked = true; - break; - } - case MultiFileOption.MultiFile: - { - radioButtonTreatAllFilesAsOneMultifile.Checked = true; - break; - } - case MultiFileOption.Ask: - { - radioButtonAskWhatToDo.Checked = true; - break; - } - } - - textBoxMultifilePattern.Text = Preferences.multiFileOptions.FormatPattern; - upDownMultifileDays.Value = Preferences.multiFileOptions.MaxDayTry; - } - - private void GetToolListBoxData() - { - GetCurrentToolValues(); - Preferences.toolEntries.Clear(); - - for (int i = 0; i < listBoxTools.Items.Count; ++i) - { - Preferences.toolEntries.Add(listBoxTools.Items[i] as ToolEntry); - (listBoxTools.Items[i] as ToolEntry).isFavourite = listBoxTools.GetItemChecked(i); - } - } - - private void GetCurrentToolValues() - { - if (_selectedTool != null) - { - _selectedTool.name = Util.IsNullOrSpaces(textBoxToolName.Text) ? textBoxTool.Text : textBoxToolName.Text; - _selectedTool.cmd = textBoxTool.Text; - _selectedTool.args = textBoxArguments.Text; - _selectedTool.columnizerName = comboBoxColumnizer.Text; - _selectedTool.sysout = checkBoxSysout.Checked; - _selectedTool.workingDir = textBoxWorkingDir.Text; - } - } - - private void ShowCurrentToolValues() - { - if (_selectedTool != null) - { - textBoxToolName.Text = _selectedTool.name; - textBoxTool.Text = _selectedTool.cmd; - textBoxArguments.Text = _selectedTool.args; - comboBoxColumnizer.Text = _selectedTool.columnizerName; - checkBoxSysout.Checked = _selectedTool.sysout; - comboBoxColumnizer.Enabled = _selectedTool.sysout; - textBoxWorkingDir.Text = _selectedTool.workingDir; - } - } - - private void DisplayCurrentIcon() - { - if (_selectedTool != null) - { - Icon icon = Win32.LoadIconFromExe(_selectedTool.iconFile, _selectedTool.iconIndex); - if (icon != null) - { - Image image = icon.ToBitmap(); - buttonIcon.Image = image; - DestroyIcon(icon.Handle); - icon.Dispose(); - } - else - { - buttonIcon.Image = _emptyImage; - } - } - } - - private void FillEncodingList() - { - comboBoxEncoding.Items.Clear(); - - comboBoxEncoding.Items.Add(Encoding.ASCII); - comboBoxEncoding.Items.Add(Encoding.Default); - comboBoxEncoding.Items.Add(Encoding.GetEncoding("iso-8859-1")); - comboBoxEncoding.Items.Add(Encoding.UTF8); - comboBoxEncoding.Items.Add(Encoding.Unicode); - comboBoxEncoding.Items.Add(CodePagesEncodingProvider.Instance.GetEncoding(1252)); - - comboBoxEncoding.ValueMember = "HeaderName"; - } - - #endregion - - #region Events handler - - private void OnSettingsDialogLoad(object sender, EventArgs e) - { - FillDialog(); - } - - private void OnBtnChangeFontClick(object sender, EventArgs e) - { - FontDialog dlg = new() - { - ShowEffects = false, - AllowVerticalFonts = false, - AllowScriptChange = false, - Font = new Font(new FontFamily(Preferences.fontName), Preferences.fontSize) - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - Preferences.fontSize = dlg.Font.Size; - Preferences.fontName = dlg.Font.FontFamily.Name; - } - - DisplayFontName(); - } - - private void OnBtnOkClick(object sender, EventArgs e) - { - Preferences.timestampControl = checkBoxTimestamp.Checked; - Preferences.filterSync = checkBoxSyncFilter.Checked; - Preferences.filterTail = checkBoxFilterTail.Checked; - Preferences.followTail = checkBoxFollowTail.Checked; - - if (radioButtonVerticalMouseDrag.Checked) - { - Preferences.timestampControlDragOrientation = DateTimeDragControl.DragOrientations.Vertical; - } - else if (radioButtonVerticalMouseDragInverted.Checked) - { - Preferences.timestampControlDragOrientation = DateTimeDragControl.DragOrientations.InvertedVertical; - } - else - { - Preferences.timestampControlDragOrientation = DateTimeDragControl.DragOrientations.Horizontal; - } - - SaveColumnizerList(); - - Preferences.maskPrio = checkBoxMaskPrio.Checked; - Preferences.autoPick = checkBoxAutoPick.Checked; - Preferences.askForClose = checkBoxAskCloseTabs.Checked; - Preferences.allowOnlyOneInstance = checkBoxSingleInstance.Checked; - Preferences.openLastFiles = checkBoxOpenLastFiles.Checked; - Preferences.showTailState = checkBoxTailState.Checked; - Preferences.setLastColumnWidth = checkBoxColumnSize.Checked; - Preferences.lastColumnWidth = (int)cpDownColumnWidth.Value; - Preferences.showTimeSpread = checkBoxTimeSpread.Checked; - Preferences.reverseAlpha = checkBoxReverseAlpha.Checked; - Preferences.timeSpreadTimeMode = radioButtonTimeView.Checked; - - Preferences.saveSessions = checkBoxSaveSessions.Checked; - Preferences.sessionSaveDirectory = labelSessionSaveOwnDir.Text; - - if (radioButtonsessionSaveDocuments.Checked) - { - Preferences.saveLocation = SessionSaveLocation.DocumentsDir; - } - else if (radioButtonSessionSaveOwn.Checked) - { - Preferences.saveLocation = SessionSaveLocation.OwnDir; - } - else if (radioButtonSessionApplicationStartupDir.Checked) - { - Preferences.saveLocation = SessionSaveLocation.ApplicationStartupDir; - } - else - { - Preferences.saveLocation = SessionSaveLocation.SameDir; - } - - Preferences.saveFilters = checkBoxSaveFilter.Checked; - Preferences.bufferCount = (int)upDownBlockCount.Value; - Preferences.linesPerBuffer = (int)upDownLinesPerBlock.Value; - Preferences.pollingInterval = (int)upDownPollingInterval.Value; - Preferences.multiThreadFilter = checkBoxMultiThread.Checked; - Preferences.defaultEncoding = comboBoxEncoding.SelectedItem != null ? (comboBoxEncoding.SelectedItem as Encoding).HeaderName : Encoding.Default.HeaderName; - Preferences.showColumnFinder = checkBoxColumnFinder.Checked; - Preferences.useLegacyReader = checkBoxLegacyReader.Checked; - - Preferences.maximumFilterEntries = (int)upDownMaximumFilterEntries.Value; - Preferences.maximumFilterEntriesDisplayed = (int)upDownMaximumFilterEntriesDisplayed.Value; - Preferences.ShowErrorMessageAllowOnlyOneInstances = checkBoxShowErrorMessageOnlyOneInstance.Checked; - Preferences.darkMode = checkBoxDarkMode.Checked; - - SavePluginSettings(); - SaveHighlightMaskList(); - GetToolListBoxData(); - SaveMultifileData(); - } - - private void OnBtnToolClick(object sender, EventArgs e) - { - OnBtnToolClickInternal(textBoxTool); - } - - private void OnBtnArgClick(object sender, EventArgs e) - { - OnBtnArgsClickInternal(textBoxArguments); - } - - //TODO Remove or refactor this function - private void OnDataGridViewColumnizerRowsAdded(object sender, DataGridViewRowsAddedEventArgs e) - { - DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridViewColumnizer.Rows[e.RowIndex].Cells[1]; - if (comboCell.Items.Count > 0) - { - // comboCell.Value = comboCell.Items[0]; - } - } - - private void OnBtnDeleteClick(object sender, EventArgs e) - { - if (dataGridViewColumnizer.CurrentRow != null && !dataGridViewColumnizer.CurrentRow.IsNewRow) - { - int index = dataGridViewColumnizer.CurrentRow.Index; - dataGridViewColumnizer.EndEdit(); - dataGridViewColumnizer.Rows.RemoveAt(index); - } - } - - private void OnDataGridViewColumnizerDataError(object sender, DataGridViewDataErrorEventArgs e) - { - e.Cancel = true; - } - - private void OnChkBoxSysoutCheckedChanged(object sender, EventArgs e) - { - comboBoxColumnizer.Enabled = checkBoxSysout.Checked; - } - - private void OnBtnTailColorClick(object sender, EventArgs e) - { - ColorDialog dlg = new() - { - Color = Preferences.showTailColor - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - Preferences.showTailColor = dlg.Color; - } - } - - private void OnChkBoxColumnSizeCheckedChanged(object sender, EventArgs e) - { - cpDownColumnWidth.Enabled = checkBoxColumnSize.Checked; - } - - private void OnBtnTimespreadColorClick(object sender, EventArgs e) - { - ColorDialog dlg = new() - { - Color = Preferences.timeSpreadColor - }; - - if (dlg.ShowDialog() == DialogResult.OK) - { - Preferences.timeSpreadColor = dlg.Color; - } - } - - private void OnListBoxPluginSelectedIndexChanged(object sender, EventArgs e) - { - _selectedPlugin?.HideConfigForm(); - - object o = listBoxPlugin.SelectedItem; - - if (o != null) - { - _selectedPlugin = o as ILogExpertPluginConfigurator; - - if (o is ILogExpertPluginConfigurator) - { - if (_selectedPlugin.HasEmbeddedForm()) - { - buttonConfigPlugin.Enabled = false; - buttonConfigPlugin.Visible = false; - _selectedPlugin.ShowConfigForm(panelPlugin); - } - else - { - buttonConfigPlugin.Enabled = true; - buttonConfigPlugin.Visible = true; - } - } - } - else - { - buttonConfigPlugin.Enabled = false; - buttonConfigPlugin.Visible = true; - } - } - - private void OnBtnSessionSaveDirClick(object sender, EventArgs e) - { - FolderBrowserDialog dlg = new(); - - if (Preferences.sessionSaveDirectory != null) - { - dlg.SelectedPath = Preferences.sessionSaveDirectory; - } - - dlg.ShowNewFolderButton = true; - dlg.Description = @"Choose folder for LogExpert's session files"; - - if (dlg.ShowDialog() == DialogResult.OK) - { - labelSessionSaveOwnDir.Text = dlg.SelectedPath; - } - } - - private void OnPortableModeCheckedChanged(object sender, EventArgs e) - { - try - { - switch (checkBoxPortableMode.CheckState) - { - case CheckState.Checked when !File.Exists(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName): - { - if (Directory.Exists(ConfigManager.PortableModeDir) == false) - { - Directory.CreateDirectory(ConfigManager.PortableModeDir); - } - - using (File.Create(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName)) - { - break; - } - } - case CheckState.Unchecked when File.Exists(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName): - { - File.Delete(ConfigManager.PortableModeDir + Path.DirectorySeparatorChar + ConfigManager.PortableModeSettingsFileName); - break; - } - } - - switch (checkBoxPortableMode.CheckState) - { - case CheckState.Unchecked: - { - checkBoxPortableMode.Text = @"Activate Portable Mode"; - Preferences.PortableMode = false; - break; - } - - case CheckState.Checked: - { - Preferences.PortableMode = true; - checkBoxPortableMode.Text = @"Deactivate Portable Mode"; - break; - } - } - } - catch (Exception exception) - { - MessageBox.Show($@"Could not create / delete marker for Portable Mode: {exception}", @"Error", MessageBoxButtons.OK); - } - - } - - private void OnBtnConfigPluginClick(object sender, EventArgs e) - { - if (!_selectedPlugin.HasEmbeddedForm()) - { - _selectedPlugin.ShowConfigDialog(this); - } - } - - private void OnNumericUpDown1ValueChanged(object sender, EventArgs e) - { - //TODO implement - } - - private void OnListBoxToolSelectedIndexChanged(object sender, EventArgs e) - { - GetCurrentToolValues(); - _selectedTool = listBoxTools.SelectedItem as ToolEntry; - ShowCurrentToolValues(); - listBoxTools.Refresh(); - FillColumnizerForToolsList(); - DisplayCurrentIcon(); - } - - private void OnBtnToolUpClick(object sender, EventArgs e) - { - int i = listBoxTools.SelectedIndex; - - if (i > 0) - { - bool isChecked = listBoxTools.GetItemChecked(i); - object item = listBoxTools.Items[i]; - listBoxTools.Items.RemoveAt(i); - i--; - listBoxTools.Items.Insert(i, item); - listBoxTools.SelectedIndex = i; - listBoxTools.SetItemChecked(i, isChecked); - } - } - - private void OnBtnToolDownClick(object sender, EventArgs e) - { - int i = listBoxTools.SelectedIndex; - - if (i < listBoxTools.Items.Count - 1) - { - bool isChecked = listBoxTools.GetItemChecked(i); - object item = listBoxTools.Items[i]; - listBoxTools.Items.RemoveAt(i); - i++; - listBoxTools.Items.Insert(i, item); - listBoxTools.SelectedIndex = i; - listBoxTools.SetItemChecked(i, isChecked); - } - } - - private void OnBtnToolAddClick(object sender, EventArgs e) - { - listBoxTools.Items.Add(new ToolEntry()); - listBoxTools.SelectedIndex = listBoxTools.Items.Count - 1; - } - - private void OnToolDeleteButtonClick(object sender, EventArgs e) - { - int i = listBoxTools.SelectedIndex; - - if (i < listBoxTools.Items.Count && i >= 0) - { - listBoxTools.Items.RemoveAt(i); - if (i < listBoxTools.Items.Count) - { - listBoxTools.SelectedIndex = i; - } - else - { - if (listBoxTools.Items.Count > 0) - { - listBoxTools.SelectedIndex = listBoxTools.Items.Count - 1; - } - } - } - } - - private void OnBtnIconClick(object sender, EventArgs e) - { - if (_selectedTool != null) - { - string iconFile = _selectedTool.iconFile; - - if (Util.IsNullOrSpaces(iconFile)) - { - iconFile = textBoxTool.Text; - } - - ChooseIconDlg dlg = new(iconFile); - - if (dlg.ShowDialog() == DialogResult.OK) - { - _selectedTool.iconFile = dlg.FileName; - _selectedTool.iconIndex = dlg.IconIndex; - DisplayCurrentIcon(); - } - } - } - - private void OnBtnCancelClick(object sender, EventArgs e) - { - _selectedPlugin?.HideConfigForm(); - } - - private void OnBtnWorkingDirClick(object sender, EventArgs e) - { - OnBtnWorkingDirClick(textBoxWorkingDir); - } - - private void OnMultiFilePatternTextChanged(object sender, EventArgs e) - { - string pattern = textBoxMultifilePattern.Text; - upDownMultifileDays.Enabled = pattern.Contains("$D"); - } - - private void OnBtnExportClick(object sender, EventArgs e) - { - SaveFileDialog dlg = new() - { - Title = @"Export Settings to file", - DefaultExt = "json", - AddExtension = true, - Filter = @"Settings (*.json)|*.json|All files (*.*)|*.*" - }; - - DialogResult result = dlg.ShowDialog(); - - if (result == DialogResult.OK) - { - FileInfo fileInfo = new(dlg.FileName); - ConfigManager.Export(fileInfo); - } - } - - /// - /// - /// - /// - /// - private void OnBtnImportClick(object sender, EventArgs e) - { - ImportSettingsDialog dlg = new(); - - if (dlg.ShowDialog() == DialogResult.OK) - { - if (string.IsNullOrWhiteSpace(dlg.FileName)) - { - return; - } - - FileInfo fileInfo; - try - { - fileInfo = new FileInfo(dlg.FileName); - } - catch (Exception ex) - { - MessageBox.Show(this, $@"Settings could not be imported: {ex}", @"LogExpert"); - return; - } - - ConfigManager.Import(fileInfo, dlg.ImportFlags); - Preferences = ConfigManager.Settings.Preferences; - FillDialog(); - MessageBox.Show(this, @"Settings imported", @"LogExpert"); - } - } - - #endregion - } -} diff --git a/src/LogExpert/Dialogs/TabRenameDlg.Designer.cs b/src/LogExpert/Dialogs/TabRenameDlg.Designer.cs deleted file mode 100644 index 75fd448f..00000000 --- a/src/LogExpert/Dialogs/TabRenameDlg.Designer.cs +++ /dev/null @@ -1,102 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class TabRenameDlg - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.textBoxTabName = new System.Windows.Forms.TextBox(); - this.labelName = new System.Windows.Forms.Label(); - this.buttonOk = new System.Windows.Forms.Button(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // textBoxTabName - // - this.textBoxTabName.Location = new System.Drawing.Point(12, 34); - this.textBoxTabName.Name = "textBoxTabName"; - this.textBoxTabName.Size = new System.Drawing.Size(193, 26); - this.textBoxTabName.TabIndex = 0; - // - // labelName - // - this.labelName.AutoSize = true; - this.labelName.Location = new System.Drawing.Point(13, 11); - this.labelName.Name = "labelName"; - this.labelName.Size = new System.Drawing.Size(55, 20); - this.labelName.TabIndex = 1; - this.labelName.Text = "Name:"; - // - // buttonOk - // - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(49, 73); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 2; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - // - // buttonCancel - // - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(130, 73); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 3; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // TabRenameDlg - // - this.AcceptButton = this.buttonOk; - this.ClientSize = new System.Drawing.Size(219, 108); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.buttonOk); - this.Controls.Add(this.labelName); - this.Controls.Add(this.textBoxTabName); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; - this.KeyPreview = true; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "TabRenameDlg"; - this.ShowIcon = false; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Rename Tab"; - this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.OnTabRenameDlgKeyDown); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.TextBox textBoxTabName; - private System.Windows.Forms.Label labelName; - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Button buttonCancel; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/TabRenameDlg.cs b/src/LogExpert/Dialogs/TabRenameDlg.cs deleted file mode 100644 index 0896cf39..00000000 --- a/src/LogExpert/Dialogs/TabRenameDlg.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class TabRenameDlg : Form - { - #region cTor - - public TabRenameDlg() - { - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - } - - #endregion - - #region Properties - - public string TabName - { - get => textBoxTabName.Text; - set => textBoxTabName.Text = value; - } - - #endregion - - #region Events handler - - private void OnTabRenameDlgKeyDown(object sender, KeyEventArgs e) - { - if (e.KeyCode == Keys.Escape) - { - DialogResult = DialogResult.Cancel; - Close(); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/TimeSpreadigControl.cs b/src/LogExpert/Dialogs/TimeSpreadigControl.cs deleted file mode 100644 index 56a888b4..00000000 --- a/src/LogExpert/Dialogs/TimeSpreadigControl.cs +++ /dev/null @@ -1,298 +0,0 @@ -using LogExpert.Classes; - -using NLog; - -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Dialogs -{ - public partial class TimeSpreadingControl : UserControl - { - private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); - #region Fields - - private Bitmap _bitmap = new(1, 1); - private int _displayHeight = 1; - private readonly int _edgeOffset = (int)Win32.GetSystemMetricsForDpi(Win32.SM_CYVSCROLL); - private int _lastMouseY = 0; - private readonly object _monitor = new(); - private int _rectHeight = 1; - - private TimeSpreadCalculator _timeSpreadCalc; - private readonly ToolTip _toolTip; - - #endregion - - #region cTor - - public TimeSpreadingControl() - { - InitializeComponent(); - _toolTip = new ToolTip(); - Font = new Font("Courier New", 8.25F, FontStyle.Regular, GraphicsUnit.Point, 0); - _toolTip.InitialDelay = 0; - _toolTip.ReshowDelay = 0; - _toolTip.ShowAlways = true; - DoubleBuffered = false; - } - - #endregion - - #region Delegates - - public delegate void LineSelectedEventHandler(object sender, SelectLineEventArgs e); - - #endregion - - #region Events - - public event LineSelectedEventHandler LineSelected; - - #endregion - - #region Properties - - public bool ReverseAlpha { get; set; } - - internal TimeSpreadCalculator TimeSpreadCalc - { - get => _timeSpreadCalc; - set - { - //timeSpreadCalc.CalcDone -= timeSpreadCalc_CalcDone; - _timeSpreadCalc = value; - _timeSpreadCalc.CalcDone += TimeSpreadCalc_CalcDone; - _timeSpreadCalc.StartCalc += TimeSpreadCalc_StartCalc; - } - } - - #endregion - - #region Overrides - - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - lock (_monitor) - { - if (DesignMode) - { - Brush bgBrush = new SolidBrush(Color.FromKnownColor(KnownColor.LightSkyBlue)); - Rectangle rect = ClientRectangle; - rect.Inflate(0, -_edgeOffset); - e.Graphics.FillRectangle(bgBrush, rect); - bgBrush.Dispose(); - } - else - { - e.Graphics.DrawImage(_bitmap, 0, _edgeOffset); - } - } - } - - #endregion - - #region Private Methods - - private TimeSpreadCalculator.SpreadEntry GetEntryForMouse(MouseEventArgs e) - { - List list = TimeSpreadCalc.DiffList; - int y = e.Y - _edgeOffset; - if (y < 0) - { - y = 0; - } - else if (y >= ClientRectangle.Height - _edgeOffset * 3) - { - y = list.Count - 1; - } - else - { - y /= _rectHeight; - } - - lock (_monitor) - { - if (y >= list.Count || y < 0) - { - return null; - } - return list[y]; - } - } - - private void DragContrast(MouseEventArgs e) - { - if (_lastMouseY == 0) - { - _lastMouseY = _lastMouseY = e.Y; - return; - } - _timeSpreadCalc.Contrast += (_lastMouseY - e.Y) * 5; - _lastMouseY = e.Y; - } - - private void OnLineSelected(SelectLineEventArgs e) - { - LineSelected?.Invoke(this, e); - } - - #endregion - - #region Events handler - - private void TimeSpreadCalc_CalcDone(object sender, EventArgs e) - { - _logger.Debug("timeSpreadCalc_CalcDone()"); - lock (_monitor) - { - Invalidate(); - Rectangle rect = ClientRectangle; - rect.Size = new Size(rect.Width, rect.Height - _edgeOffset * 3); - if (rect.Height < 1) - { - return; - } - _bitmap = new Bitmap(rect.Width, rect.Height); - Graphics gfx = Graphics.FromImage(_bitmap); - Brush bgBrush = new SolidBrush(BackColor); - gfx.FillRectangle(bgBrush, rect); - bgBrush.Dispose(); - - List list = TimeSpreadCalc.DiffList; - int step; - if (list.Count >= _displayHeight) - { - step = (int)Math.Round(list.Count / (double)_displayHeight); - _rectHeight = 1; - } - else - { - step = 1; - _rectHeight = (int)Math.Round(_displayHeight / (double)list.Count); - } - Rectangle fillRect = new(0, 0, rect.Width, _rectHeight); - - lock (list) - { - for (int i = 0; i < list.Count; i += step) - { - TimeSpreadCalculator.SpreadEntry entry = list[i]; - int color = ReverseAlpha ? entry.Value : 255 - entry.Value; - if (color > 255) - { - color = 255; - } - if (color < 0) - { - color = 0; - } - Brush brush = new SolidBrush(Color.FromArgb(color, ForeColor)); - //Brush brush = new SolidBrush(Color.FromArgb(color, color, color, color)); - gfx.FillRectangle(brush, fillRect); - brush.Dispose(); - fillRect.Offset(0, _rectHeight); - } - } - } - BeginInvoke(new MethodInvoker(Refresh)); - } - - private void TimeSpreadCalc_StartCalc(object sender, EventArgs e) - { - lock (_monitor) - { - Invalidate(); - Rectangle rect = ClientRectangle; - rect.Size = new Size(rect.Width, rect.Height - _edgeOffset * 3); - if (rect.Height < 1) - { - return; - } - //this.bmp = new Bitmap(rect.Width, rect.Height); - Graphics gfx = Graphics.FromImage(_bitmap); - - Brush bgBrush = new SolidBrush(BackColor); - Brush fgBrush = new SolidBrush(ForeColor); - //gfx.FillRectangle(bgBrush, rect); - - StringFormat format = new(StringFormatFlags.DirectionVertical | StringFormatFlags.NoWrap); - format.LineAlignment = StringAlignment.Center; - format.Alignment = StringAlignment.Center; - - 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)); - } - - private void TimeSpreadingControl_SizeChanged(object sender, EventArgs e) - { - if (TimeSpreadCalc != null) - { - _displayHeight = ClientRectangle.Height - _edgeOffset * 3; - TimeSpreadCalc.SetDisplayHeight(_displayHeight); - } - } - - private void TimeSpreadingControl_MouseDown(object sender, MouseEventArgs e) - { - } - - private void TimeSpreadingControl_MouseUp(object sender, MouseEventArgs e) - { - if (e.Button == MouseButtons.Left) - { - TimeSpreadCalculator.SpreadEntry entry = GetEntryForMouse(e); - if (entry == null) - { - return; - } - OnLineSelected(new SelectLineEventArgs(entry.LineNum)); - } - } - - private void TimeSpreadingControl_MouseEnter(object sender, EventArgs e) - { - _toolTip.Active = true; - } - - private void TimeSpreadingControl_MouseLeave(object sender, EventArgs e) - { - _toolTip.Active = false; - } - - private void TimeSpreadingControl_MouseMove(object sender, MouseEventArgs e) - { - if (e.Y == _lastMouseY) - { - return; - } - - if (e.Button == MouseButtons.Right) - { - DragContrast(e); - return; - } - - TimeSpreadCalculator.SpreadEntry entry = GetEntryForMouse(e); - if (entry == null) - { - return; - } - _lastMouseY = e.Y; - string dts = entry.Timestamp.ToString("dd.MM.yyyy HH:mm:ss"); - _toolTip.SetToolTip(this, "Line " + (entry.LineNum + 1) + "\n" + dts); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ToolArgsDialog.Designer.cs b/src/LogExpert/Dialogs/ToolArgsDialog.Designer.cs deleted file mode 100644 index fc9d4dcd..00000000 --- a/src/LogExpert/Dialogs/ToolArgsDialog.Designer.cs +++ /dev/null @@ -1,151 +0,0 @@ -namespace LogExpert.Dialogs -{ - partial class ToolArgsDialog - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.buttonOk = new System.Windows.Forms.Button(); - this.buttonRegexHelp = new System.Windows.Forms.Button(); - this.textBoxArguments = new System.Windows.Forms.TextBox(); - this.buttonTest = new System.Windows.Forms.Button(); - this.labelEnterArguments = new System.Windows.Forms.Label(); - this.labelHelp = new System.Windows.Forms.Label(); - this.buttonCancel = new System.Windows.Forms.Button(); - this.labelTestResult = new System.Windows.Forms.TextBox(); - this.SuspendLayout(); - // - // buttonOk - // - this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; - this.buttonOk.Location = new System.Drawing.Point(348, 292); - this.buttonOk.Name = "buttonOk"; - this.buttonOk.Size = new System.Drawing.Size(75, 23); - this.buttonOk.TabIndex = 1; - this.buttonOk.Text = "OK"; - this.buttonOk.UseVisualStyleBackColor = true; - this.buttonOk.Click += new System.EventHandler(this.OnButtonOkClick); - // - // buttonRegexHelp - // - this.buttonRegexHelp.Location = new System.Drawing.Point(429, 59); - this.buttonRegexHelp.Name = "buttonRegexHelp"; - this.buttonRegexHelp.Size = new System.Drawing.Size(75, 21); - this.buttonRegexHelp.TabIndex = 2; - this.buttonRegexHelp.Text = "RegEx Help"; - this.buttonRegexHelp.UseVisualStyleBackColor = true; - this.buttonRegexHelp.Click += new System.EventHandler(this.OnButtonRegexHelpClick); - // - // textBoxArguments - // - this.textBoxArguments.Location = new System.Drawing.Point(12, 36); - this.textBoxArguments.Name = "textBoxArguments"; - this.textBoxArguments.Size = new System.Drawing.Size(395, 26); - this.textBoxArguments.TabIndex = 8; - // - // buttonTest - // - this.buttonTest.Location = new System.Drawing.Point(429, 30); - this.buttonTest.Name = "buttonTest"; - this.buttonTest.Size = new System.Drawing.Size(75, 23); - this.buttonTest.TabIndex = 9; - this.buttonTest.Text = "Test"; - this.buttonTest.UseVisualStyleBackColor = true; - this.buttonTest.Click += new System.EventHandler(this.OnButtonTestClick); - // - // labelEnterArguments - // - this.labelEnterArguments.AutoSize = true; - this.labelEnterArguments.Location = new System.Drawing.Point(12, 13); - this.labelEnterArguments.Name = "labelEnterArguments"; - this.labelEnterArguments.Size = new System.Drawing.Size(154, 20); - this.labelEnterArguments.TabIndex = 11; - this.labelEnterArguments.Text = "Enter command line:"; - // - // labelHelp - // - this.labelHelp.Location = new System.Drawing.Point(15, 124); - this.labelHelp.Name = "labelHelp"; - this.labelHelp.Size = new System.Drawing.Size(392, 157); - this.labelHelp.TabIndex = 12; - this.labelHelp.Text = "Help"; - // - // buttonCancel - // - this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.buttonCancel.Location = new System.Drawing.Point(429, 292); - this.buttonCancel.Name = "buttonCancel"; - this.buttonCancel.Size = new System.Drawing.Size(75, 23); - this.buttonCancel.TabIndex = 13; - this.buttonCancel.Text = "Cancel"; - this.buttonCancel.UseVisualStyleBackColor = true; - // - // labelTestResult - // - this.labelTestResult.Location = new System.Drawing.Point(12, 68); - this.labelTestResult.Multiline = true; - this.labelTestResult.Name = "labelTestResult"; - this.labelTestResult.ReadOnly = true; - this.labelTestResult.Size = new System.Drawing.Size(395, 48); - this.labelTestResult.TabIndex = 14; - // - // ToolArgsDialog - // - this.AcceptButton = this.buttonOk; - this.CancelButton = this.buttonCancel; - this.ClientSize = new System.Drawing.Size(516, 327); - this.Controls.Add(this.labelTestResult); - this.Controls.Add(this.buttonCancel); - this.Controls.Add(this.labelHelp); - this.Controls.Add(this.labelEnterArguments); - this.Controls.Add(this.buttonTest); - this.Controls.Add(this.textBoxArguments); - this.Controls.Add(this.buttonRegexHelp); - this.Controls.Add(this.buttonOk); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.MaximizeBox = false; - this.MinimizeBox = false; - this.Name = "ToolArgsDialog"; - this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; - this.Text = "Tool Arguments Help"; - this.Load += new System.EventHandler(this.OnToolArgsDialogLoad); - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button buttonOk; - private System.Windows.Forms.Button buttonRegexHelp; - private System.Windows.Forms.TextBox textBoxArguments; - private System.Windows.Forms.Button buttonTest; - private System.Windows.Forms.Label labelEnterArguments; - private System.Windows.Forms.Label labelHelp; - private System.Windows.Forms.Button buttonCancel; - private System.Windows.Forms.TextBox labelTestResult; - } -} \ No newline at end of file diff --git a/src/LogExpert/Dialogs/ToolArgsDialog.cs b/src/LogExpert/Dialogs/ToolArgsDialog.cs deleted file mode 100644 index e69f0375..00000000 --- a/src/LogExpert/Dialogs/ToolArgsDialog.cs +++ /dev/null @@ -1,100 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using LogExpert.Classes; -using LogExpert.Controls.LogTabWindow; - - -namespace LogExpert.Dialogs -{ - internal partial class ToolArgsDialog : Form - { - #region Fields - - private readonly LogTabWindow logTabWin; - - #endregion - - #region cTor - - public ToolArgsDialog(LogTabWindow logTabWin, Form parent) - { - this.logTabWin = logTabWin; - parent.AddOwnedForm(this); - TopMost = parent.TopMost; - InitializeComponent(); - - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - } - - #endregion - - #region Properties - - public string Arg { get; set; } - - #endregion - - #region Events handler - - private void OnToolArgsDialogLoad(object sender, EventArgs e) - { - labelHelp.Text = "" + - "%L = Current line number\n" + - "%N = Current log file name without path\n" + - "%P = Path (directory) of current log file\n" + - "%F = Full name (incl. path) of log file\n" + - "%E = Extension of log file name (e.g. 'txt')\n" + - "%M = Name of log file without extension\n" + - "%S = User (from URI)\n" + - "%R = Path (from URI)\n" + - "%H = Host (from URI)\n" + - "%T = Port (from URI)\n" + - "?\"\" = variable parameter 'name'\n" + - "?\"\"(def1,def2,...) = variable parameter with predefined values\n" + - "\n" + - "{}{}:\n" + - "Regex search/replace on current selected line."; - - textBoxArguments.Text = Arg; - } - - private void OnButtonRegexHelpClick(object sender, EventArgs e) - { - RegexHelperDialog regexDlg = new(); - if (regexDlg.ShowDialog() == DialogResult.OK) - { - textBoxArguments.SelectedText = regexDlg.Pattern; - } - } - - - private void OnButtonTestClick(object sender, EventArgs e) - { - if (logTabWin.CurrentLogWindow != null) - { - ILogLine line = logTabWin.CurrentLogWindow.GetCurrentLine(); - ILogFileInfo info = logTabWin.CurrentLogWindow.GetCurrentFileInfo(); - if (line != null && info != null) - { - ArgParser parser = new(textBoxArguments.Text); - string args = parser.BuildArgs(line, logTabWin.CurrentLogWindow.GetRealLineNum() + 1, info, - this); - labelTestResult.Text = args; - } - } - } - - private void OnButtonOkClick(object sender, EventArgs e) - { - Arg = textBoxArguments.Text; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/Bookmark.cs b/src/LogExpert/Entities/Bookmark.cs deleted file mode 100644 index 81b4787f..00000000 --- a/src/LogExpert/Entities/Bookmark.cs +++ /dev/null @@ -1,44 +0,0 @@ -using System.Drawing; - -namespace LogExpert.Entities -{ - public class Bookmark - { - #region Fields - - #endregion - - #region cTor - - public Bookmark(int lineNum) - { - LineNum = lineNum; - Text = ""; - Overlay = new BookmarkOverlay(); - } - - public Bookmark(int lineNum, string comment) - { - LineNum = lineNum; - Text = comment; - Overlay = new BookmarkOverlay(); - } - - #endregion - - #region Properties - - public int LineNum { get; set; } - - public string Text { get; set; } - - public BookmarkOverlay Overlay { get; set; } - - /// - /// Position offset of the overlay as set by the user by dragging the overlay with the mouse. - /// - public Size OverlayOffset { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/BookmarkCollection.cs b/src/LogExpert/Entities/BookmarkCollection.cs deleted file mode 100644 index 9ddaf068..00000000 --- a/src/LogExpert/Entities/BookmarkCollection.cs +++ /dev/null @@ -1,24 +0,0 @@ -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace LogExpert.Entities -{ - public class BookmarkCollection : ReadOnlyCollection - { - #region Fields - - private SortedList bookmarkList; - - #endregion - - #region cTor - - internal BookmarkCollection(SortedList bookmarkList) - : base(bookmarkList.Values) - { - this.bookmarkList = bookmarkList; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/BookmarkOverlay.cs b/src/LogExpert/Entities/BookmarkOverlay.cs deleted file mode 100644 index 614b7d6d..00000000 --- a/src/LogExpert/Entities/BookmarkOverlay.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.Drawing; - -namespace LogExpert.Entities -{ - public class BookmarkOverlay - { - #region Fields - - #endregion - - #region Properties - - public Bookmark Bookmark { get; set; } - - public Point Position { get; set; } - - public Rectangle BubbleRect { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/DebugOptions.cs b/src/LogExpert/Entities/DebugOptions.cs deleted file mode 100644 index 683d20e8..00000000 --- a/src/LogExpert/Entities/DebugOptions.cs +++ /dev/null @@ -1,11 +0,0 @@ -namespace LogExpert.Entities -{ - internal class DebugOptions - { - #region Fields - - internal static bool disableWordHighlight = false; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/DefaultLogfileColumnizer.cs b/src/LogExpert/Entities/DefaultLogfileColumnizer.cs deleted file mode 100644 index 6bffc9d2..00000000 --- a/src/LogExpert/Entities/DefaultLogfileColumnizer.cs +++ /dev/null @@ -1,86 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace LogExpert.Entities -{ - public class DefaultLogfileColumnizer : ILogLineColumnizer - { - #region ILogLineColumnizer Members - - public string GetName() - { - return "Default (single line)"; - } - - public string GetDescription() - { - return "No column splitting. The whole line is displayed in a single column."; - } - - public int GetColumnCount() - { - return 1; - } - - public string[] GetColumnNames() - { - return new string[] {"Text"}; - } - - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) - { - ColumnizedLogLine cLogLine = new(); - cLogLine.LogLine = line; - cLogLine.ColumnValues = new IColumn[] - { - new Column - { - FullValue = line.FullLine, - Parent = cLogLine - } - }; - - - return cLogLine; - } - - public string Text - { - get { return GetName(); } - } - - public Priority GetPriority(string fileName, IEnumerable samples) - { - return Priority.CanSupport; - } - #endregion - - #region ILogLineColumnizer Not implemented Members - - public bool IsTimeshiftImplemented() - { - return false; - } - - public void SetTimeOffset(int msecOffset) - { - throw new NotImplementedException(); - } - - public int GetTimeOffset() - { - throw new NotImplementedException(); - } - - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) - { - throw new NotImplementedException(); - } - - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EncodingOptions.cs b/src/LogExpert/Entities/EncodingOptions.cs deleted file mode 100644 index 294a30dc..00000000 --- a/src/LogExpert/Entities/EncodingOptions.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Text; - -namespace LogExpert.Entities -{ - /// - /// Holds some encoding options. - /// - public class EncodingOptions - { - #region Fields - - #endregion - - #region Properties - - /// - /// Sets or gets the Encoding which shall be used when reading a file. A value of null means 'please autodetect' via BOM. - /// - public Encoding Encoding { get; set; } - - /// - /// The Encoding to be used when autodetect cannot be applied (missing BOM). Only used when Encoding is set to null. - /// - public Encoding DefaultEncoding { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/BookmarkEventArgs.cs b/src/LogExpert/Entities/EventArgs/BookmarkEventArgs.cs deleted file mode 100644 index 5ab95516..00000000 --- a/src/LogExpert/Entities/EventArgs/BookmarkEventArgs.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace LogExpert.Entities.EventArgs -{ - public class BookmarkEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region cTor - - public BookmarkEventArgs(Bookmark bookmark) - { - this.Bookmark = bookmark; - } - - #endregion - - #region Properties - - public Bookmark Bookmark { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/ColumnizerEventArgs.cs b/src/LogExpert/Entities/EventArgs/ColumnizerEventArgs.cs deleted file mode 100644 index bea2c285..00000000 --- a/src/LogExpert/Entities/EventArgs/ColumnizerEventArgs.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace LogExpert.Entities.EventArgs -{ - public class ColumnizerEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region cTor - - public ColumnizerEventArgs(ILogLineColumnizer columnizer) - { - this.Columnizer = columnizer; - } - - #endregion - - #region Properties - - public ILogLineColumnizer Columnizer { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/ConfigChangedEventArgs.cs b/src/LogExpert/Entities/EventArgs/ConfigChangedEventArgs.cs deleted file mode 100644 index 6a476cb5..00000000 --- a/src/LogExpert/Entities/EventArgs/ConfigChangedEventArgs.cs +++ /dev/null @@ -1,26 +0,0 @@ -using LogExpert.Config; - -namespace LogExpert.Entities.EventArgs -{ - internal class ConfigChangedEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region cTor - - internal ConfigChangedEventArgs(SettingsFlags changeFlags) - { - Flags = changeFlags; - } - - #endregion - - #region Properties - - public SettingsFlags Flags { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/ContextMenuPluginEventArgs.cs b/src/LogExpert/Entities/EventArgs/ContextMenuPluginEventArgs.cs deleted file mode 100644 index df53d7e0..00000000 --- a/src/LogExpert/Entities/EventArgs/ContextMenuPluginEventArgs.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Generic; - -namespace LogExpert.Entities.EventArgs -{ - public class ContextMenuPluginEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region cTor - - public ContextMenuPluginEventArgs(IContextMenuEntry entry, IList logLines, ILogLineColumnizer columnizer, - ILogExpertCallback callback) - { - this.Entry = entry; - this.LogLines = logLines; - this.Columnizer = columnizer; - this.Callback = callback; - } - - #endregion - - #region Properties - - public IContextMenuEntry Entry { get; } - - public IList LogLines { get; } - - public ILogLineColumnizer Columnizer { get; } - - public ILogExpertCallback Callback { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/CurrentHighlightGroupChangedEventArgs.cs b/src/LogExpert/Entities/EventArgs/CurrentHighlightGroupChangedEventArgs.cs deleted file mode 100644 index b73c2719..00000000 --- a/src/LogExpert/Entities/EventArgs/CurrentHighlightGroupChangedEventArgs.cs +++ /dev/null @@ -1,29 +0,0 @@ -using LogExpert.Controls.LogWindow; - -namespace LogExpert.Entities.EventArgs -{ - internal class CurrentHighlightGroupChangedEventArgs - { - #region Fields - - #endregion - - #region cTor - - public CurrentHighlightGroupChangedEventArgs(LogWindow logWindow, HilightGroup currentGroup) - { - this.LogWindow = logWindow; - this.CurrentGroup = currentGroup; - } - - #endregion - - #region Properties - - public LogWindow LogWindow { get; } - - public HilightGroup CurrentGroup { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/FilterListChangedEventArgs.cs b/src/LogExpert/Entities/EventArgs/FilterListChangedEventArgs.cs deleted file mode 100644 index af23273b..00000000 --- a/src/LogExpert/Entities/EventArgs/FilterListChangedEventArgs.cs +++ /dev/null @@ -1,26 +0,0 @@ -using LogExpert.Controls.LogWindow; - -namespace LogExpert.Entities.EventArgs -{ - internal class FilterListChangedEventArgs - { - #region Fields - - #endregion - - #region cTor - - public FilterListChangedEventArgs(LogWindow logWindow) - { - this.LogWindow = logWindow; - } - - #endregion - - #region Properties - - public LogWindow LogWindow { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/GuiStateArgs.cs b/src/LogExpert/Entities/EventArgs/GuiStateArgs.cs deleted file mode 100644 index cc6a5289..00000000 --- a/src/LogExpert/Entities/EventArgs/GuiStateArgs.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System; -using System.Text; - -namespace LogExpert.Entities.EventArgs -{ - public class GuiStateArgs : System.EventArgs - { - #region Fields - - #endregion - - #region Properties - - public bool TimeshiftEnabled { get; set; } - - public bool FollowTail { get; set; } - - public bool MenuEnabled { get; set; } = true; - - public string TimeshiftText { get; set; } - - public bool TimeshiftPossible { get; set; } = false; - - public bool MultiFileEnabled { get; set; } = true; - - public bool FilterEnabled { get; set; } = true; - - public bool CellSelectMode { get; set; } = false; - - public Encoding CurrentEncoding { get; set; } - - public DateTime Timestamp { get; set; } - - public DateTime MinTimestamp { get; set; } - - public DateTime MaxTimestamp { get; set; } - - public bool ShowBookmarkBubbles { get; set; } - - public bool IsMultiFileActive { get; set; } - - public bool ShowHiddenLines { get; set; } = true; - - public string HighlightGroupName { get; set; } - - public bool ColumnFinderVisible { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/LoadFileEventArgs.cs b/src/LogExpert/Entities/EventArgs/LoadFileEventArgs.cs deleted file mode 100644 index 8cfe3dfe..00000000 --- a/src/LogExpert/Entities/EventArgs/LoadFileEventArgs.cs +++ /dev/null @@ -1,4 +0,0 @@ -namespace LogExpert.Entities.EventArgs -{ - public record LoadFileEventArgs(string FileName, long ReadPos, bool Finished, long FileSize, bool NewFile); -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/PatternArgs.cs b/src/LogExpert/Entities/EventArgs/PatternArgs.cs deleted file mode 100644 index 50eac1f0..00000000 --- a/src/LogExpert/Entities/EventArgs/PatternArgs.cs +++ /dev/null @@ -1,16 +0,0 @@ -namespace LogExpert.Entities.EventArgs -{ - public class PatternArgs - { - #region Fields - - public int endLine = 0; - public int fuzzy = 6; - public int maxDiffInBlock = 5; - public int maxMisses = 5; - public int minWeight = 15; - public int startLine = 0; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/ProgressEventArgs.cs b/src/LogExpert/Entities/EventArgs/ProgressEventArgs.cs deleted file mode 100644 index 85df1780..00000000 --- a/src/LogExpert/Entities/EventArgs/ProgressEventArgs.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace LogExpert.Entities.EventArgs -{ - public class ProgressEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region Properties - - public int Value { get; set; } - - public int MinValue { get; set; } - - public int MaxValue { get; set; } - - public bool Visible { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/StatusEventArgs.cs b/src/LogExpert/Entities/EventArgs/StatusEventArgs.cs deleted file mode 100644 index 08cb79dd..00000000 --- a/src/LogExpert/Entities/EventArgs/StatusEventArgs.cs +++ /dev/null @@ -1,35 +0,0 @@ -namespace LogExpert.Entities.EventArgs -{ - public class StatusLineEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region Properties - - public long FileSize { get; set; } = 0; - - public string StatusText { get; set; } = null; - - public int LineCount { get; set; } = 0; - - public int CurrentLineNum { get; set; } = 0; - - #endregion - - #region Public methods - - public StatusLineEventArgs Clone() - { - StatusLineEventArgs e = new(); - e.StatusText = StatusText; - e.CurrentLineNum = CurrentLineNum; - e.LineCount = LineCount; - e.FileSize = FileSize; - return e; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/EventArgs/SyncModeEventArgs.cs b/src/LogExpert/Entities/EventArgs/SyncModeEventArgs.cs deleted file mode 100644 index 0d65f1ae..00000000 --- a/src/LogExpert/Entities/EventArgs/SyncModeEventArgs.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace LogExpert.Entities.EventArgs -{ - public class SyncModeEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region cTor - - public SyncModeEventArgs(bool isSynced) - { - this.IsTimeSynced = isSynced; - } - - #endregion - - #region Properties - - public bool IsTimeSynced { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/FileViewContext.cs b/src/LogExpert/Entities/FileViewContext.cs deleted file mode 100644 index a0bc2b2a..00000000 --- a/src/LogExpert/Entities/FileViewContext.cs +++ /dev/null @@ -1,29 +0,0 @@ -using LogExpert.Interface; - -namespace LogExpert.Entities -{ - public class FileViewContext - { - #region Fields - - #endregion - - #region cTor - - internal FileViewContext(ILogPaintContext logPaintContext, ILogView logView) - { - this.LogPaintContext = logPaintContext; - this.LogView = logView; - } - - #endregion - - #region Properties - - public ILogPaintContext LogPaintContext { get; } - - public ILogView LogView { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/HilightGroup.cs b/src/LogExpert/Entities/HilightGroup.cs deleted file mode 100644 index b2115103..00000000 --- a/src/LogExpert/Entities/HilightGroup.cs +++ /dev/null @@ -1,34 +0,0 @@ -using LogExpert.Classes.Highlight; - -using System; -using System.Collections.Generic; - -namespace LogExpert.Entities -{ - [Serializable] - public class HilightGroup : ICloneable - { - #region Properties - - public string GroupName { get; set; } = string.Empty; - - public List HilightEntryList { get; set; } = []; - - public object Clone() - { - HilightGroup clone = new() - { - GroupName = GroupName - }; - - foreach (HilightEntry entry in HilightEntryList) - { - clone.HilightEntryList.Add((HilightEntry)entry.Clone()); - } - - return clone; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/LogEventData.cs b/src/LogExpert/Entities/LogEventData.cs deleted file mode 100644 index 3d4f11d1..00000000 --- a/src/LogExpert/Entities/LogEventData.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace LogExpert.Entities -{ - public class LogEventArgs : System.EventArgs - { - #region Fields - - #endregion - - #region Properties - - public int RolloverOffset { get; set; } = 0; - - public bool IsRollover { get; set; } = false; - - public long FileSize { get; set; } - - public int LineCount { get; set; } - - public int PrevLineCount { get; set; } - - public long PrevFileSize { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/LogFileException.cs b/src/LogExpert/Entities/LogFileException.cs deleted file mode 100644 index 4bd1d5c5..00000000 --- a/src/LogExpert/Entities/LogFileException.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System; - -namespace LogExpert.Entities -{ - internal class LogFileException : ApplicationException - { - #region cTor - - internal LogFileException(string msg) - : base(msg) - { - } - - internal LogFileException(string msg, Exception inner) - : base(msg, inner) - { - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/MultifileOptions.cs b/src/LogExpert/Entities/MultifileOptions.cs deleted file mode 100644 index 9abc66a8..00000000 --- a/src/LogExpert/Entities/MultifileOptions.cs +++ /dev/null @@ -1,31 +0,0 @@ -using System; - -namespace LogExpert.Entities -{ - [Serializable] - public class MultiFileOptions - { - #region Fields - - private string _formatPattern = "*$J(.)"; - private int _maxDayTry = 3; - - #endregion - - #region Properties - - public int MaxDayTry - { - get => _maxDayTry; - set => _maxDayTry = value; - } - - public string FormatPattern - { - get => _formatPattern; - set => _formatPattern = value; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/Range.cs b/src/LogExpert/Entities/Range.cs deleted file mode 100644 index b92d243d..00000000 --- a/src/LogExpert/Entities/Range.cs +++ /dev/null @@ -1,31 +0,0 @@ -namespace LogExpert.Entities -{ - internal class Range - { - #region Fields - - #endregion - - #region cTor - - public Range() - { - } - - public Range(int startLine, int endLine) - { - this.StartLine = startLine; - this.EndLine = endLine; - } - - #endregion - - #region Properties - - public int StartLine { get; set; } - - public int EndLine { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/ReloadMemento.cs b/src/LogExpert/Entities/ReloadMemento.cs deleted file mode 100644 index 85037581..00000000 --- a/src/LogExpert/Entities/ReloadMemento.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace LogExpert.Entities -{ - internal class ReloadMemento - { - #region Fields - - internal int currentLine; - internal int firstDisplayedLine; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/RowHeightEntry.cs b/src/LogExpert/Entities/RowHeightEntry.cs deleted file mode 100644 index 4b6291d7..00000000 --- a/src/LogExpert/Entities/RowHeightEntry.cs +++ /dev/null @@ -1,33 +0,0 @@ -namespace LogExpert.Entities -{ - public class RowHeightEntry - { - #region Fields - - #endregion - - #region cTor - - public RowHeightEntry() - { - LineNum = 0; - Height = 0; - } - - public RowHeightEntry(int lineNum, int height) - { - LineNum = lineNum; - Height = height; - } - - #endregion - - #region Properties - - public int LineNum { get; set; } - - public int Height { get; set; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/SearchParams.cs b/src/LogExpert/Entities/SearchParams.cs deleted file mode 100644 index ca79341f..00000000 --- a/src/LogExpert/Entities/SearchParams.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; - -namespace LogExpert.Entities -{ - [Serializable] - public class SearchParams - { - #region Fields - - public int currentLine; - public List historyList = []; - public bool isCaseSensitive = false; - public bool isFindNext; - - public bool isForward = true; - public bool isFromTop = false; - public bool isRegex = false; - - [NonSerialized] public bool isShiftF3Pressed = false; - - public string searchText; - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/WindowFileEntry.cs b/src/LogExpert/Entities/WindowFileEntry.cs deleted file mode 100644 index 604adbec..00000000 --- a/src/LogExpert/Entities/WindowFileEntry.cs +++ /dev/null @@ -1,47 +0,0 @@ -using LogExpert.Controls.LogWindow; - -namespace LogExpert.Entities -{ - /// - /// Represents a log file and its window. Used as a kind of handle for menus or list of open files. - /// - internal class WindowFileEntry - { - #region Fields - - private const int MAX_LEN = 40; - - #endregion - - #region cTor - - public WindowFileEntry(LogWindow logWindow) - { - LogWindow = logWindow; - } - - #endregion - - #region Properties - - public string Title - { - get - { - string title = LogWindow.Text; - if (title.Length > MAX_LEN) - { - title = "..." + title.Substring(title.Length - MAX_LEN); - } - return title; - } - } - - public string FileName => LogWindow.FileName; - - - public LogWindow LogWindow { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Entities/WindowTypes.cs b/src/LogExpert/Entities/WindowTypes.cs deleted file mode 100644 index fa40e9e2..00000000 --- a/src/LogExpert/Entities/WindowTypes.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace LogExpert.Entities -{ - internal enum WindowTypes - { - BookmarkWindow, - LogWindow, - } -} \ No newline at end of file diff --git a/src/LogExpert/Extensions/ComboBoxExtensions.cs b/src/LogExpert/Extensions/ComboBoxExtensions.cs deleted file mode 100644 index b7488e55..00000000 --- a/src/LogExpert/Extensions/ComboBoxExtensions.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System.Windows.Forms; - -namespace LogExpert.Extensions -{ - public static class ComboBoxExtensions - { - /// - public static int GetMaxTextWidth(this ComboBox comboBox) - { - var maxTextWidth = comboBox.Width; - - foreach (var item in comboBox.Items) - { - var textWidthInPixels = TextRenderer.MeasureText(item.ToString(), comboBox.Font).Width; - - if (textWidthInPixels > maxTextWidth) - { - maxTextWidth = textWidthInPixels; - } - } - - return maxTextWidth; - } - } -} diff --git a/src/LogExpert/Extensions/Forms/LineToolStripSeparatorExtension.cs b/src/LogExpert/Extensions/Forms/LineToolStripSeparatorExtension.cs deleted file mode 100644 index a5239c73..00000000 --- a/src/LogExpert/Extensions/Forms/LineToolStripSeparatorExtension.cs +++ /dev/null @@ -1,35 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Extensions.Forms -{ - public class LineToolStripSeparatorExtension : ToolStripSeparator - { - public LineToolStripSeparatorExtension() - { - Paint += OnExtendedToolStripSeparatorPaint; - } - - private void OnExtendedToolStripSeparatorPaint(object sender, PaintEventArgs e) - { - // Get the separator's width and height. - ToolStripSeparator toolStripSeparator = (ToolStripSeparator)sender; - int width = toolStripSeparator.Width; - int height = toolStripSeparator.Height; - - // Choose the colors for drawing. - // I've used Color.White as the foreColor. - Color foreColor = Config.ColorMode.ForeColor; - // Color.Teal as the backColor. - Color backColor = Config.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/Extensions/Forms/MenuSelectedColors.cs b/src/LogExpert/Extensions/Forms/MenuSelectedColors.cs deleted file mode 100644 index 862a84e0..00000000 --- a/src/LogExpert/Extensions/Forms/MenuSelectedColors.cs +++ /dev/null @@ -1,30 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Extensions.Forms -{ - public class MenuSelectedColors : ProfessionalColorTable - { - public override Color ImageMarginGradientBegin => Config.ColorMode.MenuBackgroundColor; - - public override Color ImageMarginGradientMiddle => Config.ColorMode.MenuBackgroundColor; - - public override Color ImageMarginGradientEnd => Config.ColorMode.MenuBackgroundColor; - - public override Color ToolStripDropDownBackground => Config.ColorMode.MenuBackgroundColor; - - public override Color MenuBorder => Config.ColorMode.MenuBackgroundColor; - - public override Color MenuItemBorder => Config.ColorMode.MenuBackgroundColor; - - public override Color MenuItemSelected => Config.ColorMode.HoverMenuBackgroundColor; - - public override Color MenuItemSelectedGradientBegin => Config.ColorMode.HoverMenuBackgroundColor; - - public override Color MenuItemSelectedGradientEnd => Config.ColorMode.HoverMenuBackgroundColor; - - public override Color MenuItemPressedGradientBegin => Config.ColorMode.MenuBackgroundColor; - - public override Color MenuItemPressedGradientEnd => Config.ColorMode.MenuBackgroundColor; - } -} \ No newline at end of file diff --git a/src/LogExpert/Extensions/Forms/MenuStripExtension.cs b/src/LogExpert/Extensions/Forms/MenuStripExtension.cs deleted file mode 100644 index a3865655..00000000 --- a/src/LogExpert/Extensions/Forms/MenuStripExtension.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.Windows.Forms; - -namespace LogExpert.Extensions.Forms -{ - public class ExtendedMenuStripRenderer : ToolStripProfessionalRenderer - { - public ExtendedMenuStripRenderer() : base(new MenuSelectedColors()) { } - } -} diff --git a/src/LogExpert/Extensions/Forms/MenuToolStripSeparatorExtension.cs b/src/LogExpert/Extensions/Forms/MenuToolStripSeparatorExtension.cs deleted file mode 100644 index bf1c666b..00000000 --- a/src/LogExpert/Extensions/Forms/MenuToolStripSeparatorExtension.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace LogExpert.Extensions.Forms -{ - public class MenuToolStripSeparatorExtension : ToolStripSeparator - { - public MenuToolStripSeparatorExtension() - { - Paint += OnExtendedToolStripSeparatorPaint; - } - - private void OnExtendedToolStripSeparatorPaint(object sender, PaintEventArgs e) - { - // Get the separator's width and height. - ToolStripSeparator toolStripSeparator = (ToolStripSeparator)sender; - int width = toolStripSeparator.Width; - int height = toolStripSeparator.Height; - - // Choose the colors for drawing. - // I've used Color.White as the foreColor. - Color foreColor = Config.ColorMode.ForeColor; - // Color.Teal as the backColor. - Color backColor = Config.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/Extensions/Forms/ToolStripRendererExtension.cs b/src/LogExpert/Extensions/Forms/ToolStripRendererExtension.cs deleted file mode 100644 index 6d7f9477..00000000 --- a/src/LogExpert/Extensions/Forms/ToolStripRendererExtension.cs +++ /dev/null @@ -1,15 +0,0 @@ -using System.Windows.Forms; - -namespace LogExpert.Extensions.Forms -{ - public 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); - } - } -} diff --git a/src/LogExpert/Extensions/IEnumerable.cs b/src/LogExpert/Extensions/IEnumerable.cs deleted file mode 100644 index b0a174a8..00000000 --- a/src/LogExpert/Extensions/IEnumerable.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Collections.Generic; -using System.Linq; - -namespace LogExpert.Extensions -{ - public static class Extensions - { - public static bool IsEmpty(this IEnumerable collection) - { - if (collection == null) - { - return true; - } - - return !collection.Any(); - } - - public static bool IsEmpty(this IList list) - { - if (list == null) - { - return true; - } - - return list.Count == 0; - } - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/BackgroundProcessCancelHandler.cs b/src/LogExpert/Interface/BackgroundProcessCancelHandler.cs deleted file mode 100644 index ad41fca0..00000000 --- a/src/LogExpert/Interface/BackgroundProcessCancelHandler.cs +++ /dev/null @@ -1,18 +0,0 @@ -namespace LogExpert.Interface -{ - /// - /// Interface which can register at the LogWindow to be informed of pressing ESC. - /// Used e.g. for cancelling a filter. - /// - public interface BackgroundProcessCancelHandler - { - #region Public methods - - /// - /// Called when ESC was pressed. - /// - void EscapePressed(); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/IBookmarkData.cs b/src/LogExpert/Interface/IBookmarkData.cs deleted file mode 100644 index 2e45d796..00000000 --- a/src/LogExpert/Interface/IBookmarkData.cs +++ /dev/null @@ -1,22 +0,0 @@ -using LogExpert.Entities; - -namespace LogExpert.Interface -{ - public interface IBookmarkData - { - #region Properties - - BookmarkCollection Bookmarks { get; } - - #endregion - - #region Public methods - - void ToggleBookmark(int lineNum); - bool IsBookmarkAtLine(int lineNum); - int GetBookmarkIndexForLine(int lineNum); - Bookmark GetBookmarkForLine(int lineNum); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/IBookmarkView.cs b/src/LogExpert/Interface/IBookmarkView.cs deleted file mode 100644 index 2a5884c9..00000000 --- a/src/LogExpert/Interface/IBookmarkView.cs +++ /dev/null @@ -1,25 +0,0 @@ -using LogExpert.Entities; - -namespace LogExpert.Interface -{ - /// - /// To be implemented by the bookmark window. Will be informed from LogWindow about changes in bookmarks. - /// - internal interface IBookmarkView - { - #region Properties - - bool LineColumnVisible { set; } - - #endregion - - #region Public methods - - void UpdateView(); - void BookmarkTextChanged(Bookmark bookmark); - void SelectBookmark(int lineNum); - void SetBookmarkData(IBookmarkData bookmarkData); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/ILogExpertProxy.cs b/src/LogExpert/Interface/ILogExpertProxy.cs deleted file mode 100644 index e9e0554f..00000000 --- a/src/LogExpert/Interface/ILogExpertProxy.cs +++ /dev/null @@ -1,41 +0,0 @@ -using LogExpert.Controls.LogTabWindow; -using LogExpert.Grpc; - -namespace LogExpert.Interface -{ - internal interface ILogExpertProxy - { - #region Public methods - - /// - /// Load the given files into the existing window. - /// - /// - void LoadFiles(string[] fileNames); - - /// - /// Open a new LogExpert window and load the given files. - /// - /// - void NewWindow(string[] fileNames); - - /// - /// load given files into the locked window or open a new window if no window is locked. - /// - /// - void NewWindowOrLockedWindow(string[] fileNames); - - - /// - /// Called from LogTabWindow when the window is about to be closed. - /// - /// - void WindowClosed(LogTabWindow logWin); - - int GetLogWindowCount(); - - #endregion - - //void BroadcastSettingsChanged(Object cookie); - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/ILogPaintContext.cs b/src/LogExpert/Interface/ILogPaintContext.cs deleted file mode 100644 index 367d4ff1..00000000 --- a/src/LogExpert/Interface/ILogPaintContext.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Collections.Generic; -using System.Drawing; -using LogExpert.Classes.Highlight; -using LogExpert.Entities; - -namespace LogExpert.Interface -{ - /// - /// Declares methods that are needed for drawing log lines. Used by PaintHelper. - /// - public interface ILogPaintContext - { - #region Properties - - Font MonospacedFont { get; } // Font font = new Font("Courier New", this.Preferences.fontSize, FontStyle.Bold); - Font NormalFont { get; } - Font BoldFont { get; } - Color BookmarkColor { get; } - - #endregion - - #region Public methods - - ILogLine GetLogLine(int lineNum); - - IColumn GetCellValue(int rowIndex, int columnIndex); - - Bookmark GetBookmarkForLine(int lineNum); - - HilightEntry FindHighlightEntry(ITextValue line, bool noWordMatches); - - IList FindHighlightMatches(ITextValue line); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/ILogStreamReader.cs b/src/LogExpert/Interface/ILogStreamReader.cs deleted file mode 100644 index b443d14f..00000000 --- a/src/LogExpert/Interface/ILogStreamReader.cs +++ /dev/null @@ -1,25 +0,0 @@ -using System; -using System.Text; - -namespace LogExpert.Interface -{ - public interface ILogStreamReader : IDisposable - { - #region Properties - - long Position { get; set; } - - bool IsBufferComplete { get; } - - Encoding Encoding { get; } - - #endregion - - #region Public methods - - int ReadChar(); - string ReadLine(); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/ILogView.cs b/src/LogExpert/Interface/ILogView.cs deleted file mode 100644 index 6af02b3f..00000000 --- a/src/LogExpert/Interface/ILogView.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System.Collections.Generic; - -namespace LogExpert.Interface -{ - /// - /// Methods to control the LogWindow from other views. - /// - public interface ILogView - { - #region Properties - - ILogLineColumnizer CurrentColumnizer { get; } - string FileName { get; } - - #endregion - - #region Public methods - - void SelectLogLine(int lineNumber); - void SelectAndEnsureVisible(int line, bool triggerSyncCall); - void RefreshLogView(); - void DeleteBookmarks(List lineNumList); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/Interface/ISharedToolWindow.cs b/src/LogExpert/Interface/ISharedToolWindow.cs deleted file mode 100644 index 2986d687..00000000 --- a/src/LogExpert/Interface/ISharedToolWindow.cs +++ /dev/null @@ -1,32 +0,0 @@ -using LogExpert.Config; -using LogExpert.Entities; - -namespace LogExpert.Interface -{ - /// - /// Interface to be implemented by tools windows that are shared across multiple log files. - /// The implementor will be called whenever the current log file changes. So it can draw new content - /// according to the current active log file. - /// - internal interface ISharedToolWindow - { - #region Public methods - - /// - /// Called when a file becomes the active file (e.g. when user selects a tab). - /// - /// - void SetCurrentFile(FileViewContext ctx); - - /// - /// Called whenever the current file has been changed. - /// - void FileChanged(); - - void SetColumnizer(ILogLineColumnizer columnizer); - - void PreferencesChanged(Preferences newPreferences, bool isLoadTime, SettingsFlags flags); - - #endregion - } -} \ No newline at end of file diff --git a/src/LogExpert/LogExpert.csproj b/src/LogExpert/LogExpert.csproj index c4be38e4..20ea2108 100644 --- a/src/LogExpert/LogExpert.csproj +++ b/src/LogExpert/LogExpert.csproj @@ -1,68 +1,19 @@  - net8.0-windows - true - WinExe - Resources\logexpert.ico - false - true - true + PerMonitorV2 + logexpert.ico + True $(SolutionDir)..\bin\Docs\LogExpert.xml - false - true + True + True Auto - true - ..\Solution Items\Key.snk - false $(SolutionDir)..\bin\$(Configuration) - true - PerMonitorV2 - true - CS1591; - - - False - - - True + WinExe + net8.0-windows + False + - - Properties\AssemblyVersion.cs - - - Component - - - UserControl - - - UserControl - - - UserControl - - - Component - - - Component - - - Component - - - Component - - - PublicResXFileCodeGenerator - True - True - Resources.resx - - - Key.snk - Always @@ -71,32 +22,20 @@ Always - - Always - + - - - - - - - + + + - - - PublicResXFileCodeGenerator - Resources.Designer.cs - - diff --git a/src/LogExpert/Program.cs b/src/LogExpert/Program.cs index 5f7c6abb..53d6678a 100644 --- a/src/LogExpert/Program.cs +++ b/src/LogExpert/Program.cs @@ -1,98 +1,71 @@ -using Grpc.Core; -using Grpc.Net.Client; - using LogExpert.Classes; +using LogExpert.Classes.CommandLine; using LogExpert.Config; -using LogExpert.Controls.LogTabWindow; +using LogExpert.Core.Classes.IPC; +using LogExpert.Core.Config; +using LogExpert.Core.Interface; using LogExpert.Dialogs; +using LogExpert.UI.Controls.LogWindow; +using LogExpert.UI.Dialogs; +using LogExpert.UI.Extensions.LogWindow; -using LogexpertGRPCService.Services; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using NLog; -using System; -using System.Collections.Generic; using System.Diagnostics; -using System.IO; +using System.Globalization; +using System.IO.Pipes; using System.Reflection; using System.Security; using System.Security.Principal; -using System.Threading; +using System.Text; using System.Windows.Forms; -namespace LogExpert +namespace LogExpert; + +internal static class Program { - internal static class Program - { - #region Fields - private static readonly ILogger _logger = LogManager.GetLogger("Program"); - #endregion + #region Fields - #region Private Methods + private static readonly Logger _logger = LogManager.GetLogger("Program"); + private const string PIPE_SERVER_NAME = "LogExpert_IPC"; + private const int PIPE_CONNECTION_TIMEOUT_IN_MS = 5000; - /// - /// The main entry point for the application. - /// - [STAThread] - private static void Main(string[] orgArgs) - { - try - { - var server = new Server() - { - Services = { Grpc.LogExpertService.BindService(new LogExpertServiceImpl()) }, - Ports = { new ServerPort("localhost", 5001, ServerCredentials.Insecure) } - }; + #endregion - Sub_Main(server, orgArgs); - } - catch (SecurityException se) - { - MessageBox.Show("Insufficient system rights for LogExpert. Maybe you have started it from a network drive. Please start LogExpert from a local drive.\n(" + se.Message + ")", "LogExpert Error"); - } - } + #region Private Methods - private static void Sub_Main(Server server, string[] orgArgs) - { - AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; - Application.ThreadException += Application_ThreadException; - ApplicationConfiguration.Initialize(); + /// + /// The main entry point for the application. + /// + [STAThread] + private static void Main(string[] args) + { + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + Application.ThreadException += Application_ThreadException; - Application.EnableVisualStyles(); - Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); + ApplicationConfiguration.Initialize(); - _logger.Info("\r\n============================================================================\r\nLogExpert {0} started.\r\n============================================================================", Assembly.GetExecutingAssembly().GetName().Version.ToString(3)); + Application.EnableVisualStyles(); + Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); - CmdLine cmdLine = new(); + _logger.Info(CultureInfo.InvariantCulture, $"\r\n============================================================================\r\nLogExpert {Assembly.GetExecutingAssembly().GetName().Version.ToString(3)} started.\r\n============================================================================"); + + CancellationTokenSource cts = new(); + try + { CmdLineString configFile = new("config", false, "A configuration (settings) file"); + CmdLine cmdLine = new(); cmdLine.RegisterParameter(configFile); - string[] remainingArgs = cmdLine.Parse(orgArgs); - - List argsList = []; - - // This loop tries to convert relative file names into absolute file names (assuming that platform file names are given). - // It tolerates errors, to give file system plugins (e.g. sftp) a change later. - // TODO: possibly should be moved to LocalFileSystem plugin - foreach (string fileArg in remainingArgs) - { - try - { - FileInfo info = new(fileArg); - argsList.Add(info.Exists ? info.FullName : fileArg); - } - catch (Exception) - { - argsList.Add(fileArg); - } - } - string[] args = [.. argsList]; if (configFile.Exists) { FileInfo cfgFileInfo = new(configFile.Value); - + //TODO: The config file import and the try catch for the primary instance and secondary instance should be separated functions if (cfgFileInfo.Exists) { - ConfigManager.Import(cfgFileInfo, ExportImportFlags.All); + ConfigManager.Instance.Import(cfgFileInfo, ExportImportFlags.All); } else { @@ -100,65 +73,45 @@ private static void Sub_Main(Server server, string[] orgArgs) } } - int pId = Process.GetCurrentProcess().SessionId; + PluginRegistry.PluginRegistry.Instance.Create(ConfigManager.Instance.ConfigDir, ConfigManager.Instance.Settings.Preferences.PollingInterval); + + var pId = Process.GetCurrentProcess().SessionId; try { - Settings settings = ConfigManager.Settings; - Mutex mutex = new(false, "Local\\LogExpertInstanceMutex" + pId, out var isCreated); + var remainingArgs = cmdLine.Parse(args); + var absoluteFilePaths = GenerateAbsoluteFilePaths(remainingArgs); if (isCreated) { // first application instance Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); - LogTabWindow logWin = new(args.Length > 0 ? args : null, 1, false); + var logWin = AbstractLogTabWindow.Create(absoluteFilePaths.Length > 0 ? absoluteFilePaths : null, 1, false, ConfigManager.Instance); // first instance - WindowsIdentity wi = WindowsIdentity.GetCurrent(); - - server.Start(); - - //IpcServerChannel ipcChannel = new IpcServerChannel("LogExpert" + pId); - //ChannelServices.RegisterChannel(ipcChannel, false); - //RemotingConfiguration.RegisterWellKnownServiceType(typeof(LogExpertProxy), "LogExpertProxy", WellKnownObjectMode.Singleton); + var wi = WindowsIdentity.GetCurrent(); LogExpertProxy proxy = new(logWin); - //RemotingServices.Marshal(proxy, "LogExpertProxy"); - LogExpertApplicationContext context = new(proxy, logWin); - Application.Run(context); - //ChannelServices.UnregisterChannel(ipcChannel); - server.ShutdownAsync().Wait(); + Task.Run(() => RunServerLoopAsync(SendMessageToProxy, proxy, cts.Token)); + + Application.Run(context); } else { - int counter = 3; + var counter = 3; Exception errMsg = null; - //IpcClientChannel ipcChannel = new IpcClientChannel("LogExpertClient#" + pId, null); - //ChannelServices.RegisterChannel(ipcChannel, false); + Settings settings = ConfigManager.Instance.Settings; while (counter > 0) { try { - using var channel = GrpcChannel.ForAddress("https://localhost:5001"); - var client = new Grpc.LogExpertService.LogExpertServiceClient(channel); - - //Console.WriteLine("Greeting: " + reply.Result); - // another instance already exists - WindowsIdentity wi = WindowsIdentity.GetCurrent(); - //LogExpertProxy proxy = (LogExpertProxy)Activator.GetObject(typeof(LogExpertProxy), "ipc://LogExpert" + pId + "/LogExpertProxy"); - if (settings.Preferences.allowOnlyOneInstance) - { - client.LoadFiles(new Grpc.FileNames { FileNames_ = { args } }); - } - else - { - client.NewWindowOrLockedWindow(new Grpc.FileNames { FileNames_ = { args } }); - } - + var wi = WindowsIdentity.GetCurrent(); + var command = SerializeCommandIntoNonFormattedJSON(absoluteFilePaths, settings.Preferences.AllowOnlyOneInstance); + SendCommandToServer(command); break; } catch (Exception e) @@ -176,81 +129,225 @@ private static void Sub_Main(Server server, string[] orgArgs) MessageBox.Show($"Cannot open connection to first instance ({errMsg})", "LogExpert"); } - if (settings.Preferences.allowOnlyOneInstance && settings.Preferences.ShowErrorMessageAllowOnlyOneInstances) + //TODO: Remove this from here? Why is it called from the Main project and not from the main window? + if (settings.Preferences.AllowOnlyOneInstance && settings.Preferences.ShowErrorMessageAllowOnlyOneInstances) { AllowOnlyOneInstanceErrorDialog a = new(); if (a.ShowDialog() == DialogResult.OK) { settings.Preferences.ShowErrorMessageAllowOnlyOneInstances = !a.DoNotShowThisMessageAgain; - ConfigManager.Save(SettingsFlags.All); + ConfigManager.Instance.Save(SettingsFlags.All); } - - //MessageBox.Show($"Only one instance allowed, uncheck \"View Settings => Allow only 1 Instances\" to start multiple instances!", "Logexpert"); } } mutex.Close(); + cts.Cancel(); } catch (Exception ex) { _logger.Error(ex, "Mutex error, giving up: "); + cts.Cancel(); MessageBox.Show($"Cannot open connection to first instance ({ex.Message})", "LogExpert"); } } + catch (SecurityException se) + { + MessageBox.Show("Insufficient system rights for LogExpert. Maybe you have started it from a network drive. Please start LogExpert from a local drive.\n(" + se.Message + ")", "LogExpert Error"); + cts.Cancel(); + } + } + + private static string SerializeCommandIntoNonFormattedJSON(string[] fileNames, bool allowOnlyOneInstance) + { + var message = new IpcMessage() + { + Type = allowOnlyOneInstance ? IpcMessageType.NewWindowOrLockedWindow : IpcMessageType.NewWindow, + Payload = JObject.FromObject(new LoadPayload { Files = [.. fileNames] }) + }; + + return JsonConvert.SerializeObject(message, Formatting.None); + } + + // This loop tries to convert relative file names into absolute file names (assuming that platform file names are given). + // It tolerates errors, to give file system plugins (e.g. sftp) a change later. + // TODO: possibly should be moved to LocalFileSystem plugin + private static string[] GenerateAbsoluteFilePaths(string[] remainingArgs) + { + List argsList = []; - [STAThread] - private static void ShowUnhandledException(object exceptionObject) + foreach (var fileArg in remainingArgs) { - string errorText = string.Empty; - string stackTrace = string.Empty; - if (exceptionObject is Exception exception) + try { - errorText = exception.Message; - stackTrace = "\r\n" + exception.GetType().Name + "\r\n" + - exception.StackTrace; + FileInfo info = new(fileArg); + argsList.Add(info.Exists ? info.FullName : fileArg); } - else + catch (Exception) { - stackTrace = exceptionObject.ToString(); - string[] lines = stackTrace.Split('\n'); - if (lines != null && lines.Length > 0) - { - errorText = lines[0]; - } + argsList.Add(fileArg); } - ExceptionWindow win = new(errorText, stackTrace); - _ = win.ShowDialog(); } - #endregion + return [.. argsList]; + } - #region Events handler + private static void SendMessageToProxy(IpcMessage message, LogExpertProxy proxy) + { + var payLoad = message.Payload.ToObject(); - private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) + if (CheckPayload(payLoad)) { - _logger.Fatal(e); - - //ShowUnhandledException(e.Exception); - Thread thread = new(ShowUnhandledException); - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(e.Exception); - thread.Join(); + switch (message.Type) + { + case IpcMessageType.Load: + proxy.LoadFiles([.. payLoad.Files]); + break; + case IpcMessageType.NewWindow: + proxy.NewWindow([.. payLoad.Files]); + break; + case IpcMessageType.NewWindowOrLockedWindow: + proxy.NewWindowOrLockedWindow([.. payLoad.Files]); + break; + default: + _logger.Error($"Unknown IPC Message Type: {message.Type}; with payload: {payLoad}"); + break; + } } + } - private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + private static bool CheckPayload (LoadPayload payLoad) + { + if (payLoad == null) { - _logger.Fatal(e); - - object exceptionObject = e.ExceptionObject; - //ShowUnhandledException(exceptionObject); - Thread thread = new(ShowUnhandledException); - thread.IsBackground = true; - thread.SetApartmentState(ApartmentState.STA); - thread.Start(exceptionObject); - thread.Join(); + _logger.Error("Invalid payload command: null"); + return false; } - #endregion + return true; } + + private static void SendCommandToServer(string command) + { + using var client = new NamedPipeClientStream(".", PIPE_SERVER_NAME, PipeDirection.Out); + + try + { + client.Connect(PIPE_CONNECTION_TIMEOUT_IN_MS); + } + catch (TimeoutException) + { + _logger.Error("Timeout connecting to pipe server"); + return; + } + catch (IOException ex) + { + _logger.Warn(ex, "An I/O error occurred while connecting to the pipe server."); + return; + } + catch (UnauthorizedAccessException ex) + { + _logger.Warn(ex, "Unauthorized access while connecting to the pipe server."); + return; + } + + using var writer = new StreamWriter(client, Encoding.UTF8) { AutoFlush = true }; + writer.WriteLine(command); + } + + private static async Task RunServerLoopAsync(Action onCommand, LogExpertProxy proxy, CancellationToken cancellationToken) + { + while (cancellationToken.IsCancellationRequested == false) + { + using var server = new NamedPipeServerStream( + PIPE_SERVER_NAME, + PipeDirection.In, + 1, + PipeTransmissionMode.Message, + PipeOptions.Asynchronous); + + try + { + await server.WaitForConnectionAsync(cancellationToken); + using var reader = new StreamReader(server, Encoding.UTF8); + var line = await reader.ReadLineAsync(cancellationToken); + + if (line != null) + { + var message = JsonConvert.DeserializeObject(line); + onCommand(message, proxy); + } + } + catch (OperationCanceledException) + { + break; + } + catch (Exception ex) + { + _logger.Warn(ex, "Pipe server error"); + } + } + } + + [STAThread] + private static void ShowUnhandledException(object exceptionObject) + { + var errorText = string.Empty; + string stackTrace; + + if (exceptionObject is Exception exception) + { + errorText = exception.Message; + stackTrace = $"\r\n{exception.GetType().Name}\r\n{exception.StackTrace}"; + } + else + { + stackTrace = exceptionObject.ToString(); + var lines = stackTrace.Split('\n'); + + if (lines != null && lines.Length > 0) + { + errorText = lines[0]; + } + } + + ExceptionWindow win = new(errorText, stackTrace); + _ = win.ShowDialog(); + } + + #endregion + + #region Events handler + + private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) + { + _logger.Fatal(e); + + Thread thread = new(ShowUnhandledException) + { + IsBackground = true + }; + + thread.SetApartmentState(ApartmentState.STA); + thread.Start(e.Exception); + thread.Join(); + } + + private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + _logger.Fatal(e); + + var exceptionObject = e.ExceptionObject; + + Thread thread = new(ShowUnhandledException) + { + IsBackground = true + }; + + thread.SetApartmentState(ApartmentState.STA); + thread.Start(exceptionObject); + thread.Join(); + } + + #endregion } diff --git a/src/LogExpert/Properties/AssemblyInfo.cs b/src/LogExpert/Properties/AssemblyInfo.cs deleted file mode 100644 index 69e5aee9..00000000 --- a/src/LogExpert/Properties/AssemblyInfo.cs +++ /dev/null @@ -1 +0,0 @@ -[assembly: System.Runtime.Versioning.SupportedOSPlatform("windows")] \ No newline at end of file diff --git a/src/LogExpert/Properties/Settings.Designer.cs b/src/LogExpert/Properties/Settings.Designer.cs deleted file mode 100644 index 6f26ca6e..00000000 --- a/src/LogExpert/Properties/Settings.Designer.cs +++ /dev/null @@ -1,26 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace LogExpert.Properties { - - - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.8.0.0")] - internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { - - private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); - - public static Settings Default { - get { - return defaultInstance; - } - } - } -} diff --git a/src/LogExpert/Properties/Settings.settings b/src/LogExpert/Properties/Settings.settings deleted file mode 100644 index eeb7df06..00000000 --- a/src/LogExpert/Properties/Settings.settings +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/src/LogExpert/Resources/AdvancedIcon.bmp b/src/LogExpert/Resources/AdvancedIcon.bmp deleted file mode 100644 index efe15320..00000000 Binary files a/src/LogExpert/Resources/AdvancedIcon.bmp and /dev/null differ diff --git a/src/LogExpert/Resources/AdvancedIcon2.gif b/src/LogExpert/Resources/AdvancedIcon2.gif deleted file mode 100644 index cf300683..00000000 Binary files a/src/LogExpert/Resources/AdvancedIcon2.gif and /dev/null differ diff --git a/src/LogExpert/Resources/LogExpert-Logo.png b/src/LogExpert/Resources/LogExpert-Logo.png deleted file mode 100644 index b94e7cfd..00000000 Binary files a/src/LogExpert/Resources/LogExpert-Logo.png and /dev/null differ diff --git a/src/LogExpert/Resources/Log_Icon.png b/src/LogExpert/Resources/Log_Icon.png deleted file mode 100644 index a1774717..00000000 Binary files a/src/LogExpert/Resources/Log_Icon.png and /dev/null differ diff --git a/src/LogExpert/Resources/Log_Icon_small.png b/src/LogExpert/Resources/Log_Icon_small.png deleted file mode 100644 index 864bd7f3..00000000 Binary files a/src/LogExpert/Resources/Log_Icon_small.png and /dev/null differ diff --git a/src/LogExpert/Resources/PanelClose.gif b/src/LogExpert/Resources/PanelClose.gif deleted file mode 100644 index 41615c3d..00000000 Binary files a/src/LogExpert/Resources/PanelClose.gif and /dev/null differ diff --git a/src/LogExpert/Resources/PanelOpen.gif b/src/LogExpert/Resources/PanelOpen.gif deleted file mode 100644 index a826a94c..00000000 Binary files a/src/LogExpert/Resources/PanelOpen.gif and /dev/null differ diff --git a/src/LogExpert/Resources/check-blue.gif b/src/LogExpert/Resources/check-blue.gif deleted file mode 100644 index 0b2bcc66..00000000 Binary files a/src/LogExpert/Resources/check-blue.gif and /dev/null differ diff --git a/src/LogExpert/Resources/delete-page-red.gif b/src/LogExpert/Resources/delete-page-red.gif deleted file mode 100644 index 21a08dce..00000000 Binary files a/src/LogExpert/Resources/delete-page-red.gif and /dev/null differ diff --git a/src/LogExpert/Resources/down-blue.gif b/src/LogExpert/Resources/down-blue.gif deleted file mode 100644 index 7304e2f8..00000000 Binary files a/src/LogExpert/Resources/down-blue.gif and /dev/null differ diff --git a/src/LogExpert/Resources/folder-blue.gif b/src/LogExpert/Resources/folder-blue.gif deleted file mode 100644 index 4c92bf71..00000000 Binary files a/src/LogExpert/Resources/folder-blue.gif and /dev/null differ diff --git a/src/LogExpert/Resources/search-blue.gif b/src/LogExpert/Resources/search-blue.gif deleted file mode 100644 index 29b42ea1..00000000 Binary files a/src/LogExpert/Resources/search-blue.gif and /dev/null differ diff --git a/src/LogExpert/Resources/search-folder-blue.gif b/src/LogExpert/Resources/search-folder-blue.gif deleted file mode 100644 index 363fdea1..00000000 Binary files a/src/LogExpert/Resources/search-folder-blue.gif and /dev/null differ diff --git a/src/LogExpert/Resources/up-blue.gif b/src/LogExpert/Resources/up-blue.gif deleted file mode 100644 index 0d785f38..00000000 Binary files a/src/LogExpert/Resources/up-blue.gif and /dev/null differ diff --git a/src/LogExpert/gRPC/LogExpert.proto b/src/LogExpert/gRPC/LogExpert.proto deleted file mode 100644 index 3a082a08..00000000 --- a/src/LogExpert/gRPC/LogExpert.proto +++ /dev/null @@ -1,45 +0,0 @@ -syntax = "proto3"; - -option csharp_namespace = "LogExpert.Grpc"; - -package logexpert; - -// The log service definition. -service LogExpertService { - // Sends a log message - rpc SendLog (LogRequest) returns (LogReply) {} - rpc LoadFiles (FileNames); - rpc NewWindow (FileNames); - rpc NewWindowOrLockedWindow (FileNames); - rpc WindowClosed(); - rpc GetLogWindowCount() returns (Count); -} - -message FileNames -{ - repeated string FileNames = 4; -} - -message Count -{ - int32 count = 0; -} - -message FilesReply -{ - bool success = false; -} - -// The request message containing the log message. -message LogRequest -{ - string message = 1; -} - -message LoadFiles(repeated ) - -// The response message containing the response. -message LogReply -{ - string result = 1; -} \ No newline at end of file diff --git a/src/LogExpert/logexpert.ico b/src/LogExpert/logexpert.ico new file mode 100644 index 00000000..d616d1e3 Binary files /dev/null and b/src/LogExpert/logexpert.ico differ diff --git a/src/LogexpertgRPCService/LogexpertgRPCService.csproj b/src/LogexpertgRPCService/LogexpertgRPCService.csproj deleted file mode 100644 index a5d0b2bf..00000000 --- a/src/LogexpertgRPCService/LogexpertgRPCService.csproj +++ /dev/null @@ -1,18 +0,0 @@ - - - net8.0 - enable - false - enable - - - true - ..\Solution Items\Key.snk - - - - - - - - \ No newline at end of file diff --git a/src/LogexpertgRPCService/Program.cs b/src/LogexpertgRPCService/Program.cs deleted file mode 100644 index 7ecdb775..00000000 --- a/src/LogexpertgRPCService/Program.cs +++ /dev/null @@ -1,14 +0,0 @@ -using LogexpertGRPCService.Services; - -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. -builder.Services.AddGrpc(); - -var app = builder.Build(); - -// Configure the HTTP request pipeline. -app.MapGrpcService(); -app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909"); - -app.Run(); diff --git a/src/LogexpertgRPCService/Properties/launchSettings.json b/src/LogexpertgRPCService/Properties/launchSettings.json deleted file mode 100644 index 25ca2150..00000000 --- a/src/LogexpertgRPCService/Properties/launchSettings.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "$schema": "http://json.schemastore.org/launchsettings.json", - "profiles": { - "http": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": false, - "applicationUrl": "http://localhost:5282", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "https": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": false, - "applicationUrl": "https://localhost:7125;http://localhost:5282", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/src/LogexpertgRPCService/Protos/Logexpert.proto b/src/LogexpertgRPCService/Protos/Logexpert.proto deleted file mode 100644 index 838357a7..00000000 --- a/src/LogexpertgRPCService/Protos/Logexpert.proto +++ /dev/null @@ -1,47 +0,0 @@ -syntax = "proto3"; - -option csharp_namespace = "LogExpert.Grpc"; - -import "google/protobuf/empty.proto"; - -package logexpert; - -// The log service definition. -service LogExpertService -{ - // Sends a log message - rpc SendLog (LogRequest) returns (LogReply) ; - rpc LoadFiles (FileNames) returns (FilesReply); - rpc NewWindow (FileNames) returns (FilesReply); - rpc NewWindowOrLockedWindow (FileNames) returns (FilesReply); - //is this really needed? - rpc WindowClosed(google.protobuf.Empty) returns (google.protobuf.Empty); - rpc GetLogWindowCount(google.protobuf.Empty) returns (Count); -} - -message FileNames -{ - repeated string fileNames = 1; -} - -message Count -{ - int32 count = 1; -} - -message FilesReply -{ - bool success = 1; -} - -// The request message containing the log message. -message LogRequest -{ - string message = 1; -} - -// The response message containing the response. -message LogReply -{ - string result = 1; -} \ No newline at end of file diff --git a/src/LogexpertgRPCService/Services/LogExpertServiceImpl.cs b/src/LogexpertgRPCService/Services/LogExpertServiceImpl.cs deleted file mode 100644 index 86a237d4..00000000 --- a/src/LogexpertgRPCService/Services/LogExpertServiceImpl.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Grpc.Core; - -using LogExpert.Grpc; - -namespace LogexpertGRPCService.Services -{ - public class LogExpertServiceImpl : LogExpertService.LogExpertServiceBase - { - public override Task SendLog(LogRequest request, ServerCallContext context) - { - return Task.FromResult(new LogReply { Result = "Hello " + request.Message }); - } - - public override Task LoadFiles(FileNames fileNames, ServerCallContext context) - { - return Task.FromResult(new FilesReply { Success = true }); - } - - public override Task NewWindow(FileNames fileNames, ServerCallContext context) - { - return Task.FromResult(new FilesReply { Success = true }); - } - - public override Task NewWindowOrLockedWindow(FileNames fileNames, ServerCallContext context) - { - return Task.FromResult(new FilesReply { Success = true }); - } - - //public override void WindowClosed() - //{ - - //} - } -} diff --git a/src/LogexpertgRPCService/appsettings.Development.json b/src/LogexpertgRPCService/appsettings.Development.json deleted file mode 100644 index 0c208ae9..00000000 --- a/src/LogexpertgRPCService/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/src/LogexpertgRPCService/appsettings.json b/src/LogexpertgRPCService/appsettings.json deleted file mode 100644 index 1aef5074..00000000 --- a/src/LogexpertgRPCService/appsettings.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "AllowedHosts": "*", - "Kestrel": { - "EndpointDefaults": { - "Protocols": "Http2" - } - } -} diff --git a/src/PluginRegistry/FileSystem/LocalFileSystem.cs b/src/PluginRegistry/FileSystem/LocalFileSystem.cs new file mode 100644 index 00000000..289b1ed3 --- /dev/null +++ b/src/PluginRegistry/FileSystem/LocalFileSystem.cs @@ -0,0 +1,39 @@ +namespace LogExpert.PluginRegistry.FileSystem; + +public class LocalFileSystem : IFileSystemPlugin +{ + #region IFileSystemPlugin Member + + public bool CanHandleUri(string uriString) + { + try + { + Uri uri = new(uriString); + return uri.IsFile; + } + catch (Exception) + { + return false; + } + } + + public ILogFileInfo GetLogfileInfo(string uriString) + { + Uri uri = new(uriString); + if (uri.IsFile) + { + ILogFileInfo logFileInfo = new LogFileInfo(uri); + return logFileInfo; + } + else + { + throw new UriFormatException("Uri " + uriString + " is no file Uri"); + } + } + + public string Text => "Local file system"; + + public string Description => "Access files from normal file system."; + + #endregion +} \ No newline at end of file diff --git a/src/PluginRegistry/FileSystem/LogFileInfo.cs b/src/PluginRegistry/FileSystem/LogFileInfo.cs new file mode 100644 index 00000000..31920565 --- /dev/null +++ b/src/PluginRegistry/FileSystem/LogFileInfo.cs @@ -0,0 +1,171 @@ +using NLog; + +namespace LogExpert.PluginRegistry.FileSystem; + +public class LogFileInfo : ILogFileInfo +{ + #region Fields + + private const int RETRY_COUNT = 5; + private const int RETRY_SLEEP = 250; + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + + //FileStream fStream; + private readonly FileInfo fInfo; + + private long lastLength; + + #endregion + + #region cTor + + public LogFileInfo(Uri fileUri) + { + fInfo = new FileInfo(fileUri.LocalPath); + Uri = fileUri; + OriginalLength = lastLength = LengthWithoutRetry; + //this.oldLength = 0; + } + + #endregion + + #region Properties + + public string FullName => fInfo.FullName; + + public string FileName => fInfo.Name; + + + public string DirectoryName => fInfo.DirectoryName; + + public char DirectorySeparatorChar => Path.DirectorySeparatorChar; + + public Uri Uri { get; } + + public long Length + { + get + { + if (fInfo == null) + { + return -1; + } + + var retry = RETRY_COUNT; + + while (retry > 0) + { + try + { + fInfo.Refresh(); + return fInfo.Length; + } + catch (IOException e) + { + if (--retry <= 0) + { + _logger.Warn(e, "LogFileInfo.Length"); + return -1; + } + Thread.Sleep(RETRY_SLEEP); + } + } + + return -1; + } + } + + public long OriginalLength { get; } + + public bool FileExists + { + get + { + fInfo.Refresh(); + return fInfo.Exists; + } + } + + //TODO this should be set from outside once + public int PollInterval => PluginRegistry.PollingInterval; + + public long LengthWithoutRetry + { + get + { + if (fInfo == null) + { + return -1; + } + try + { + fInfo.Refresh(); + return fInfo.Length; + } + catch (IOException) + { + return -1; + } + } + } + + #endregion + + #region Public methods + + /// + /// Creates a new FileStream for the file. The caller is responsible for closing. + /// If file opening fails it will be tried RETRY_COUNT times. This may be needed sometimes + /// if the file is locked for a short amount of time or temporarly unaccessible because of + /// rollover situations. + /// + /// + public Stream OpenStream() + { + var retry = RETRY_COUNT; + + while (true) + { + try + { + return new FileStream(fInfo.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + } + catch (IOException fe) + { + _logger.Debug(fe, "LogFileInfo.OpenFile(): \r\nRetry counter {0}", retry); + if (--retry <= 0) + { + throw; + } + Thread.Sleep(RETRY_SLEEP); + } + catch (UnauthorizedAccessException uae) + { + _logger.Debug(uae, "LogFileInfo.OpenFile(): \r\nRetry counter: {0}", retry); + if (--retry <= 0) + { + throw new IOException("Error opening file", uae); + } + Thread.Sleep(RETRY_SLEEP); + } + } + } + + //TODO Replace with Event from FileSystemWatcher + public bool FileHasChanged() + { + if (LengthWithoutRetry != lastLength) + { + lastLength = LengthWithoutRetry; + return true; + } + return false; + } + + public override string ToString() + { + return fInfo.FullName + ", OldLen: " + OriginalLength + ", Len: " + Length; + } + + #endregion +} \ No newline at end of file diff --git a/src/PluginRegistry/LogExpert.PluginRegistry.csproj b/src/PluginRegistry/LogExpert.PluginRegistry.csproj new file mode 100644 index 00000000..cf09bc7b --- /dev/null +++ b/src/PluginRegistry/LogExpert.PluginRegistry.csproj @@ -0,0 +1,15 @@ + + + + net8.0 + + + + + + + + + + + diff --git a/src/PluginRegistry/PluginRegistry.cs b/src/PluginRegistry/PluginRegistry.cs new file mode 100644 index 00000000..0b7a339b --- /dev/null +++ b/src/PluginRegistry/PluginRegistry.cs @@ -0,0 +1,387 @@ +using System.Globalization; +using System.Reflection; + +using LogExpert.Core.Classes; +using LogExpert.Core.Classes.Columnizer; +using LogExpert.Core.Entities; +using LogExpert.Core.Interface; +using LogExpert.PluginRegistry.FileSystem; + +using NLog; + +namespace LogExpert.PluginRegistry; + +/// +/// Holds all registered plugins. +/// +/// +/// It all has started with Columnizers only. So the different types of plugins have no common super interface. I didn't change it +/// to keep existing plugin API stable. In a future version this may change. +/// +public class PluginRegistry : IPluginRegistry +{ + #region Fields + + private static readonly ILogger _logger = LogManager.GetCurrentClassLogger(); + private static PluginRegistry? _instance; + private static readonly object _lock = new(); + + private readonly IFileSystemCallback _fileSystemCallback = new FileSystemCallback(); + private readonly IList _pluginList = []; + private readonly IDictionary _registeredKeywordsDict = new Dictionary(); + + #endregion + + private static string _applicationConfigurationFolder = string.Empty; + private static int _pollingInterval = 250; + + #region cTor + // Private constructor to prevent instantiation + private PluginRegistry (string applicationConfigurationFolder, int pollingInterval) + { + _applicationConfigurationFolder = applicationConfigurationFolder; + _pollingInterval = pollingInterval; + } + + public PluginRegistry Create (string applicationConfigurationFolder, int pollingInterval) + { + if (_instance != null) + { + return _instance; + } + + lock (_lock) + { + _instance = new PluginRegistry(applicationConfigurationFolder, pollingInterval); + } + + _applicationConfigurationFolder = applicationConfigurationFolder; + _pollingInterval = pollingInterval; + + _instance.LoadPlugins(); + return Instance; + } + + #endregion + + #region Properties + + public static PluginRegistry Instance => _instance ?? new PluginRegistry(_applicationConfigurationFolder, _pollingInterval); + + public IList RegisteredColumnizers { get; private set; } + + public IList RegisteredContextMenuPlugins { get; } = []; + + public IList RegisteredKeywordActions { get; } = []; + + public IList RegisteredFileSystemPlugins { get; } = []; + + #endregion + + #region Public methods + + public static int PollingInterval => _pollingInterval; + + #endregion + + #region Internals + + internal void LoadPlugins () + { + _logger.Info(CultureInfo.InvariantCulture, "Loading plugins..."); + + RegisteredColumnizers = + [ + //TODO: Remove these plugins and load them as any other plugin + new DefaultLogfileColumnizer(), + new TimestampColumnizer(), + new SquareBracketColumnizer(), + new ClfColumnizer(), + ]; + RegisteredFileSystemPlugins.Add(new LocalFileSystem()); + + var pluginDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins"); + //TODO: FIXME: This is a hack for the tests to pass. Need to find a better approach + if (!Directory.Exists(pluginDir)) + { + pluginDir = "."; + } + + AppDomain.CurrentDomain.AssemblyResolve += ColumnizerResolveEventHandler; + + var interfaceName = typeof(ILogLineColumnizer).FullName + ?? throw new NotImplementedException("The interface name is null. How did this happen? Let's fix this."); + + foreach (var dllName in Directory.EnumerateFiles(pluginDir, "*.dll")) + { + try + { + LoadPluginAssembly(dllName, interfaceName); + } + catch (Exception ex) when (ex is BadImageFormatException or FileLoadException) + { + // Can happen when a 32bit-only DLL is loaded on a 64bit system (or vice versa) + // or could be a not columnizer DLL (e.g. A DLL that is needed by a plugin). + _logger.Error(ex, dllName); + } + catch (ReflectionTypeLoadException ex) + { + // can happen when a dll dependency is missing + if (ex.LoaderExceptions != null && ex.LoaderExceptions.Length != 0) + { + foreach (Exception loaderException in ex.LoaderExceptions) + { + _logger.Error(loaderException, "Plugin load failed with '{0}'", dllName); + } + } + _logger.Error(ex, "Loader exception during load of dll '{0}'", dllName); + throw; + } + catch (Exception ex) + { + _logger.Error(ex, $"General Exception for the file {dllName}, of type: {ex.GetType()}, with the message: {ex.Message}"); + throw; + } + } + + _logger.Info(CultureInfo.InvariantCulture, "Plugin loading complete."); + } + + private void LoadPluginAssembly (string dllName, string interfaceName) + { + var assembly = Assembly.LoadFrom(dllName); + Type[] types = assembly.GetTypes(); + + foreach (Type type in types) + { + _logger.Info($"Type {type.FullName} in assembly {assembly.FullName} implements {interfaceName}"); + + if (type.GetInterfaces().Any(i => i.FullName == interfaceName)) + { + ConstructorInfo cti = type.GetConstructor(Type.EmptyTypes); + if (cti != null) + { + var instance = cti.Invoke([]); + RegisteredColumnizers.Add((ILogLineColumnizer)instance); + + if (instance is IColumnizerConfigurator configurator) + { + configurator.LoadConfig(_applicationConfigurationFolder); + } + + if (instance is ILogExpertPlugin plugin) + { + _pluginList.Add(plugin); + plugin.PluginLoaded(); + } + + _logger.Info($"Added columnizer {type.Name}"); + } + } + else + { + if (TryAsContextMenu(type)) + { + continue; + } + + if (TryAsKeywordAction(type)) + { + continue; + } + + if (TryAsFileSystem(type)) + { + continue; + } + } + } + } + + public IKeywordAction FindKeywordActionPluginByName (string name) + { + _registeredKeywordsDict.TryGetValue(name, out IKeywordAction action); + return action; + } + + public void CleanupPlugins () + { + foreach (ILogExpertPlugin plugin in _pluginList) + { + plugin.AppExiting(); + } + } + + public IFileSystemPlugin FindFileSystemForUri (string uriString) + { + if (_logger.IsDebugEnabled) + { + _logger.Debug(CultureInfo.InvariantCulture, "Trying to find file system plugin for uri {0}", uriString); + } + + foreach (IFileSystemPlugin fs in RegisteredFileSystemPlugins) + { + if (_logger.IsDebugEnabled) + { + _logger.Debug(CultureInfo.InvariantCulture, "Checking {0}", fs.Text); + } + + if (fs.CanHandleUri(uriString)) + { + if (_logger.IsDebugEnabled) + { + _logger.Debug(CultureInfo.InvariantCulture, "Found match {0}", fs.Text); + } + + return fs; + } + } + + _logger.Error("No file system plugin found for uri {0}", uriString); + return null; + } + + #endregion + + #region Private Methods + //TODO: Can this be deleted? + private bool TryAsContextMenu (Type type) + { + IContextMenuEntry me = TryInstantiate(type); + + if (me != null) + { + RegisteredContextMenuPlugins.Add(me); + if (me is ILogExpertPluginConfigurator configurator) + { + configurator.LoadConfig(_applicationConfigurationFolder); + } + + if (me is ILogExpertPlugin plugin) + { + _pluginList.Add(plugin); + plugin.PluginLoaded(); + } + + _logger.Info(CultureInfo.InvariantCulture, "Added context menu plugin {0}", type); + return true; + } + + return false; + } + + //TODO: Can this be delted? + private bool TryAsKeywordAction (Type type) + { + IKeywordAction ka = TryInstantiate(type); + if (ka != null) + { + RegisteredKeywordActions.Add(ka); + _registeredKeywordsDict.Add(ka.GetName(), ka); + if (ka is ILogExpertPluginConfigurator configurator) + { + configurator.LoadConfig(_applicationConfigurationFolder); + } + + if (ka is ILogExpertPlugin plugin) + { + _pluginList.Add(plugin); + plugin.PluginLoaded(); + } + + _logger.Info(CultureInfo.InvariantCulture, "Added keyword plugin {0}", type); + return true; + } + + return false; + } + + //TODO: Can this be delted? + private bool TryAsFileSystem (Type type) + { + // file system plugins can have optional constructor with IFileSystemCallback argument + IFileSystemPlugin fs = TryInstantiate(type, _fileSystemCallback); + fs ??= TryInstantiate(type); + + if (fs != null) + { + RegisteredFileSystemPlugins.Add(fs); + if (fs is ILogExpertPluginConfigurator configurator) + { + //TODO Refactor, this should be set from outside once and not loaded all the time + configurator.LoadConfig(_applicationConfigurationFolder); + } + + if (fs is ILogExpertPlugin plugin) + { + _pluginList.Add(plugin); + plugin.PluginLoaded(); + } + + _logger.Info(CultureInfo.InvariantCulture, "Added file system plugin {0}", type); + return true; + } + + return false; + } + + private static T TryInstantiate (Type loadedType) where T : class + { + Type t = typeof(T); + Type inter = loadedType.GetInterface(t.Name); + if (inter != null) + { + ConstructorInfo cti = loadedType.GetConstructor(Type.EmptyTypes); + if (cti != null) + { + var o = cti.Invoke([]); + return o as T; + } + } + + return default; + } + + private static T TryInstantiate (Type loadedType, IFileSystemCallback fsCallback) where T : class + { + Type t = typeof(T); + Type inter = loadedType.GetInterface(t.Name); + if (inter != null) + { + ConstructorInfo cti = loadedType.GetConstructor([typeof(IFileSystemCallback)]); + if (cti != null) + { + var o = cti.Invoke([fsCallback]); + return o as T; + } + } + + return default; + } + + #endregion + + #region Events handler + + private static Assembly ColumnizerResolveEventHandler (object? sender, ResolveEventArgs args) + { + var fileName = new AssemblyName(args.Name).Name + ".dll"; + + var mainDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); + var pluginDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "plugins", fileName); + + if (File.Exists(mainDir)) + { + return Assembly.LoadFrom(mainDir); + } + + if (File.Exists(pluginDir)) + { + return Assembly.LoadFrom(pluginDir); + } + + return null; + } + + #endregion +} \ No newline at end of file diff --git a/src/RegexColumnizer.UnitTests/Properties/AssemblyInfo.cs b/src/RegexColumnizer.UnitTests/Properties/AssemblyInfo.cs deleted file mode 100644 index 323361a8..00000000 --- a/src/RegexColumnizer.UnitTests/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,12 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("FBFB598D-B94A-4AD3-A355-0D5A618CEEE3")] diff --git a/src/RegexColumnizer.UnitTests/RegexColumnizer.UnitTests.csproj b/src/RegexColumnizer.UnitTests/RegexColumnizer.UnitTests.csproj index 75cf507e..be3904ad 100644 --- a/src/RegexColumnizer.UnitTests/RegexColumnizer.UnitTests.csproj +++ b/src/RegexColumnizer.UnitTests/RegexColumnizer.UnitTests.csproj @@ -1,23 +1,21 @@  net8.0-windows - Library + true - false - false + + bin\$(Configuration) + true - true + - ..\Solution Items\Key.snk + RegexColumnizer.UnitTests - RegexColumnizer.UnitTests - Copyright © 2023 - 1.0.0.0 - 1.0.0.0 + diff --git a/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs b/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs index 6728420d..54312b0e 100644 --- a/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs +++ b/src/RegexColumnizer.UnitTests/RegexColumnizerTests.cs @@ -4,69 +4,66 @@ using System.Runtime.Versioning; [assembly: SupportedOSPlatform("windows")] -namespace RegexColumnizer.UnitTests +namespace RegexColumnizer.UnitTests; + +[TestFixture] +public class RegexColumnizerTests { - [TestFixture] - public class RegexColumnizerTests + // The same amount of columns should be returned whether the line matches the regex or not. + [TestCase("5 test message", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 2)] + [TestCase("Error in com.example.core", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 2)] + public void SplitLine_ColumnCountMatches(string lineToParse, string regex, int expectedNumberOfColumns) { - // The same amount of columns should be returned whether the line matches the regex or not. - [TestCase("5 test message", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 2)] - [TestCase("Error in com.example.core", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 2)] - public void SplitLine_ColumnCountMatches(string lineToParse, string regex, int expectedNumberOfColumns) - { - Regex1Columnizer columnizer = CreateInitializedColumnizer(regex); + Regex1Columnizer columnizer = CreateInitializedColumnizer(regex); - TestLogLine testLogLine = new(4, lineToParse); - IColumnizedLogLine parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); + TestLogLine testLogLine = new(4, lineToParse); + IColumnizedLogLine parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); - Assert.That(expectedNumberOfColumns, Is.EqualTo(parsedLogLine.ColumnValues.Length)); - } + Assert.That(expectedNumberOfColumns, Is.EqualTo(parsedLogLine.ColumnValues.Length)); + } - //Using "" for empty string since string.Empty can't be passed to the TestCase attribute. - [TestCase("5 test message", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 0, "5")] - [TestCase("5 test message", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 1, "test message")] - [TestCase("Error in com.example.core", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 0, "")] // doesn't match regex so should be empty - [TestCase("Error in com.example.core", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 1, "Error in com.example.core")] - public void SplitLine_ColumnValues(string lineToParse, string regex, int columnIndexToTest, - string expectedColumnValue) - { - Regex1Columnizer columnizer = CreateInitializedColumnizer(regex); + //Using "" for empty string since string.Empty can't be passed to the TestCase attribute. + [TestCase("5 test message", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 0, "5")] + [TestCase("5 test message", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 1, "test message")] + [TestCase("Error in com.example.core", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 0, "")] // doesn't match regex so should be empty + [TestCase("Error in com.example.core", @"^(?'time'[\d]+)\s+(?'Message'.+)$", 1, "Error in com.example.core")] + public void SplitLine_ColumnValues(string lineToParse, string regex, int columnIndexToTest, + string expectedColumnValue) + { + Regex1Columnizer columnizer = CreateInitializedColumnizer(regex); - TestLogLine testLogLine = new(3, lineToParse); - IColumnizedLogLine parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); + TestLogLine testLogLine = new(3, lineToParse); + IColumnizedLogLine parsedLogLine = columnizer.SplitLine(Mock.Of(), testLogLine); - Assert.That(expectedColumnValue, Is.EqualTo(parsedLogLine.ColumnValues[columnIndexToTest].Text)); - } + Assert.That(expectedColumnValue, Is.EqualTo(parsedLogLine.ColumnValues[columnIndexToTest].Text)); + } - private Regex1Columnizer CreateInitializedColumnizer(string regex) + private Regex1Columnizer CreateInitializedColumnizer(string regex) + { + RegexColumnizerConfig columnizerConfig = new() { - RegexColumnizerConfig columnizerConfig = new() - { - Expression = regex, - Name = "Test regex" - }; + Expression = regex, + Name = "Test regex" + }; - Regex1Columnizer columnizer = new(); - //TODO this should be an internal function - columnizer.Init(columnizerConfig); - return columnizer; - } + Regex1Columnizer columnizer = new(); + //TODO this should be an internal function + columnizer.Init(columnizerConfig); + return columnizer; + } - private class TestLogLine : ILogLine + private class TestLogLine : ILogLine + { + public TestLogLine(int lineNumber, string fullLine) { - public TestLogLine(int lineNumber, string fullLine) - { - LineNumber = lineNumber; - FullLine = fullLine; - } + LineNumber = lineNumber; + FullLine = fullLine; + } - public string FullLine { get; set; } + public string FullLine { get; set; } - public int LineNumber { get; set; } + public int LineNumber { get; set; } - public string Text { get; set; } - } + public string Text { get; set; } } - - } diff --git a/src/RegexColumnizer/RegexColumnizer.cs b/src/RegexColumnizer/RegexColumnizer.cs index 89143937..bc66b146 100644 --- a/src/RegexColumnizer/RegexColumnizer.cs +++ b/src/RegexColumnizer/RegexColumnizer.cs @@ -8,241 +8,240 @@ using System.Xml.Serialization; [assembly: SupportedOSPlatform("windows")] -namespace RegexColumnizer +namespace RegexColumnizer; + +public abstract class BaseRegexColumnizer : ILogLineColumnizer, IColumnizerConfigurator { - public abstract class BaseRegexColumnizer : ILogLineColumnizer, IColumnizerConfigurator - { - #region Fields + #region Fields - private readonly XmlSerializer xml = new XmlSerializer(typeof(RegexColumnizerConfig)); - private string[] columns; + private readonly XmlSerializer xml = new XmlSerializer(typeof(RegexColumnizerConfig)); + private string[] columns; - #endregion + #endregion - #region Properties + #region Properties - public RegexColumnizerConfig Config { get; private set; } - - public Regex Regex { get; private set; } + public RegexColumnizerConfig Config { get; private set; } + + public Regex Regex { get; private set; } - #endregion + #endregion - #region Public methods + #region Public methods - public string GetName() + public string GetName() + { + if (Config == null || string.IsNullOrWhiteSpace(Config.Name)) { - if (Config == null || string.IsNullOrWhiteSpace(Config.Name)) - { - return GetNameInternal(); - } - - return Config.Name; + return GetNameInternal(); } - public string GetDescription() => "Columns are filled by regular expression named capture groups"; - - public int GetColumnCount() => columns.Length; - public string[] GetColumnNames() => columns; + return Config.Name; + } + public string GetDescription() => "Columns are filled by regular expression named capture groups"; + + public int GetColumnCount() => columns.Length; - public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + public string[] GetColumnNames() => columns; + + public IColumnizedLogLine SplitLine(ILogLineColumnizerCallback callback, ILogLine line) + { + var logLine = new ColumnizedLogLine(); + + logLine.ColumnValues = new IColumn[columns.Length]; + if (Regex != null) { - ColumnizedLogLine logLine = new ColumnizedLogLine(); + var m = Regex.Match(line.FullLine); - logLine.ColumnValues = new IColumn[columns.Length]; - if (Regex != null) + if (m.Success) { - var m = Regex.Match(line.FullLine); - - if (m.Success) - { - for (int i = m.Groups.Count - 1; i > 0; i--) - { - logLine.ColumnValues[i - 1] = new Column - { - Parent = logLine, - FullValue = m.Groups[i].Value - }; - } - } - else + for (var i = m.Groups.Count - 1; i > 0; i--) { - //Move non matching lines in the last column - logLine.ColumnValues[columns.Length - 1] = new Column + logLine.ColumnValues[i - 1] = new Column { Parent = logLine, - FullValue = line.FullLine + FullValue = m.Groups[i].Value }; - - - //Fill other columns with empty string to avoid null pointer exceptions in unexpected places - for (var i = 0; i < columns.Length - 1; i++) - { - logLine.ColumnValues[i] = new Column - { - Parent = logLine, - FullValue = string.Empty - }; - } } } else { - IColumn colVal = new Column + //Move non matching lines in the last column + logLine.ColumnValues[columns.Length - 1] = new Column { Parent = logLine, FullValue = line.FullLine }; - logLine.ColumnValues[0] = colVal; + + //Fill other columns with empty string to avoid null pointer exceptions in unexpected places + for (var i = 0; i < columns.Length - 1; i++) + { + logLine.ColumnValues[i] = new Column + { + Parent = logLine, + FullValue = string.Empty + }; + } } - - logLine.LogLine = line; - return logLine; } - - public bool IsTimeshiftImplemented() => false; - - public void SetTimeOffset(int msecOffset) + else { - throw new NotImplementedException(); - } + IColumn colVal = new Column + { + Parent = logLine, + FullValue = line.FullLine + }; - public int GetTimeOffset() - { - throw new NotImplementedException(); + logLine.ColumnValues[0] = colVal; } - public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) - { - throw new NotImplementedException(); - } + logLine.LogLine = line; + return logLine; + } - public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) - { - throw new NotImplementedException(); - } + public bool IsTimeshiftImplemented() => false; - public void Configure(ILogLineColumnizerCallback callback, string configDir) - { - RegexColumnizerConfigDialog dialog = new RegexColumnizerConfigDialog {Config = Config}; - if (dialog.ShowDialog() == DialogResult.OK) - { - var configFile = GetConfigFile(configDir); - using (var w = new FileStream(configFile, FileMode.Create)) - { - xml.Serialize(w, dialog.Config); - } + public void SetTimeOffset(int msecOffset) + { + throw new NotImplementedException(); + } - Init(dialog.Config); - } - } + public int GetTimeOffset() + { + throw new NotImplementedException(); + } + + public DateTime GetTimestamp(ILogLineColumnizerCallback callback, ILogLine line) + { + throw new NotImplementedException(); + } - public void LoadConfig(string configDir) + public void PushValue(ILogLineColumnizerCallback callback, int column, string value, string oldValue) + { + throw new NotImplementedException(); + } + + public void Configure(ILogLineColumnizerCallback callback, string configDir) + { + var dialog = new RegexColumnizerConfigDialog {Config = Config}; + if (dialog.ShowDialog() == DialogResult.OK) { var configFile = GetConfigFile(configDir); - RegexColumnizerConfig config; - if (!File.Exists(configFile)) - { - config = new RegexColumnizerConfig - { - Name = GetName() - }; - } - else + using (var w = new FileStream(configFile, FileMode.Create)) { - using (var reader = new StreamReader(configFile)) - { - config = xml.Deserialize(reader) as RegexColumnizerConfig; - } + xml.Serialize(w, dialog.Config); } - Init(config); + Init(dialog.Config); } + } - public string GetConfigFile(string configDir) - { - var name = GetType().Name; - string configPath = Path.Combine(configDir, name); - configPath = Path.ChangeExtension(configPath, "xml"); //todo change to json - return configPath; - } - - #endregion - - /// - /// ToString, this is displayed in the columnizer picker combobox only in the FilterSelectionDialog - /// - /// - public override string ToString() + public void LoadConfig(string configDir) + { + var configFile = GetConfigFile(configDir); + RegexColumnizerConfig config; + if (!File.Exists(configFile)) { - return GetName(); + config = new RegexColumnizerConfig + { + Name = GetName() + }; } - - #region Private Methods - - protected abstract string GetNameInternal(); - - public void Init(RegexColumnizerConfig config) + else { - Config = config; - - try + using (var reader = new StreamReader(configFile)) { - Regex = new Regex(Config.Expression, RegexOptions.Compiled); - int skip = Regex.GetGroupNames().Length == 1 ? 0 : 1; - columns = Regex.GetGroupNames().Skip(skip).ToArray(); - } - catch - { - Regex = null; + config = xml.Deserialize(reader) as RegexColumnizerConfig; } } - #endregion + Init(config); } - public class Regex1Columnizer : BaseRegexColumnizer + public string GetConfigFile(string configDir) { - protected override string GetNameInternal() => "Regex1"; + var name = GetType().Name; + var configPath = Path.Combine(configDir, name); + configPath = Path.ChangeExtension(configPath, "xml"); //todo change to json + return configPath; } - public class Regex2Columnizer : BaseRegexColumnizer - { - protected override string GetNameInternal() => "Regex2"; - } + #endregion - public class Regex3Columnizer : BaseRegexColumnizer + /// + /// ToString, this is displayed in the columnizer picker combobox only in the FilterSelectionDialog + /// + /// + public override string ToString() { - protected override string GetNameInternal() => "Regex3"; + return GetName(); } - public class Regex4Columnizer : BaseRegexColumnizer - { - protected override string GetNameInternal() => "Regex4"; - } + #region Private Methods - public class Regex5Columnizer : BaseRegexColumnizer - { - protected override string GetNameInternal() => "Regex5"; - } + protected abstract string GetNameInternal(); - public class Regex6Columnizer : BaseRegexColumnizer + public void Init(RegexColumnizerConfig config) { - protected override string GetNameInternal() => "Regex6"; - } + Config = config; - public class Regex7Columnizer : BaseRegexColumnizer - { - protected override string GetNameInternal() => "Regex7"; + try + { + Regex = new Regex(Config.Expression, RegexOptions.Compiled); + var skip = Regex.GetGroupNames().Length == 1 ? 0 : 1; + columns = Regex.GetGroupNames().Skip(skip).ToArray(); + } + catch + { + Regex = null; + } } - public class Regex8Columnizer : BaseRegexColumnizer - { - protected override string GetNameInternal() => "Regex8"; - } + #endregion +} - public class Regex9Columnizer : BaseRegexColumnizer - { - protected override string GetNameInternal() => "Regex9"; - } +public class Regex1Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex1"; +} + +public class Regex2Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex2"; +} + +public class Regex3Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex3"; +} + +public class Regex4Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex4"; +} + +public class Regex5Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex5"; +} + +public class Regex6Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex6"; +} + +public class Regex7Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex7"; +} + +public class Regex8Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex8"; +} + +public class Regex9Columnizer : BaseRegexColumnizer +{ + protected override string GetNameInternal() => "Regex9"; } \ No newline at end of file diff --git a/src/RegexColumnizer/RegexColumnizer.csproj b/src/RegexColumnizer/RegexColumnizer.csproj index 22af73ea..b85e7eac 100644 --- a/src/RegexColumnizer/RegexColumnizer.csproj +++ b/src/RegexColumnizer/RegexColumnizer.csproj @@ -2,41 +2,14 @@ net8.0-windows true - Library - false + true - false true - false $(SolutionDir)..\bin\$(Configuration)\plugins - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - + - - - Key.snk - - - - - - - + + \ No newline at end of file diff --git a/src/RegexColumnizer/RegexColumnizerConfig.cs b/src/RegexColumnizer/RegexColumnizerConfig.cs index f9b3897b..a8547403 100644 --- a/src/RegexColumnizer/RegexColumnizerConfig.cs +++ b/src/RegexColumnizer/RegexColumnizerConfig.cs @@ -1,13 +1,12 @@ -namespace RegexColumnizer +namespace RegexColumnizer; + +public class RegexColumnizerConfig { - public class RegexColumnizerConfig - { - #region Properties + #region Properties - public string Expression { get; set; } = "(?.*)"; + public string Expression { get; set; } = "(?.*)"; - public string Name { get; set; } + public string Name { get; set; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/RegexColumnizer/RegexColumnizerConfigDialog.cs b/src/RegexColumnizer/RegexColumnizerConfigDialog.cs index b44cf02f..a355aa38 100644 --- a/src/RegexColumnizer/RegexColumnizerConfigDialog.cs +++ b/src/RegexColumnizer/RegexColumnizerConfigDialog.cs @@ -5,78 +5,77 @@ using System.Text.RegularExpressions; using System.Windows.Forms; -namespace RegexColumnizer +namespace RegexColumnizer; + +public partial class RegexColumnizerConfigDialog : Form { - public partial class RegexColumnizerConfigDialog : Form + public RegexColumnizerConfigDialog() { - public RegexColumnizerConfigDialog() - { - SuspendLayout(); - AutoScaleDimensions = new SizeF(96F, 96F); - AutoScaleMode = AutoScaleMode.Dpi; - - InitializeComponent(); - ResumeLayout(); - } + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; - public RegexColumnizerConfig Config { get; set; } - - private void OnBtnOkClick(object sender, EventArgs e) - { - if (Check()) - { - Config.Expression = tbExpression.Text; - Config.Name = tbName.Text; - } + InitializeComponent(); + ResumeLayout(); + } - } + public RegexColumnizerConfig Config { get; set; } - private void RegexColumnizerConfigDialog_Load(object sender, EventArgs e) + private void OnBtnOkClick(object sender, EventArgs e) + { + if (Check()) { - tbExpression.Text = Config.Expression; - tbName.Text = Config.Name; + Config.Expression = tbExpression.Text; + Config.Name = tbName.Text; } - private void OnButtonCheckClick(object sender, EventArgs e) - { - Check(); - } + } - private bool Check() - { - DataTable table = new(); + private void RegexColumnizerConfigDialog_Load(object sender, EventArgs e) + { + tbExpression.Text = Config.Expression; + tbName.Text = Config.Name; + } - try - { - Regex regex = new(tbExpression.Text); - var groupNames = regex.GetGroupNames(); - int offset = groupNames.Length > 1 ? 1 : 0; + private void OnButtonCheckClick(object sender, EventArgs e) + { + Check(); + } - for (int i = offset; i < groupNames.Length; i++) - { - table.Columns.Add(groupNames[i]); - } + private bool Check() + { + DataTable table = new(); - if (!string.IsNullOrEmpty(tbTestLine.Text)) - { - Match match = regex.Match(tbTestLine.Text); - var row = table.NewRow(); - var values = match.Groups.OfType().Skip(offset).Select(group => group.Value).Cast().ToArray(); - row.ItemArray = values; - table.Rows.Add(row); - } + try + { + Regex regex = new(tbExpression.Text); + var groupNames = regex.GetGroupNames(); + var offset = groupNames.Length > 1 ? 1 : 0; - return true; - } - catch (Exception ex) + for (var i = offset; i < groupNames.Length; i++) { - MessageBox.Show($@"Invalid Regex !{Environment.NewLine}{ex.Message}", @"Regex Columnizer Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); - return false; + table.Columns.Add(groupNames[i]); } - finally + + if (!string.IsNullOrEmpty(tbTestLine.Text)) { - dataGridView1.DataSource = table; + Match match = regex.Match(tbTestLine.Text); + var row = table.NewRow(); + var values = match.Groups.OfType().Skip(offset).Select(group => group.Value).Cast().ToArray(); + row.ItemArray = values; + table.Rows.Add(row); } + + return true; + } + catch (Exception ex) + { + MessageBox.Show($@"Invalid Regex !{Environment.NewLine}{ex.Message}", @"Regex Columnizer Configuration", MessageBoxButtons.OK, MessageBoxIcon.Error); + return false; + } + finally + { + dataGridView1.DataSource = table; } } } diff --git a/src/SDK/Columnizer/Columnizer/Properties/AssemblyInfo.cs b/src/SDK/Columnizer/Columnizer/Properties/AssemblyInfo.cs deleted file mode 100644 index 29495b39..00000000 --- a/src/SDK/Columnizer/Columnizer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// Allgemeine Informationen über eine Assembly werden über die folgenden -// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, -// die mit einer Assembly verknüpft sind. -[assembly: AssemblyTitle("Columnizer")] -[assembly: AssemblyDescription("")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Columnizer")] -[assembly: AssemblyCopyright("Copyright © 2008")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar -// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von -// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. -[assembly: ComVisible(false)] - -// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird -[assembly: Guid("cbf6cfb3-b9b7-4596-aba4-f622e350bed1")] - -// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: -// -// Hauptversion -// Nebenversion -// Buildnummer -// Revision -// -// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern -// übernehmen, indem Sie "*" eingeben: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/SDK/Log4jXmlColumnizer/Properties/AssemblyInfo.cs b/src/SDK/Log4jXmlColumnizer/Properties/AssemblyInfo.cs deleted file mode 100644 index e77e09f6..00000000 --- a/src/SDK/Log4jXmlColumnizer/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,36 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// Allgemeine Informationen über eine Assembly werden über die folgenden -// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, -// die mit einer Assembly verknüpft sind. -[assembly: AssemblyTitle("Log4jXmlColumnizer")] -[assembly: AssemblyDescription("XML logfile support for LogExpert")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Log4jXmlColumnizer")] -[assembly: AssemblyCopyright("Copyright © 2009 Hagen Raab")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar -// für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von -// COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. -[assembly: ComVisible(false)] - -// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird -[assembly: Guid("7e083fad-da9a-4962-870f-0f1676293961")] - -// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: -// -// Hauptversion -// Nebenversion -// Buildnummer -// Revision -// -// Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern -// übernehmen, indem Sie "*" eingeben: -// [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/src/SftpFileSystemx64/ConfigData.cs b/src/SftpFileSystemx64/ConfigData.cs index 800005ce..02b58e21 100644 --- a/src/SftpFileSystemx64/ConfigData.cs +++ b/src/SftpFileSystemx64/ConfigData.cs @@ -1,15 +1,14 @@ -namespace SftpFileSystem +namespace SftpFileSystem; + +public class ConfigData { - public class ConfigData - { - #region Properties + #region Properties - public string KeyFile { get; set; } + public string KeyFile { get; set; } - public bool UseKeyfile { get; set; } + public bool UseKeyfile { get; set; } - public KeyType KeyType { get; set; } + public KeyType KeyType { get; set; } - #endregion - } + #endregion } \ No newline at end of file diff --git a/src/SftpFileSystemx64/ConfigDialog.cs b/src/SftpFileSystemx64/ConfigDialog.cs index 78f7f5cc..c3515d9d 100644 --- a/src/SftpFileSystemx64/ConfigDialog.cs +++ b/src/SftpFileSystemx64/ConfigDialog.cs @@ -1,66 +1,70 @@ using System; +using System.Drawing; using System.Runtime.Versioning; using System.Windows.Forms; [assembly: SupportedOSPlatform("windows")] -namespace SftpFileSystem -{ - public partial class ConfigDialog : Form - { - #region Ctor +namespace SftpFileSystem; - public ConfigDialog(ConfigData configData) - { - InitializeComponent(); - TopLevel = false; - ConfigData = configData; - chkBoxPK.Checked = ConfigData.UseKeyfile; - radioBtnPuttyKey.Checked = ConfigData.KeyType == KeyType.Putty; - radioBtnSSHKey.Checked = ConfigData.KeyType == KeyType.Ssh; - lblFile.Text = ConfigData.KeyFile; - } +public partial class ConfigDialog : Form +{ + #region Ctor - #endregion + public ConfigDialog(ConfigData configData) + { + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + InitializeComponent(); + TopLevel = false; + ConfigData = configData; + chkBoxPK.Checked = ConfigData.UseKeyfile; + radioBtnPuttyKey.Checked = ConfigData.KeyType == KeyType.Putty; + radioBtnSSHKey.Checked = ConfigData.KeyType == KeyType.Ssh; + lblFile.Text = ConfigData.KeyFile; + ResumeLayout(); + } - #region Properties / Indexers + #endregion - public ConfigData ConfigData { get; } + #region Properties / Indexers - #endregion + public ConfigData ConfigData { get; } - #region Event handling Methods + #endregion - private void OnBtnKeyFileClick(object sender, EventArgs e) - { - FileDialog dlg = new OpenFileDialog(); - if (DialogResult.OK == dlg.ShowDialog()) - { - ConfigData.KeyFile = dlg.FileName; - lblFile.Text = ConfigData.KeyFile; - } - } + #region Event handling Methods - private void OnChkBoxPKCheckedChanged(object sender, EventArgs e) + private void OnBtnKeyFileClick(object sender, EventArgs e) + { + FileDialog dlg = new OpenFileDialog(); + if (DialogResult.OK == dlg.ShowDialog()) { - ConfigData.UseKeyfile = chkBoxPK.Checked; + ConfigData.KeyFile = dlg.FileName; + lblFile.Text = ConfigData.KeyFile; } + } - private void OnChkBoxPKCheckStateChanged(object sender, EventArgs e) - { - keyFileButton.Enabled = chkBoxPK.Checked; - keyTypeGroupBox.Enabled = chkBoxPK.Checked; - } + private void OnChkBoxPKCheckedChanged(object sender, EventArgs e) + { + ConfigData.UseKeyfile = chkBoxPK.Checked; + } - private void OnRadioButtonPuttyKeyCheckedChanged(object sender, EventArgs e) - { - ConfigData.KeyType = KeyType.Putty; - } + private void OnChkBoxPKCheckStateChanged(object sender, EventArgs e) + { + keyFileButton.Enabled = chkBoxPK.Checked; + keyTypeGroupBox.Enabled = chkBoxPK.Checked; + } - private void OnRadioButtonSSHKeyCheckedChanged(object sender, EventArgs e) - { - ConfigData.KeyType = KeyType.Ssh; - } + private void OnRadioButtonPuttyKeyCheckedChanged(object sender, EventArgs e) + { + ConfigData.KeyType = KeyType.Putty; + } - #endregion + private void OnRadioButtonSSHKeyCheckedChanged(object sender, EventArgs e) + { + ConfigData.KeyType = KeyType.Ssh; } + + #endregion } diff --git a/src/SftpFileSystemx64/CredentialCache.cs b/src/SftpFileSystemx64/CredentialCache.cs index 43043170..c377efc2 100644 --- a/src/SftpFileSystemx64/CredentialCache.cs +++ b/src/SftpFileSystemx64/CredentialCache.cs @@ -1,60 +1,57 @@ -using System.Collections.Generic; +namespace SftpFileSystem; -namespace SftpFileSystem +internal class CredentialCache { - internal class CredentialCache - { - #region Private Fields + #region Private Fields - private readonly IList _credList = new List(); + private readonly IList _credList = []; - #endregion + #endregion - #region Private Methods + #region Private Methods - private void RemoveCredentials(string host, string user) + private void RemoveCredentials (string host, string user) + { + var credentials = GetCredentials(host, user); + if (credentials != null) { - Credentials credentials = GetCredentials(host, user); - if (credentials != null) - { - _credList.Remove(credentials); - } + _credList.Remove(credentials); } + } - #endregion + #endregion - internal IList GetUsersForHost(string host) - { - IList result = new List(); + internal IList GetUsersForHost (string host) + { + IList result = []; - foreach (Credentials cred in _credList) + foreach (var cred in _credList) + { + if (cred.Host.Equals(host, StringComparison.Ordinal)) { - if (cred.Host.Equals(host)) - { - result.Add(cred.UserName); - } + result.Add(cred.UserName); } - - return result; } - internal Credentials GetCredentials(string host, string user) + return result; + } + + internal Credentials GetCredentials (string host, string user) + { + foreach (var cred in _credList) { - foreach (Credentials cred in _credList) + if (cred.Host.Equals(host, StringComparison.Ordinal) && cred.UserName.Equals(user, StringComparison.Ordinal)) { - if (cred.Host.Equals(host) && cred.UserName.Equals(user)) - { - return cred; - } + return cred; } - - return null; } - internal void Add(Credentials cred) - { - RemoveCredentials(cred.Host, cred.UserName); - _credList.Add(cred); - } + return null; + } + + internal void Add (Credentials cred) + { + RemoveCredentials(cred.Host, cred.UserName); + _credList.Add(cred); } -} +} \ No newline at end of file diff --git a/src/SftpFileSystemx64/Credentials.cs b/src/SftpFileSystemx64/Credentials.cs index 8bdcdf5d..bffc2155 100644 --- a/src/SftpFileSystemx64/Credentials.cs +++ b/src/SftpFileSystemx64/Credentials.cs @@ -1,26 +1,3 @@ -namespace SftpFileSystem -{ - internal class Credentials - { - #region Ctor +namespace SftpFileSystem; - internal Credentials(string host, string userName, string password) - { - Host = host; - UserName = userName; - Password = password; - } - - #endregion - - #region Properties / Indexers - - public string Host { get; } - - public string Password { get; } - - public string UserName { get; } - - #endregion - } -} +internal record Credentials (string Host, string UserName, string Password); diff --git a/src/SftpFileSystemx64/FailedKeyDialog.cs b/src/SftpFileSystemx64/FailedKeyDialog.cs index cffb91e7..6084c33d 100644 --- a/src/SftpFileSystemx64/FailedKeyDialog.cs +++ b/src/SftpFileSystemx64/FailedKeyDialog.cs @@ -1,39 +1,43 @@ using System; +using System.Drawing; using System.Windows.Forms; -namespace SftpFileSystem -{ - public partial class FailedKeyDialog : Form - { - #region Ctor +namespace SftpFileSystem; - public FailedKeyDialog() - { - InitializeComponent(); - } +public partial class FailedKeyDialog : Form +{ + #region Ctor - #endregion + public FailedKeyDialog() + { + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + InitializeComponent(); + ResumeLayout(); + } - #region Event handling Methods + #endregion - private void OnBtnCancelClick(object sender, EventArgs e) - { - DialogResult = DialogResult.Cancel; - Close(); - } + #region Event handling Methods - private void OnBtnRetryClick(object sender, EventArgs e) - { - DialogResult = DialogResult.Retry; - Close(); - } + private void OnBtnCancelClick(object sender, EventArgs e) + { + DialogResult = DialogResult.Cancel; + Close(); + } - private void OnBtnUsePasswordAuthenticationClick(object sender, EventArgs e) - { - DialogResult = DialogResult.OK; - Close(); - } + private void OnBtnRetryClick(object sender, EventArgs e) + { + DialogResult = DialogResult.Retry; + Close(); + } - #endregion + private void OnBtnUsePasswordAuthenticationClick(object sender, EventArgs e) + { + DialogResult = DialogResult.OK; + Close(); } + + #endregion } diff --git a/src/SftpFileSystemx64/KeyType.cs b/src/SftpFileSystemx64/KeyType.cs index 8d989f34..a6a737c4 100644 --- a/src/SftpFileSystemx64/KeyType.cs +++ b/src/SftpFileSystemx64/KeyType.cs @@ -1,8 +1,7 @@ -namespace SftpFileSystem +namespace SftpFileSystem; + +public enum KeyType { - public enum KeyType - { - Putty, - Ssh - } + Putty, + Ssh } diff --git a/src/SftpFileSystemx64/LoginDialog.cs b/src/SftpFileSystemx64/LoginDialog.cs index ef911558..7f9581a7 100644 --- a/src/SftpFileSystemx64/LoginDialog.cs +++ b/src/SftpFileSystemx64/LoginDialog.cs @@ -1,75 +1,81 @@ using System; using System.Collections.Generic; +using System.Drawing; using System.Windows.Forms; -namespace SftpFileSystem +namespace SftpFileSystem; + +public partial class LoginDialog : Form { - public partial class LoginDialog : Form - { - #region Private Fields + #region Private Fields + + private string _username; - private string _username; + #endregion - #endregion + #region Ctor - #region Ctor + public LoginDialog(string host, IList userNames, bool hidePasswordField) + { + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; - public LoginDialog(string host, IList userNames, bool hidePasswordField) + InitializeComponent(); + serverNameLabel.Text = host; + if (userNames != null) { - InitializeComponent(); - serverNameLabel.Text = host; - if (userNames != null) + foreach (var name in userNames) { - foreach (string name in userNames) + if (name != null) { - if (name != null) - { - cmbUsername.Items.Add(name); - } + cmbUsername.Items.Add(name); } } + } - if (hidePasswordField) - { - txtBoxPassword.Enabled = false; - lblPassword.Enabled = false; - } + if (hidePasswordField) + { + txtBoxPassword.Enabled = false; + lblPassword.Enabled = false; } - #endregion + ResumeLayout(); + } + + #endregion - #region Properties / Indexers + #region Properties / Indexers - public string Password { get; private set; } + public string Password { get; private set; } - public string Username + public string Username + { + get => _username; + set { - get => _username; - set - { - _username = value ?? string.Empty; - cmbUsername.Text = value; - } + _username = value ?? string.Empty; + cmbUsername.Text = value; } + } - #endregion + #endregion - #region Event handling Methods + #region Event handling Methods - private void OnBtnOKClick(object sender, EventArgs e) - { - Password = txtBoxPassword.Text; - _username = cmbUsername.Text; - } + private void OnBtnOKClick(object sender, EventArgs e) + { + Password = txtBoxPassword.Text; + _username = cmbUsername.Text; + } - private void OnLoginDialogLoad(object sender, EventArgs e) + private void OnLoginDialogLoad(object sender, EventArgs e) + { + if (cmbUsername.Text.Length > 0) { - if (cmbUsername.Text.Length > 0) - { - txtBoxPassword.Focus(); - } + txtBoxPassword.Focus(); } - - #endregion } + + #endregion } diff --git a/src/SftpFileSystemx64/PrivateKeyPasswordDialog.cs b/src/SftpFileSystemx64/PrivateKeyPasswordDialog.cs index 59ea84d8..21c2c269 100644 --- a/src/SftpFileSystemx64/PrivateKeyPasswordDialog.cs +++ b/src/SftpFileSystemx64/PrivateKeyPasswordDialog.cs @@ -1,37 +1,41 @@ using System; +using System.Drawing; using System.Windows.Forms; -namespace SftpFileSystem -{ - public partial class PrivateKeyPasswordDialog : Form - { - #region Ctor +namespace SftpFileSystem; - public PrivateKeyPasswordDialog() - { - InitializeComponent(); - } +public partial class PrivateKeyPasswordDialog : Form +{ + #region Ctor - #endregion + public PrivateKeyPasswordDialog() + { + SuspendLayout(); + AutoScaleDimensions = new SizeF(96F, 96F); + AutoScaleMode = AutoScaleMode.Dpi; + InitializeComponent(); + ResumeLayout(); + } - #region Properties / Indexers + #endregion - public string Password { get; private set; } + #region Properties / Indexers - #endregion + public string Password { get; private set; } - #region Event handling Methods + #endregion - private void OnLoginDialogLoad(object sender, EventArgs e) - { - passwordTextBox.Focus(); - } + #region Event handling Methods - private void OnBtnOkClick(object sender, EventArgs e) - { - Password = passwordTextBox.Text; - } + private void OnLoginDialogLoad(object sender, EventArgs e) + { + passwordTextBox.Focus(); + } - #endregion + private void OnBtnOkClick(object sender, EventArgs e) + { + Password = passwordTextBox.Text; } + + #endregion } diff --git a/src/SftpFileSystemx64/Properties/AssemblyInfo.cs b/src/SftpFileSystemx64/Properties/AssemblyInfo.cs deleted file mode 100644 index 458b8d80..00000000 --- a/src/SftpFileSystemx64/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Reflection; -using System.Runtime.InteropServices; -[assembly: AssemblyCulture("")] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("6d67894f-87fd-40ad-bbce-0923fd38d0ff")] \ No newline at end of file diff --git a/src/SftpFileSystemx64/SftpFileSystem.cs b/src/SftpFileSystemx64/SftpFileSystem.cs index e53c0e17..a8583f3d 100644 --- a/src/SftpFileSystemx64/SftpFileSystem.cs +++ b/src/SftpFileSystemx64/SftpFileSystem.cs @@ -1,229 +1,225 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Windows.Forms; +using System.Globalization; using System.Xml.Serialization; -using LogExpert; -using Renci.SshNet; -namespace SftpFileSystem -{ - public class SftpFileSystem : IFileSystemPlugin, ILogExpertPluginConfigurator - { - #region Private Fields +using LogExpert; - private readonly ILogExpertLogger _logger; +using Renci.SshNet; - private ConfigDialog _configDialog; - private volatile PrivateKeyFile _privateKeyFile; +namespace SftpFileSystem; - #endregion +public class SftpFileSystem (IFileSystemCallback callback) : IFileSystemPlugin, ILogExpertPluginConfigurator +{ + #region Private Fields - #region Ctor + private readonly ILogExpertLogger _logger = callback.GetLogger(); - public SftpFileSystem(IFileSystemCallback callback) - { - _logger = callback.GetLogger(); - CredentialsCache = new CredentialCache(); - } + private ConfigDialog _configDialog; + private volatile PrivateKeyFile _privateKeyFile; + private readonly object _lock = new(); - #endregion + #endregion - #region Interface IFileSystemPlugin + #region Interface IFileSystemPlugin - public string Description => "Can read log files directly from SFTP server."; + public string Description => "Can read log files directly from SFTP server."; - public string Text => "SFTP plugin"; + public string Text => "SFTP plugin"; - public bool CanHandleUri(string uriString) + public bool CanHandleUri (string uriString) + { + try { - try - { - Uri uri = new(uriString); - return uri.Scheme.Equals("sftp", StringComparison.InvariantCultureIgnoreCase); - } - catch (Exception e) - { - _logger.LogError(e.Message); - return false; - } + Uri uri = new(uriString); + return uri.Scheme.Equals("sftp", StringComparison.OrdinalIgnoreCase); } - - public ILogFileInfo GetLogfileInfo(string uriString) + catch (Exception e) { - try - { - Uri uri = new(uriString.Replace('\\', '/')); - return new SftpLogFileInfo(this, uri, _logger); - } - catch (Exception e) - { - _logger.LogError(e.Message); - return null; - } + _logger.LogError(e.Message); + return false; } + } - #endregion - - #region Interface ILogExpertPluginConfigurator - - public bool HasEmbeddedForm() + public ILogFileInfo GetLogfileInfo (string uriString) + { + try { - return true; + Uri uri = new(uriString.Replace('\\', '/')); + return new SftpLogFileInfo(this, uri, _logger); } - - public void HideConfigForm() + catch (Exception e) { - ConfigData = _configDialog.ConfigData; - _configDialog.Hide(); - _configDialog.Dispose(); + _logger.LogError(e.Message); + return null; } + } - public void LoadConfig(string configDir) - { - XmlSerializer xml = new(ConfigData.GetType()); + #endregion - FileInfo configFile = new(configDir + "\\" + "sftpfilesystem.cfg"); + #region Interface ILogExpertPluginConfigurator - if (!configFile.Exists) - { - return; - } + public bool HasEmbeddedForm () + { + return true; + } - FileStream fs = null; + public void HideConfigForm () + { + ConfigData = _configDialog.ConfigData; + _configDialog.Hide(); + _configDialog.Dispose(); + } - try - { - fs = configFile.OpenRead(); + //TODO JSON config should be used + public void LoadConfig (string configDir) + { + XmlSerializer xml = new(ConfigData.GetType()); - ConfigData = (ConfigData)xml.Deserialize(fs); - } - catch (IOException e) - { - _logger.LogError(e.Message); - } - finally - { - fs?.Flush(); - fs?.Close(); - fs?.Dispose(); - } - } + FileInfo configFile = new(configDir + "\\" + "sftpfilesystem.cfg"); - public void SaveConfig(string configDir) + if (!configFile.Exists) { - _logger.Info("Saving SFTP config"); - XmlSerializer xml = new(ConfigData.GetType()); + return; + } - FileStream fs = null; + FileStream fs = null; - try - { - fs = new FileStream(configDir + "\\" + "sftpfilesystem.cfg", FileMode.Create); - xml.Serialize(fs, ConfigData); - fs.Close(); - } - catch (IOException e) - { - _logger.LogError(e.Message); - } - finally - { - fs?.Flush(); - fs?.Close(); - fs?.Dispose(); - } - } + try + { + fs = configFile.OpenRead(); - public void ShowConfigDialog(object owner) + ConfigData = (ConfigData)xml.Deserialize(fs); + } + catch (IOException e) { - throw new NotImplementedException(); + _logger.LogError(e.Message); } - - public void ShowConfigForm(object parentPanel) + finally { - _configDialog = new ConfigDialog(ConfigData); - _configDialog.Parent = (Panel)parentPanel; - _configDialog.Show(); + fs?.Flush(); + fs?.Close(); + fs?.Dispose(); } + } + + public void SaveConfig (string configDir) + { + _logger.Info(CultureInfo.InvariantCulture, "Saving SFTP config"); + XmlSerializer xml = new(ConfigData.GetType()); + + FileStream fs = null; - public void StartConfig() + try { + fs = new FileStream(configDir + "\\" + "sftpfilesystem.cfg", FileMode.Create); + xml.Serialize(fs, ConfigData); + fs.Close(); } + catch (IOException e) + { + _logger.LogError(e.Message); + } + finally + { + fs?.Flush(); + fs?.Close(); + fs?.Dispose(); + } + } - #endregion + public void ShowConfigDialog (object owner) + { + throw new NotImplementedException(); + } - #region Properties / Indexers + public void ShowConfigForm (object parentPanel) + { + _configDialog = new ConfigDialog(ConfigData) + { + Parent = (Panel)parentPanel + }; - public ConfigData ConfigData { get; private set; } = new ConfigData(); + _configDialog.Show(); + } - public PrivateKeyFile PrivateKeyFile - { - get => _privateKeyFile; - set => _privateKeyFile = value; - } + public void StartConfig () + { + } - private CredentialCache CredentialsCache { get; } + #endregion - #endregion + #region Properties / Indexers - internal Credentials GetCredentials(Uri uri, bool cacheAllowed, bool hidePasswordField) + public ConfigData ConfigData { get; private set; } = new ConfigData(); + + public PrivateKeyFile PrivateKeyFile + { + get => _privateKeyFile; + set => _privateKeyFile = value; + } + + private CredentialCache CredentialsCache { get; } = new CredentialCache(); + + #endregion + + internal Credentials GetCredentials (Uri uri, bool cacheAllowed, bool hidePasswordField) + { + // Synchronized access to the GetCredentials() method prevents multiple login dialogs when loading multiple files at once + // (e.g. on startup). So the user only needs to enter credentials once for the same host. + lock (_lock) { - // Synchronized access to the GetCredentials() method prevents multiple login dialogs when loading multiple files at once - // (e.g. on startup). So the user only needs to enter credentials once for the same host. - lock (this) + string userName = null; + string password = null; + if (uri.UserInfo != null && uri.UserInfo.Length > 0) { - string userName = null; - string password = null; - if (uri.UserInfo != null && uri.UserInfo.Length > 0) + var split = uri.UserInfo.Split(':'); + if (split.Length > 0) + { + userName = split[0]; + } + + if (split.Length > 1) { - string[] split = uri.UserInfo.Split(':'); - if (split.Length > 0) - { - userName = split[0]; - } - - if (split.Length > 1) - { - password = split[1]; - } + password = split[1]; } + } - IList usersForHost = CredentialsCache.GetUsersForHost(uri.Host); - if (userName == null && cacheAllowed) + var usersForHost = CredentialsCache.GetUsersForHost(uri.Host); + if (userName == null && cacheAllowed) + { + if (usersForHost.Count == 1) { - if (usersForHost.Count == 1) - { - userName = usersForHost[0]; - } + userName = usersForHost[0]; } + } - if (userName != null && password == null && cacheAllowed) + if (userName != null && password == null && cacheAllowed) + { + var cred = CredentialsCache.GetCredentials(uri.Host, userName); + if (cred != null) { - Credentials cred = CredentialsCache.GetCredentials(uri.Host, userName); - if (cred != null) - { - return cred; - } + return cred; } + } - if (userName == null || password == null) + if (userName == null || password == null) + { + LoginDialog dlg = new(uri.Host, usersForHost, hidePasswordField) { - LoginDialog dlg = new(uri.Host, usersForHost, hidePasswordField); - dlg.Username = userName; - if (DialogResult.OK == dlg.ShowDialog()) - { - password = dlg.Password; - userName = dlg.Username; - } - - dlg.Dispose(); + Username = userName + }; + + if (DialogResult.OK == dlg.ShowDialog()) + { + password = dlg.Password; + userName = dlg.Username; } - Credentials credentials = new(uri.Host, userName, password); - CredentialsCache.Add(credentials); - return credentials; + dlg.Dispose(); } + + Credentials credentials = new(uri.Host, userName, password); + CredentialsCache.Add(credentials); + return credentials; } } } diff --git a/src/SftpFileSystemx64/SftpFileSystemSSHDotNET.cs b/src/SftpFileSystemx64/SftpFileSystemSSHDotNET.cs deleted file mode 100644 index 7a253d56..00000000 --- a/src/SftpFileSystemx64/SftpFileSystemSSHDotNET.cs +++ /dev/null @@ -1,225 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Xml.Serialization; -using System.IO; -using Renci.SshNet; -using LogExpert; - -namespace SftpFileSystem -{ - public class SftpFileSystem : IFileSystemPlugin, ILogExpertPluginConfigurator - { - #region Fields - - private readonly ILogExpertLogger _logger; - - private ConfigDialog _configDialog; - private volatile PrivateKeyFile _privateKeyFile; - - #endregion - - #region cTor - - public SftpFileSystem(IFileSystemCallback callback) - { - _logger = callback.GetLogger(); - CredentialsCache = new CredentialCache(); - } - - #endregion - - #region Properties - - private CredentialCache CredentialsCache { get; } - - public string Text => "SFTP plugin"; - - public string Description => "Can read log files directly from SFTP server."; - - public ConfigData ConfigData { get; private set; } = new ConfigData(); - - public PrivateKeyFile PrivateKeyFile { get => _privateKeyFile; set => _privateKeyFile = value; } - - #endregion - - #region Public methods - - public bool CanHandleUri(string uriString) - { - try - { - Uri uri = new Uri(uriString); - return uri.Scheme.Equals("sftp", StringComparison.InvariantCultureIgnoreCase); - } - catch (Exception e) - { - _logger.LogError(e.Message); - return false; - } - } - - public ILogFileInfo GetLogfileInfo(string uriString) - { - try - { - Uri uri = new Uri(uriString.Replace('\\', '/')); - return new SftpLogFileInfo(this, uri, _logger); - } - catch (Exception e) - { - _logger.LogError(e.Message); - return null; - } - } - - public bool HasEmbeddedForm() - { - return true; - } - - public void HideConfigForm() - { - ConfigData = _configDialog.ConfigData; - _configDialog.Hide(); - _configDialog.Dispose(); - } - - public void LoadConfig(string configDir) - { - XmlSerializer xml = new XmlSerializer(ConfigData.GetType()); - - FileInfo configFile = new FileInfo(configDir + "\\" + "sftpfilesystem.cfg"); - - if (!configFile.Exists) - { - return; - } - - FileStream fs = null; - - try - { - fs = configFile.OpenRead(); - - ConfigData = (ConfigData) xml.Deserialize(fs); - } - catch (IOException e) - { - _logger.LogError(e.Message); - } - finally - { - fs?.Flush(); - fs?.Close(); - fs?.Dispose(); - } - } - - public void SaveConfig(string configDir) - { - _logger.Info("Saving SFTP config"); - XmlSerializer xml = new XmlSerializer(ConfigData.GetType()); - - FileStream fs = null; - - try - { - fs = new FileStream(configDir + "\\" + "sftpfilesystem.cfg", FileMode.Create); - xml.Serialize(fs, ConfigData); - fs.Close(); - } - catch (IOException e) - { - _logger.LogError(e.Message); - } - finally - { - fs?.Flush(); - fs?.Close(); - fs?.Dispose(); - } - } - - public void ShowConfigDialog(Form owner) - { - throw new NotImplementedException(); - } - - public void ShowConfigForm(Panel parentPanel) - { - _configDialog = new ConfigDialog(ConfigData); - _configDialog.Parent = parentPanel; - _configDialog.Show(); - } - - public void StartConfig() - { - } - - #endregion - - #region Internals - - internal Credentials GetCredentials(Uri uri, bool cacheAllowed, bool hidePasswordField) - { - // Synchronized access to the GetCredentials() method prevents multiple login dialogs when loading multiple files at once - // (e.g. on startup). So the user only needs to enter credentials once for the same host. - lock (this) - { - string userName = null; - string password = null; - if (uri.UserInfo != null && uri.UserInfo.Length > 0) - { - string[] split = uri.UserInfo.Split(new char[] {':'}); - if (split.Length > 0) - { - userName = split[0]; - } - - if (split.Length > 1) - { - password = split[1]; - } - } - - IList usersForHost = CredentialsCache.GetUsersForHost(uri.Host); - if (userName == null && cacheAllowed) - { - if (usersForHost.Count == 1) - { - userName = usersForHost[0]; - } - } - - if (userName != null && password == null && cacheAllowed) - { - Credentials cred = CredentialsCache.GetCredentials(uri.Host, userName); - if (cred != null) - { - return cred; - } - } - - if (userName == null || password == null) - { - LoginDialog dlg = new LoginDialog(uri.Host, usersForHost, hidePasswordField); - dlg.UserName = userName; - if (DialogResult.OK == dlg.ShowDialog()) - { - password = dlg.Password; - userName = dlg.UserName; - } - - dlg.Dispose(); - } - - Credentials credentials = new Credentials(uri.Host, userName, password); - CredentialsCache.Add(credentials); - return credentials; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/SftpFileSystemx64/SftpFileSystemx64.csproj b/src/SftpFileSystemx64/SftpFileSystemx64.csproj index b9080834..2627ca27 100644 --- a/src/SftpFileSystemx64/SftpFileSystemx64.csproj +++ b/src/SftpFileSystemx64/SftpFileSystemx64.csproj @@ -2,52 +2,22 @@ net8.0-windows true - Library + SftpFileSystem SftpFileSystem - false - false true true - false + true $(SolutionDir)..\bin\$(Configuration)\plugins + SftpFileSystem - - False - - - True - - - true - - - ..\Solution Items\Key.snk - - - - Properties\AssemblyVersion.cs - - - - - Key.snk - - - - - + + - - - - - + - - SftpFileSystem - + diff --git a/src/SftpFileSystemx64/SftpLogFileInfo.cs b/src/SftpFileSystemx64/SftpLogFileInfo.cs index 6323c202..b31ce3b7 100644 --- a/src/SftpFileSystemx64/SftpLogFileInfo.cs +++ b/src/SftpFileSystemx64/SftpLogFileInfo.cs @@ -1,263 +1,250 @@ -using System; -using System.IO; -using System.Threading; -using System.Windows.Forms; using LogExpert; + using Renci.SshNet; using Renci.SshNet.Sftp; -namespace SftpFileSystem +namespace SftpFileSystem; + +public class SftpLogFileInfo : ILogFileInfo { - internal class SftpLogFileInfo : ILogFileInfo - { - #region Static/Constants - //TODO Add to Options - private const int RETRY_COUNT = 20; - private const int RETRY_SLEEP = 250; + #region Static/Constants + //TODO Add to Options + private const int RETRY_COUNT = 20; + private const int RETRY_SLEEP = 250; - #endregion + #endregion - #region Private Fields + #region Private Fields - private readonly ILogExpertLogger _logger; - private readonly string _remoteFileName; + private readonly ILogExpertLogger _logger; + private readonly string _remoteFileName; - private readonly SftpClient _sftp; - private readonly object _sshKeyMonitor = new(); - private DateTime _lastChange = DateTime.Now; - private long _lastLength; + private readonly SftpClient _sftp; + private readonly object _sshKeyMonitor = new(); + private DateTime _lastChange = DateTime.Now; + private long _lastLength; - #endregion + #endregion - #region Ctor + #region Ctor - internal SftpLogFileInfo(SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpertLogger logger) - { - _logger = logger; - SftpFileSystem sftFileSystem = sftpFileSystem; - Uri = fileUri; - _remoteFileName = Uri.PathAndQuery; + public SftpLogFileInfo (SftpFileSystem sftpFileSystem, Uri fileUri, ILogExpertLogger logger) + { + _logger = logger; + var sftFileSystem = sftpFileSystem; + Uri = fileUri; + _remoteFileName = Uri.PathAndQuery; - int port = Uri.Port != -1 ? Uri.Port : 22; + var port = Uri.Port != -1 ? Uri.Port : 22; - bool success = false; - bool cancelled = false; - if (sftFileSystem.ConfigData.UseKeyfile) + var success = false; + var cancelled = false; + if (sftFileSystem.ConfigData.UseKeyfile) + { + lock (_sshKeyMonitor) // prevent multiple password dialogs when opening multiple files at once { - lock (_sshKeyMonitor) // prevent multiple password dialogs when opening multiple files at once + while (sftFileSystem.PrivateKeyFile == null) { - while (sftFileSystem.PrivateKeyFile == null) + PrivateKeyPasswordDialog dlg = new(); + var dialogResult = dlg.ShowDialog(); + if (dialogResult == DialogResult.Cancel) { - PrivateKeyPasswordDialog dlg = new(); - DialogResult dialogResult = dlg.ShowDialog(); - if (dialogResult == DialogResult.Cancel) - { - cancelled = true; - break; - } + cancelled = true; + break; + } - PrivateKeyFile privateKeyFile = new(sftFileSystem.ConfigData.KeyFile, dlg.Password); + PrivateKeyFile privateKeyFile = new(sftFileSystem.ConfigData.KeyFile, dlg.Password); - if (privateKeyFile != null) - { - sftFileSystem.PrivateKeyFile = privateKeyFile; - } - else - { - MessageBox.Show("Loading key file failed"); - } + if (privateKeyFile != null) + { + sftFileSystem.PrivateKeyFile = privateKeyFile; + } + else + { + MessageBox.Show("Loading key file failed"); } } + } - if (cancelled == false) + if (cancelled == false) + { + success = false; + var credentials = sftFileSystem.GetCredentials(Uri, true, true); + while (success == false) { - success = false; - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, true); - while (success == false) + //Add ConnectionInfo object + _sftp = new SftpClient(Uri.Host, credentials.UserName, sftFileSystem.PrivateKeyFile); + + if (_sftp != null) { - //Add ConnectionInfo object - _sftp = new SftpClient(Uri.Host, credentials.UserName, sftFileSystem.PrivateKeyFile); + _sftp.Connect(); + success = true; + } - if (_sftp != null) + if (success == false) + { + FailedKeyDialog dlg = new(); + var res = dlg.ShowDialog(); + dlg.Dispose(); + if (res == DialogResult.Cancel) { - _sftp.Connect(); - success = true; + return; } - if (success == false) + if (res == DialogResult.OK) { - FailedKeyDialog dlg = new(); - DialogResult res = dlg.ShowDialog(); - dlg.Dispose(); - if (res == DialogResult.Cancel) - { - return; - } - - if (res == DialogResult.OK) - { - break; // go to user/pw auth - } - - // retries with disabled cache - credentials = sftFileSystem.GetCredentials(Uri, false, true); + break; // go to user/pw auth } + + // retries with disabled cache + credentials = sftFileSystem.GetCredentials(Uri, false, true); } } } + } - if (success == false) + if (success == false) + { + // username/password auth + var credentials = sftFileSystem.GetCredentials(Uri, true, false); + _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); + + if (_sftp == null) { - // username/password auth - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, false); + // first fail -> try again with disabled cache + credentials = sftFileSystem.GetCredentials(Uri, false, false); _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); if (_sftp == null) { - // first fail -> try again with disabled cache - credentials = sftFileSystem.GetCredentials(Uri, false, false); - _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); - - if (_sftp == null) - { - // 2nd fail -> abort - MessageBox.Show("Authentication failed!"); - //MessageBox.Show(sftp.LastErrorText); - return; - } - } - else - { - _sftp.Connect(); + // 2nd fail -> abort + MessageBox.Show("Authentication failed!"); + //MessageBox.Show(sftp.LastErrorText); + return; } } - - if (_sftp.IsConnected == false) + else { - MessageBox.Show("Sftp is not connected"); - return; + _sftp.Connect(); } + } - OriginalLength = _lastLength = Length; + if (_sftp.IsConnected == false) + { + MessageBox.Show("Sftp is not connected"); + return; } - #endregion + OriginalLength = _lastLength = Length; + } - #region Interface ILogFileInfo + #endregion - public string DirectoryName - { - get - { - string full = FullName; - int i = full.LastIndexOf(DirectorySeparatorChar); - if (i != -1) - { - return full.Substring(0, i); - } + #region Interface ILogFileInfo - return "."; - } + public string DirectoryName + { + get + { + var full = FullName; + var i = full.LastIndexOf(DirectorySeparatorChar); + return i != -1 + ? full[..i] + : "."; } + } - public char DirectorySeparatorChar => '/'; + public char DirectorySeparatorChar => '/'; - public bool FileExists + public bool FileExists + { + get { - get + try { - try - { - SftpFile file = (SftpFile) _sftp.Get(_remoteFileName); - long len = file.Attributes.Size; - return len != -1; - } - catch (Exception e) - { - _logger.LogError(e.Message); - return false; - } + var file = (SftpFile)_sftp.Get(_remoteFileName); + var len = file.Attributes.Size; + return len != -1; + } + catch (Exception e) + { + _logger.LogError(e.Message); + return false; } } + } - public string FileName + public string FileName + { + get { - get - { - string full = FullName; - int i = full.LastIndexOf(DirectorySeparatorChar); - return full.Substring(i + 1); - } + var full = FullName; + var i = full.LastIndexOf(DirectorySeparatorChar); + return full[(i + 1)..]; } + } - public string FullName => Uri.ToString(); + public string FullName => Uri.ToString(); - public long Length + public long Length + { + get { - get - { - SftpFile file = (SftpFile)_sftp.Get(_remoteFileName); - return file.Attributes.Size; - } + var file = (SftpFile)_sftp.Get(_remoteFileName); + return file.Attributes.Size; } + } - public long OriginalLength { get; } + public long OriginalLength { get; } - public int PollInterval + public int PollInterval + { + get { - get - { - TimeSpan diff = DateTime.Now - _lastChange; - if (diff.TotalSeconds < 4) - { - return 400; - } + var diff = DateTime.Now - _lastChange; + return diff.TotalSeconds < 4 + ? 400 + : diff.TotalSeconds < 30 + ? (int)diff.TotalSeconds * 100 + : 5000; + } + } - if (diff.TotalSeconds < 30) - { - return (int)diff.TotalSeconds * 100; - } + public Uri Uri { get; } - return 5000; - } + public bool FileHasChanged () + { + if (Length != _lastLength) + { + _lastLength = Length; + _lastChange = DateTime.Now; + return true; } - public Uri Uri { get; } + return false; + } - public bool FileHasChanged() + public Stream OpenStream () + { + var retry = RETRY_COUNT; + while (true) { - if (Length != _lastLength) + try { - _lastLength = Length; - _lastChange = DateTime.Now; - return true; + return _sftp.OpenRead(_remoteFileName); } - - return false; - } - - public Stream OpenStream() - { - int retry = RETRY_COUNT; - while (true) + catch (IOException) { - try + //First remove a try then check if its less or 0 + if (--retry <= 0) { - return _sftp.OpenRead(_remoteFileName); + throw; } - catch (IOException) - { - //First remove a try then check if its less or 0 - if (--retry <= 0) - { - throw; - } - Thread.Sleep(RETRY_SLEEP); - } + Thread.Sleep(RETRY_SLEEP); } } - - #endregion } -} + + #endregion +} \ No newline at end of file diff --git a/src/SftpFileSystemx64/SftpLogFileInfoSSHDotNET.cs b/src/SftpFileSystemx64/SftpLogFileInfoSSHDotNET.cs deleted file mode 100644 index 78705afc..00000000 --- a/src/SftpFileSystemx64/SftpLogFileInfoSSHDotNET.cs +++ /dev/null @@ -1,231 +0,0 @@ -using LogExpert; - -using Renci.SshNet; -using Renci.SshNet.Sftp; - -using System; -using System.IO; -using System.Windows.Forms; - -namespace SftpFileSystem -{ - internal class SftpLogFileInfo : ILogFileInfo - { - - private const int RetryCount = 20; - private const int RetrySleep = 250; - private readonly ILogExpertLogger _logger; - private readonly string _remoteFileName; - - private readonly SftpClient _sftp; - private readonly object _sshKeyMonitor = new object(); - private DateTime _lastChange = DateTime.Now; - private long _lastLength; - - internal SftpLogFileInfo(SftpFileSystemSSHDotNET sftpFileSystem, Uri fileUri, ILogExpertLogger logger) - { - _logger = logger; - SftpFileSystemSSHDotNET sftFileSystem = sftpFileSystem; - Uri = fileUri; - _remoteFileName = Uri.PathAndQuery; - - int port = Uri.Port != -1 ? Uri.Port : 22; - - bool success = false; - bool cancelled = false; - if (sftFileSystem.ConfigData.UseKeyfile) - { - lock (_sshKeyMonitor) // prevent multiple password dialogs when opening multiple files at once - { - while (sftFileSystem.PrivateKeyFile == null) - { - PrivateKeyPasswordDialog dlg = new PrivateKeyPasswordDialog(); - DialogResult dialogResult = dlg.ShowDialog(); - if (dialogResult == DialogResult.Cancel) - { - cancelled = true; - break; - } - - PrivateKeyFile privateKeyFile = new PrivateKeyFile(sftFileSystem.ConfigData.KeyFile, dlg.Password); - - if (privateKeyFile != null) - { - sftFileSystem.PrivateKeyFile = privateKeyFile; - } - else - { - MessageBox.Show("Loading key file failed"); - } - } - } - - if (cancelled == false) - { - success = false; - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, true); - while (success == false) - { - //Add ConnectionInfo object - _sftp = new SftpClient(Uri.Host, credentials.UserName, new[] { sftFileSystem.PrivateKeyFile }); - - if (_sftp != null) - { - _sftp.Connect(); - success = true; - } - - if (success == false) - { - FailedKeyDialog dlg = new FailedKeyDialog(); - DialogResult res = dlg.ShowDialog(); - dlg.Dispose(); - if (res == DialogResult.Cancel) - { - return; - } - - if (res == DialogResult.OK) - { - break; // go to user/pw auth - } - - // retries with disabled cache - credentials = sftFileSystem.GetCredentials(Uri, false, true); - } - } - } - } - - if (success == false) - { - // username/password auth - Credentials credentials = sftFileSystem.GetCredentials(Uri, true, false); - _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); - - if (_sftp == null) - { - // first fail -> try again with disabled cache - credentials = sftFileSystem.GetCredentials(Uri, false, false); - _sftp = new SftpClient(Uri.Host, port, credentials.UserName, credentials.Password); - - if (_sftp == null) - { - // 2nd fail -> abort - MessageBox.Show("Authentication failed!"); - //MessageBox.Show(sftp.LastErrorText); - return; - } - } - else - { - _sftp.Connect(); - } - } - - if (_sftp.IsConnected == false) - { - MessageBox.Show("Sftp is not connected"); - return; - } - - OriginalLength = _lastLength = Length; - } - - public string FullName => Uri.ToString(); - - public string FileName - { - get - { - string full = FullName; - int i = full.LastIndexOf(DirectorySeparatorChar); - return full.Substring(i + 1); - } - } - - public string DirectoryName - { - get - { - string full = FullName; - int i = full.LastIndexOf(DirectorySeparatorChar); - if (i != -1) - { - return full.Substring(0, i); - } - - return "."; - } - } - - public char DirectorySeparatorChar => '/'; - - public Uri Uri { get; } - - public long Length - { - get - { - SftpFile file = _sftp.Get(_remoteFileName); - return file.Attributes.Size; - } - } - - public long OriginalLength { get; } - - public bool FileExists - { - get - { - try - { - SftpFile file = _sftp.Get(_remoteFileName); - long len = file.Attributes.Size; - return len != -1; - } - catch (Exception e) - { - _logger.LogError(e.Message); - return false; - } - } - } - - public int PollInterval - { - get - { - TimeSpan diff = DateTime.Now - _lastChange; - if (diff.TotalSeconds < 4) - { - return 400; - } - - if (diff.TotalSeconds < 30) - { - return (int)diff.TotalSeconds * 100; - } - - return 5000; - } - } - - public bool FileHasChanged() - { - if (Length != _lastLength) - { - _lastLength = Length; - _lastChange = DateTime.Now; - return true; - } - - return false; - } - - public Stream OpenStream() - { - return _sftp.OpenRead(_remoteFileName); - } - } -} diff --git a/src/SftpFileSystemx64/SftpLogFileInfoSharpSSH.cs b/src/SftpFileSystemx64/SftpLogFileInfoSharpSSH.cs deleted file mode 100644 index 5a13f323..00000000 --- a/src/SftpFileSystemx64/SftpLogFileInfoSharpSSH.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using LogExpert; -using Tamir.SharpSsh.jsch; -using System.Windows.Forms; - -namespace SftpFileSystem -{ - class SftpLogFileInfoSharpSSH : ILogFileInfo - { - private long originalFileLength = -1; - - private Uri uri; - private string remoteFileName; - - private ChannelSftp sftpChannel; - - internal SftpLogFileInfoSharpSSH(Uri uri) - { - this.uri = uri; - this.remoteFileName = uri.PathAndQuery; - - string userName = null; - string password = null; - if (uri.UserInfo != null && uri.UserInfo.Length > 0) - { - string[] split = uri.UserInfo.Split(new char[] { ':' }); - if (split.Length > 0) - userName = split[0]; - if (split.Length > 1) - password = split[1]; - } - if (userName == null || password == null) - { - IList userNames = new List(); - LoginDialog dlg = new LoginDialog(uri.Host, userNames); - dlg.UserName = userName; - if (DialogResult.OK == dlg.ShowDialog()) - { - password = dlg.Password; - userName = dlg.UserName; - } - } - - UserInfo userInfo = new SharpSshUserInfo(userName, password); - JSch jsch = new JSch(); - int port = uri.Port != -1 ? uri.Port : 22; - Session session = jsch.getSession(userName, this.uri.Host, port); - session.setUserInfo(userInfo); - session.connect(); - Channel channel = session.openChannel("sftp"); - channel.connect(); - this.sftpChannel = (ChannelSftp)channel; - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - this.originalFileLength = sftpAttrs.getSize(); - - } - - #region ILogFileInfo Member - - public System.IO.Stream OpenStream() - { - throw new NotImplementedException(); - } - - public string FileName - { - get { return this.remoteFileName; } - } - - public long Length - { - get - { - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - return sftpAttrs.getSize(); - } - } - - public long OriginalLength - { - get { return this.originalFileLength; } - } - - public bool FileExists - { - get - { - try - { - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - return true; - } - catch (SftpException e) - { - return false; - } - } - } - - #endregion - - #region ILogFileInfo Member - - - public string FullName - { - get { throw new NotImplementedException(); } - } - - public string DirectoryName - { - get { throw new NotImplementedException(); } - } - - public char DirectorySeparatorChar - { - get { throw new NotImplementedException(); } - } - - public Uri Uri - { - get { throw new NotImplementedException(); } - } - - public int PollInterval - { - get { throw new NotImplementedException(); } - } - - public bool FileHasChanged() - { - throw new NotImplementedException(); - } - - #endregion - } -} diff --git a/src/SftpFileSystemx64/SftpStreamSharpSSH.cs b/src/SftpFileSystemx64/SftpStreamSharpSSH.cs deleted file mode 100644 index 8162f664..00000000 --- a/src/SftpFileSystemx64/SftpStreamSharpSSH.cs +++ /dev/null @@ -1,104 +0,0 @@ -using System; -using System.IO; -using Tamir.SharpSsh.jsch; - -namespace SftpFileSystem -{ - class SftpStreamSharpSSH : Stream - { - private ChannelSftp sftpChannel; - private long currentPos; - private string remoteFileName; - - internal SftpStreamSharpSSH(ChannelSftp sftpChannel, string remoteFileName) - { - this.sftpChannel = sftpChannel; - this.currentPos = 0; - this.remoteFileName = remoteFileName; - } - - public override bool CanRead - { - get { return true; } - } - - public override bool CanSeek - { - get { return true; } - } - - public override bool CanWrite - { - get { return false; } - } - - public override void Flush() - { - throw new NotImplementedException(); - } - - public override long Length - { - get - { - SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName); - return sftpAttrs.getSize(); - } - } - - public override long Position - { - get { return this.currentPos; } - set - { - this.currentPos = value; - } - } - - public override int Read(byte[] buffer, int offset, int count) - { - Tamir.SharpSsh.java.io.OutputStream os = new Tamir.SharpSsh.java.io.OutputStream(); - - this.sftpChannel.get(Tamir.SharpSsh.java.String(this.remoteFileName), os, null, ChannelSftp.RESUME, - this.currentPos); - - this.currentPos += bytes.Length; - Array.Copy(bytes, 0, buffer, offset, bytes.Length); - return bytes.Length; - } - - public override long Seek(long offset, SeekOrigin origin) - { - if (origin == SeekOrigin.Begin) - { - this.Position = offset; - } - else if (origin == SeekOrigin.Current) - { - this.Position += offset; - } - else if (origin == SeekOrigin.End) - { - this.Position = this.Length - offset; - } - return this.Position; - } - - public override void SetLength(long value) - { - throw new NotImplementedException(); - } - - public override void Write(byte[] buffer, int offset, int count) - { - throw new NotImplementedException(); - } - - public override void Close() - { - base.Close(); - this.sftp.CloseHandle(this.handle); - } - - } -} \ No newline at end of file diff --git a/src/SftpFileSystemx64/SharpSshUserInfo.cs b/src/SftpFileSystemx64/SharpSshUserInfo.cs deleted file mode 100644 index 95dc2497..00000000 --- a/src/SftpFileSystemx64/SharpSshUserInfo.cs +++ /dev/null @@ -1,51 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using Tamir.SharpSsh.jsch; -using System.Windows.Forms; - -namespace SftpFileSystem -{ - internal class SharpSshUserInfo : UserInfo - { - private String password; - private String userName; - - internal SharpSshUserInfo(string userName, string password) - { - this.userName = userName; - this.password = password; - } - - - public String getPassword() { return password; } - - public bool promptYesNo(String str) - { - DialogResult returnVal = MessageBox.Show( - str, - "LogExpert", - MessageBoxButtons.YesNo, - MessageBoxIcon.Warning); - return (returnVal == DialogResult.Yes); - } - - public String getPassphrase() { return null; } - - public bool promptPassphrase(String message) { return true; } - - public bool promptPassword(String message) - { - return true; - } - - public void showMessage(String message) - { - MessageBox.Show( - message, - "LogExpert", - MessageBoxButtons.OK, - MessageBoxIcon.Asterisk); - } - } -} diff --git a/src/SftpFileSystemx86/Properties/AssemblyInfo.cs b/src/SftpFileSystemx86/Properties/AssemblyInfo.cs deleted file mode 100644 index 2d342d43..00000000 --- a/src/SftpFileSystemx86/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -using System.Reflection; -using System.Runtime.CompilerServices; -using System.Runtime.InteropServices; - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("3d01e923-5219-488b-b0a7-98521841e680")] \ No newline at end of file diff --git a/src/SftpFileSystemx86/SftpFileSystemx86.csproj b/src/SftpFileSystemx86/SftpFileSystemx86.csproj index 339e9ea5..eb96b544 100644 --- a/src/SftpFileSystemx86/SftpFileSystemx86.csproj +++ b/src/SftpFileSystemx86/SftpFileSystemx86.csproj @@ -2,23 +2,16 @@ net8.0-windows true - Library + SftpFileSystem SftpFileSystem - false true - false true + true SftpFileSystemx86 - false $(SolutionDir)..\bin\$(Configuration)\pluginsx86 - - False - - - True - + ConfigData.cs @@ -46,28 +39,21 @@ SftpLogFileInfo.cs - - Properties\AssemblyVersion.cs - + + - - - - - - Key.snk - + + - - - + + diff --git a/src/Solution Items/AssemblyVersion.cs b/src/Solution Items/AssemblyInfo.cs similarity index 61% rename from src/Solution Items/AssemblyVersion.cs rename to src/Solution Items/AssemblyInfo.cs index c7b9e075..d27ce7a1 100644 --- a/src/Solution Items/AssemblyVersion.cs +++ b/src/Solution Items/AssemblyInfo.cs @@ -1,12 +1,13 @@ -using System.Reflection; -using System.Runtime.InteropServices; - -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyProduct("LogExpert")] -[assembly: AssemblyCopyright("Original work Copyright (c) 2008-2011 Hagen Raab\r\nModified work Copyright (c) 2025 Zarunbal|Hirogen and many others")] - -[assembly: AssemblyVersion("1.12.0")] -[assembly: AssemblyFileVersion("1.12.0")] -[assembly: AssemblyInformationalVersion("1.12.0")] - -[assembly: ComVisible(false)] +using System.Reflection; +using System.Runtime.InteropServices; + +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyProduct("LogExpert")] +[assembly: AssemblyCopyright("Original work Copyright (c) 2008-2011 Hagen Raab\r\nModified work Copyright (c) 2025 Zarunbal|Hirogen and many others")] + +[assembly: AssemblyVersion("1.20.0")] +[assembly: AssemblyFileVersion("1.20.0")] +[assembly: AssemblyInformationalVersion("1.20.0")] + +[assembly: ComVisible(false)] +//warning CA1824: Mark assemblies with NeutralResourcesLanguageAttribute \ No newline at end of file diff --git a/src/Solution Items/Key.Public.snk b/src/Solution Items/Key.Public.snk new file mode 100644 index 00000000..b9d1ac95 Binary files /dev/null and b/src/Solution Items/Key.Public.snk differ diff --git a/src/Solution Items/usedComponents.json b/src/Solution Items/usedComponents.json new file mode 100644 index 00000000..4bfb6a2c Binary files /dev/null and b/src/Solution Items/usedComponents.json differ diff --git a/src/WinFormsUI/Docking/AutoHideStripBase.cs b/src/WinFormsUI/Docking/AutoHideStripBase.cs deleted file mode 100644 index abcfa941..00000000 --- a/src/WinFormsUI/Docking/AutoHideStripBase.cs +++ /dev/null @@ -1,684 +0,0 @@ -using System; -using System.Collections; -using System.Windows.Forms; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public abstract partial class AutoHideStripBase : Control - { - #region Fields - - private GraphicsPath m_displayingArea = null; - - #endregion - - #region cTor - - protected AutoHideStripBase(DockPanel panel) - { - DockPanel = panel; - PanesTop = new PaneCollection(panel, DockState.DockTopAutoHide); - PanesBottom = new PaneCollection(panel, DockState.DockBottomAutoHide); - PanesLeft = new PaneCollection(panel, DockState.DockLeftAutoHide); - PanesRight = new PaneCollection(panel, DockState.DockRightAutoHide); - - SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - SetStyle(ControlStyles.Selectable, false); - } - - #endregion - - #region Properties - - protected DockPanel DockPanel { get; } - - protected PaneCollection PanesTop { get; } - - protected PaneCollection PanesBottom { get; } - - protected PaneCollection PanesLeft { get; } - - protected PaneCollection PanesRight { get; } - - protected Rectangle RectangleTopLeft - { - get - { - int height = MeasureHeight(); - return PanesTop.Count > 0 && PanesLeft.Count > 0 - ? new Rectangle(0, 0, height, height) - : Rectangle.Empty; - } - } - - protected Rectangle RectangleTopRight - { - get - { - int height = MeasureHeight(); - return PanesTop.Count > 0 && PanesRight.Count > 0 - ? new Rectangle(Width - height, 0, height, height) - : Rectangle.Empty; - } - } - - protected Rectangle RectangleBottomLeft - { - get - { - int height = MeasureHeight(); - return PanesBottom.Count > 0 && PanesLeft.Count > 0 - ? new Rectangle(0, Height - height, height, height) - : Rectangle.Empty; - } - } - - protected Rectangle RectangleBottomRight - { - get - { - int height = MeasureHeight(); - return PanesBottom.Count > 0 && PanesRight.Count > 0 - ? new Rectangle(Width - height, Height - height, height, height) - : Rectangle.Empty; - } - } - - private GraphicsPath DisplayingArea - { - get - { - if (m_displayingArea == null) - { - m_displayingArea = new GraphicsPath(); - } - - return m_displayingArea; - } - } - - #endregion - - #region Internals - - internal int GetNumberOfPanes(DockState dockState) - { - return GetPanes(dockState).Count; - } - - internal void RefreshChanges() - { - if (IsDisposed) - { - return; - } - - SetRegion(); - OnRefreshChanges(); - } - - #endregion - - #region Overrides - - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - if (e.Button != MouseButtons.Left) - { - return; - } - - IDockContent content = HitTest(); - if (content == null) - { - return; - } - - content.DockHandler.Activate(); - } - - protected override void OnMouseHover(EventArgs e) - { - base.OnMouseHover(e); - - IDockContent content = HitTest(); - if (content != null && DockPanel.ActiveAutoHideContent != content) - { - DockPanel.ActiveAutoHideContent = content; - } - - // requires further tracking of mouse hover behavior, - ResetMouseEventArgs(); - } - - protected override void OnLayout(LayoutEventArgs levent) - { - RefreshChanges(); - base.OnLayout(levent); - } - - #endregion - - #region Private Methods - - private void SetRegion() - { - DisplayingArea.Reset(); - DisplayingArea.AddRectangle(RectangleTopLeft); - DisplayingArea.AddRectangle(RectangleTopRight); - DisplayingArea.AddRectangle(RectangleBottomLeft); - DisplayingArea.AddRectangle(RectangleBottomRight); - DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.DockTopAutoHide)); - DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.DockBottomAutoHide)); - DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.DockLeftAutoHide)); - DisplayingArea.AddRectangle(GetTabStripRectangle(DockState.DockRightAutoHide)); - Region = new Region(DisplayingArea); - } - - private IDockContent HitTest() - { - Point ptMouse = PointToClient(Control.MousePosition); - return HitTest(ptMouse); - } - - #endregion - - protected PaneCollection GetPanes(DockState dockState) - { - if (dockState == DockState.DockTopAutoHide) - { - return PanesTop; - } - else if (dockState == DockState.DockBottomAutoHide) - { - return PanesBottom; - } - else if (dockState == DockState.DockLeftAutoHide) - { - return PanesLeft; - } - else if (dockState == DockState.DockRightAutoHide) - { - return PanesRight; - } - else - { - throw new ArgumentOutOfRangeException("dockState"); - } - } - - protected internal Rectangle GetTabStripRectangle(DockState dockState) - { - int height = MeasureHeight(); - if (dockState == DockState.DockTopAutoHide && PanesTop.Count > 0) - { - return new Rectangle(RectangleTopLeft.Width, 0, - Width - RectangleTopLeft.Width - RectangleTopRight.Width, height); - } - else if (dockState == DockState.DockBottomAutoHide && PanesBottom.Count > 0) - { - return new Rectangle(RectangleBottomLeft.Width, Height - height, - Width - RectangleBottomLeft.Width - RectangleBottomRight.Width, height); - } - else if (dockState == DockState.DockLeftAutoHide && PanesLeft.Count > 0) - { - return new Rectangle(0, RectangleTopLeft.Width, height, - Height - RectangleTopLeft.Height - RectangleBottomLeft.Height); - } - else if (dockState == DockState.DockRightAutoHide && PanesRight.Count > 0) - { - return new Rectangle(Width - height, RectangleTopRight.Width, height, - Height - RectangleTopRight.Height - RectangleBottomRight.Height); - } - else - { - return Rectangle.Empty; - } - } - - protected virtual void OnRefreshChanges() - { - } - - protected internal abstract int MeasureHeight(); - - protected virtual Tab CreateTab(IDockContent content) - { - return new Tab(content); - } - - protected virtual Pane CreatePane(DockPane dockPane) - { - return new Pane(dockPane); - } - - protected abstract IDockContent HitTest(Point point); - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - protected class Tab : IDisposable - { - #region Fields - - #endregion - - #region cTor - - protected internal Tab(IDockContent content) - { - Content = content; - } - - #endregion - - #region Properties - - public IDockContent Content { get; } - - #endregion - - #region Public methods - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - #endregion - - ~Tab() - { - Dispose(false); - } - - protected virtual void Dispose(bool disposing) - { - } - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - protected sealed class TabCollection : IEnumerable - { - #region Fields - - #endregion - - #region cTor - - internal TabCollection(DockPane pane) - { - DockPane = pane; - } - - #endregion - - #region Properties - - public DockPane DockPane { get; } = null; - - public DockPanel DockPanel - { - get { return DockPane.DockPanel; } - } - - public int Count - { - get { return DockPane.DisplayingContents.Count; } - } - - public Tab this[int index] - { - get - { - IDockContent content = DockPane.DisplayingContents[index]; - if (content == null) - { - throw new ArgumentOutOfRangeException("index"); - } - if (content.DockHandler.AutoHideTab == null) - { - content.DockHandler.AutoHideTab = DockPanel.AutoHideStripControl.CreateTab(content); - } - return content.DockHandler.AutoHideTab as Tab; - } - } - - #endregion - - #region Public methods - - public bool Contains(Tab tab) - { - return IndexOf(tab) != -1; - } - - public bool Contains(IDockContent content) - { - return IndexOf(content) != -1; - } - - public int IndexOf(Tab tab) - { - if (tab == null) - { - return -1; - } - - return IndexOf(tab.Content); - } - - public int IndexOf(IDockContent content) - { - return DockPane.DisplayingContents.IndexOf(content); - } - - #endregion - - #region IEnumerable Members - - IEnumerator IEnumerable.GetEnumerator() - { - for (int i = 0; i < Count; i++) - { - yield return this[i]; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (int i = 0; i < Count; i++) - { - yield return this[i]; - } - } - - #endregion - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - protected class Pane : IDisposable - { - #region Fields - - #endregion - - #region cTor - - protected internal Pane(DockPane dockPane) - { - DockPane = dockPane; - } - - #endregion - - #region Properties - - public DockPane DockPane { get; } - - public TabCollection AutoHideTabs - { - get - { - if (DockPane.AutoHideTabs == null) - { - DockPane.AutoHideTabs = new TabCollection(DockPane); - } - return DockPane.AutoHideTabs as TabCollection; - } - } - - #endregion - - #region Public methods - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - #endregion - - ~Pane() - { - Dispose(false); - } - - protected virtual void Dispose(bool disposing) - { - } - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - protected sealed class PaneCollection : IEnumerable - { - #region Fields - - #endregion - - #region cTor - - internal PaneCollection(DockPanel panel, DockState dockState) - { - DockPanel = panel; - States = new AutoHideStateCollection(); - States[DockState.DockTopAutoHide].Selected = dockState == DockState.DockTopAutoHide; - States[DockState.DockBottomAutoHide].Selected = dockState == DockState.DockBottomAutoHide; - States[DockState.DockLeftAutoHide].Selected = dockState == DockState.DockLeftAutoHide; - States[DockState.DockRightAutoHide].Selected = dockState == DockState.DockRightAutoHide; - } - - #endregion - - #region Properties - - public DockPanel DockPanel { get; } - - private AutoHideStateCollection States { get; } - - public int Count - { - get - { - int count = 0; - foreach (DockPane pane in DockPanel.Panes) - { - if (States.ContainsPane(pane)) - { - count++; - } - } - - return count; - } - } - - public Pane this[int index] - { - get - { - int count = 0; - foreach (DockPane pane in DockPanel.Panes) - { - if (!States.ContainsPane(pane)) - { - continue; - } - - if (count == index) - { - if (pane.AutoHidePane == null) - { - pane.AutoHidePane = DockPanel.AutoHideStripControl.CreatePane(pane); - } - return pane.AutoHidePane as Pane; - } - - count++; - } - throw new ArgumentOutOfRangeException("index"); - } - } - - #endregion - - #region Public methods - - public bool Contains(Pane pane) - { - return IndexOf(pane) != -1; - } - - public int IndexOf(Pane pane) - { - if (pane == null) - { - return -1; - } - - int index = 0; - foreach (DockPane dockPane in DockPanel.Panes) - { - if (!States.ContainsPane(pane.DockPane)) - { - continue; - } - - if (pane == dockPane.AutoHidePane) - { - return index; - } - - index++; - } - return -1; - } - - #endregion - - private class AutoHideState - { - #region Fields - - public readonly DockState m_dockState; - public bool m_selected = false; - - #endregion - - #region cTor - - public AutoHideState(DockState dockState) - { - m_dockState = dockState; - } - - #endregion - - #region Properties - - public DockState DockState - { - get { return m_dockState; } - } - - public bool Selected - { - get { return m_selected; } - set { m_selected = value; } - } - - #endregion - } - - private class AutoHideStateCollection - { - #region Fields - - private readonly AutoHideState[] m_states; - - #endregion - - #region cTor - - public AutoHideStateCollection() - { - m_states = new AutoHideState[] - { - new AutoHideState(DockState.DockTopAutoHide), - new AutoHideState(DockState.DockBottomAutoHide), - new AutoHideState(DockState.DockLeftAutoHide), - new AutoHideState(DockState.DockRightAutoHide) - }; - } - - #endregion - - #region Properties - - public AutoHideState this[DockState dockState] - { - get - { - for (int i = 0; i < m_states.Length; i++) - { - if (m_states[i].DockState == dockState) - { - return m_states[i]; - } - } - throw new ArgumentOutOfRangeException("dockState"); - } - } - - #endregion - - #region Public methods - - public bool ContainsPane(DockPane pane) - { - if (pane.IsHidden) - { - return false; - } - - for (int i = 0; i < m_states.Length; i++) - { - if (m_states[i].DockState == pane.DockState && m_states[i].Selected) - { - return true; - } - } - return false; - } - - #endregion - } - - #region IEnumerable Members - - IEnumerator IEnumerable.GetEnumerator() - { - for (int i = 0; i < Count; i++) - { - yield return this[i]; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (int i = 0; i < Count; i++) - { - yield return this[i]; - } - } - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockAreasEditor.cs b/src/WinFormsUI/Docking/DockAreasEditor.cs deleted file mode 100644 index dffde868..00000000 --- a/src/WinFormsUI/Docking/DockAreasEditor.cs +++ /dev/null @@ -1,201 +0,0 @@ -using System; -using System.ComponentModel; -using System.Drawing; -using System.Drawing.Design; -using System.Windows.Forms; -using System.Windows.Forms.Design; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal class DockAreasEditor : UITypeEditor - { - #region Fields - - private DockAreasEditor.DockAreasEditorControl m_ui = null; - - #endregion - - #region Public methods - - public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context) - { - return UITypeEditorEditStyle.DropDown; - } - - public override object EditValue(ITypeDescriptorContext context, IServiceProvider sp, object value) - { - if (m_ui == null) - { - m_ui = new DockAreasEditor.DockAreasEditorControl(); - } - - m_ui.SetStates((DockAreas) value); - - IWindowsFormsEditorService edSvc = - (IWindowsFormsEditorService) sp.GetService(typeof(IWindowsFormsEditorService)); - edSvc.DropDownControl(m_ui); - - return m_ui.DockAreas; - } - - #endregion - - private class DockAreasEditorControl : System.Windows.Forms.UserControl - { - #region Fields - - private readonly CheckBox checkBoxDockBottom; - private readonly CheckBox checkBoxDockFill; - private readonly CheckBox checkBoxDockLeft; - private readonly CheckBox checkBoxDockRight; - private readonly CheckBox checkBoxDockTop; - private readonly CheckBox checkBoxFloat; - private DockAreas m_oldDockAreas; - - #endregion - - #region cTor - - public DockAreasEditorControl() - { - checkBoxFloat = new CheckBox(); - checkBoxDockLeft = new CheckBox(); - checkBoxDockRight = new CheckBox(); - checkBoxDockTop = new CheckBox(); - checkBoxDockBottom = new CheckBox(); - checkBoxDockFill = new CheckBox(); - - SuspendLayout(); - - checkBoxFloat.Appearance = Appearance.Button; - checkBoxFloat.Dock = DockStyle.Top; - checkBoxFloat.Height = 24; - checkBoxFloat.Text = Strings.DockAreaEditor_FloatCheckBoxText; - checkBoxFloat.TextAlign = ContentAlignment.MiddleCenter; - checkBoxFloat.FlatStyle = FlatStyle.System; - - checkBoxDockLeft.Appearance = System.Windows.Forms.Appearance.Button; - checkBoxDockLeft.Dock = System.Windows.Forms.DockStyle.Left; - checkBoxDockLeft.Width = 24; - checkBoxDockLeft.FlatStyle = FlatStyle.System; - - checkBoxDockRight.Appearance = System.Windows.Forms.Appearance.Button; - checkBoxDockRight.Dock = System.Windows.Forms.DockStyle.Right; - checkBoxDockRight.Width = 24; - checkBoxDockRight.FlatStyle = FlatStyle.System; - - checkBoxDockTop.Appearance = System.Windows.Forms.Appearance.Button; - checkBoxDockTop.Dock = System.Windows.Forms.DockStyle.Top; - checkBoxDockTop.Height = 24; - checkBoxDockTop.FlatStyle = FlatStyle.System; - - checkBoxDockBottom.Appearance = System.Windows.Forms.Appearance.Button; - checkBoxDockBottom.Dock = System.Windows.Forms.DockStyle.Bottom; - checkBoxDockBottom.Height = 24; - checkBoxDockBottom.FlatStyle = FlatStyle.System; - - checkBoxDockFill.Appearance = System.Windows.Forms.Appearance.Button; - checkBoxDockFill.Dock = System.Windows.Forms.DockStyle.Fill; - checkBoxDockFill.FlatStyle = FlatStyle.System; - - this.Controls.AddRange(new Control[] - { - checkBoxDockFill, - checkBoxDockBottom, - checkBoxDockTop, - checkBoxDockRight, - checkBoxDockLeft, - checkBoxFloat - }); - - Size = new System.Drawing.Size(160, 144); - BackColor = SystemColors.Control; - ResumeLayout(); - } - - #endregion - - #region Properties - - public DockAreas DockAreas - { - get - { - DockAreas dockAreas = 0; - if (checkBoxFloat.Checked) - { - dockAreas |= DockAreas.Float; - } - if (checkBoxDockLeft.Checked) - { - dockAreas |= DockAreas.DockLeft; - } - if (checkBoxDockRight.Checked) - { - dockAreas |= DockAreas.DockRight; - } - if (checkBoxDockTop.Checked) - { - dockAreas |= DockAreas.DockTop; - } - if (checkBoxDockBottom.Checked) - { - dockAreas |= DockAreas.DockBottom; - } - if (checkBoxDockFill.Checked) - { - dockAreas |= DockAreas.Document; - } - - if (dockAreas == 0) - { - return m_oldDockAreas; - } - else - { - return dockAreas; - } - } - } - - #endregion - - #region Public methods - - public void SetStates(DockAreas dockAreas) - { - m_oldDockAreas = dockAreas; - if ((dockAreas & DockAreas.DockLeft) != 0) - { - checkBoxDockLeft.Checked = true; - } - if ((dockAreas & DockAreas.DockRight) != 0) - { - checkBoxDockRight.Checked = true; - } - if ((dockAreas & DockAreas.DockTop) != 0) - { - checkBoxDockTop.Checked = true; - } - if ((dockAreas & DockAreas.DockTop) != 0) - { - checkBoxDockTop.Checked = true; - } - if ((dockAreas & DockAreas.DockBottom) != 0) - { - checkBoxDockBottom.Checked = true; - } - if ((dockAreas & DockAreas.Document) != 0) - { - checkBoxDockFill.Checked = true; - } - if ((dockAreas & DockAreas.Float) != 0) - { - checkBoxFloat.Checked = true; - } - } - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockContent.cs b/src/WinFormsUI/Docking/DockContent.cs deleted file mode 100644 index 76bad264..00000000 --- a/src/WinFormsUI/Docking/DockContent.cs +++ /dev/null @@ -1,328 +0,0 @@ -using System; -using System.ComponentModel; -using System.Drawing; -using System.Windows.Forms; -using System.Diagnostics.CodeAnalysis; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public class DockContent : Form, IDockContent - { - #region Fields - - private static readonly object DockStateChangedEvent = new object(); - - [Localizable(true)] [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_TabText_Description")] [DefaultValue(null)] private string m_tabText = null; - - #endregion - - #region cTor - - public DockContent() - { - DockHandler = new DockContentHandler(this, GetPersistString); - DockHandler.DockStateChanged += DockHandler_DockStateChanged; - //Suggested as a fix by bensty regarding form resize - ParentChanged += DockContent_ParentChanged; - } - - #endregion - - #region Events - - [LocalizedCategory("Category_PropertyChanged")] - [LocalizedDescription("Pane_DockStateChanged_Description")] - public event EventHandler DockStateChanged - { - - add => Events.AddHandler(DockStateChangedEvent, value); - remove => Events.RemoveHandler(DockStateChangedEvent, value); - } - - #endregion - - #region Properties - - [Browsable(false)] - public DockContentHandler DockHandler { get; } = null; - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_AllowEndUserDocking_Description")] - [DefaultValue(true)] - public bool AllowEndUserDocking - { - get => DockHandler.AllowEndUserDocking; - set => DockHandler.AllowEndUserDocking = value; - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_DockAreas_Description")] - [DefaultValue(DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | DockAreas.DockBottom | - DockAreas.Document | DockAreas.Float)] - public DockAreas DockAreas - { - get => DockHandler.DockAreas; - set => DockHandler.DockAreas = value; - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_AutoHidePortion_Description")] - [DefaultValue(0.25)] - public double AutoHidePortion - { - get => DockHandler.AutoHidePortion; - set => DockHandler.AutoHidePortion = value; - } - - public string TabText - { - get => m_tabText; - set => DockHandler.TabText = m_tabText = value; - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_CloseButton_Description")] - [DefaultValue(true)] - public bool CloseButton - { - get => DockHandler.CloseButton; - set => DockHandler.CloseButton = value; - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_CloseButtonVisible_Description")] - [DefaultValue(true)] - public bool CloseButtonVisible - { - get => DockHandler.CloseButtonVisible; - set => DockHandler.CloseButtonVisible = value; - } - - [Browsable(false)] - public DockPanel DockPanel - { - get => DockHandler.DockPanel; - set => DockHandler.DockPanel = value; - } - - [Browsable(false)] - public DockState DockState - { - get => DockHandler.DockState; - set => DockHandler.DockState = value; - } - - [Browsable(false)] - public DockPane Pane - { - get => DockHandler.Pane; - set => DockHandler.Pane = value; - } - - [Browsable(false)] - public bool IsHidden - { - get => DockHandler.IsHidden; - set => DockHandler.IsHidden = value; - } - - [Browsable(false)] - public DockState VisibleState - { - get => DockHandler.VisibleState; - set => DockHandler.VisibleState = value; - } - - [Browsable(false)] - public bool IsFloat - { - get => DockHandler.IsFloat; - set => DockHandler.IsFloat = value; - } - - [Browsable(false)] - public DockPane PanelPane - { - get => DockHandler.PanelPane; - set => DockHandler.PanelPane = value; - } - - [Browsable(false)] - public DockPane FloatPane - { - get => DockHandler.FloatPane; - set => DockHandler.FloatPane = value; - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_HideOnClose_Description")] - [DefaultValue(false)] - public bool HideOnClose - { - get => DockHandler.HideOnClose; - set => DockHandler.HideOnClose = value; - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_ShowHint_Description")] - [DefaultValue(DockState.Unknown)] - public DockState ShowHint - { - get => DockHandler.ShowHint; - set => DockHandler.ShowHint = value; - } - - [Browsable(false)] - public bool IsActivated => DockHandler.IsActivated; - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_TabPageContextMenu_Description")] - [DefaultValue(null)] - public ContextMenuStrip TabPageContextMenu - { - get => DockHandler.TabPageContextMenu; - set => DockHandler.TabPageContextMenu = value; - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockContent_TabPageContextMenuStrip_Description")] - [DefaultValue(null)] - public ContextMenuStrip TabPageContextMenuStrip - { - get => DockHandler.TabPageContextMenuStrip; - set => DockHandler.TabPageContextMenuStrip = value; - } - - [Localizable(true)] - [Category("Appearance")] - [LocalizedDescription("DockContent_ToolTipText_Description")] - [DefaultValue(null)] - public string ToolTipText - { - get => DockHandler.ToolTipText; - set => DockHandler.ToolTipText = value; - } - - #endregion - - #region Public methods - - public bool IsDockStateValid(DockState dockState) - { - return DockHandler.IsDockStateValid(dockState); - } - - public new void Activate() - { - DockHandler.Activate(); - } - - public new void Hide() - { - DockHandler.Hide(); - } - - public new void Show() - { - DockHandler.Show(); - } - - public void Show(DockPanel dockPanel) - { - DockHandler.Show(dockPanel); - } - - public void Show(DockPanel dockPanel, DockState dockState) - { - DockHandler.Show(dockPanel, dockState); - } - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] - public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) - { - DockHandler.Show(dockPanel, floatWindowBounds); - } - - public void Show(DockPane pane, IDockContent beforeContent) - { - DockHandler.Show(pane, beforeContent); - } - - public void Show(DockPane previousPane, DockAlignment alignment, double proportion) - { - DockHandler.Show(previousPane, alignment, proportion); - } - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] - public void FloatAt(Rectangle floatWindowBounds) - { - DockHandler.FloatAt(floatWindowBounds); - } - - public void DockTo(DockPane paneTo, DockStyle dockStyle, int contentIndex) - { - DockHandler.DockTo(paneTo, dockStyle, contentIndex); - } - - public void DockTo(DockPanel panel, DockStyle dockStyle) - { - DockHandler.DockTo(panel, dockStyle); - } - - #endregion - - #region Private Methods - - private bool ShouldSerializeTabText() - { - return m_tabText != null; - } - - #endregion - - #region Events handler - - //Suggested as a fix by bensty regarding form resize - private void DockContent_ParentChanged(object Sender, EventArgs e) - { - if (Parent != null) - { - Font = Parent.Font; - } - } - - private void DockHandler_DockStateChanged(object sender, EventArgs e) - { - OnDockStateChanged(e); - } - - #endregion - - [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] - protected virtual string GetPersistString() - { - return GetType().ToString(); - } - - protected virtual void OnDockStateChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[DockStateChangedEvent]; - handler?.Invoke(this, e); - } - - #region IDockContent Members - - void IDockContent.OnActivated(EventArgs e) - { - OnActivated(e); - } - - void IDockContent.OnDeactivate(EventArgs e) - { - OnDeactivate(e); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockContentCollection.cs b/src/WinFormsUI/Docking/DockContentCollection.cs deleted file mode 100644 index 7f0e9151..00000000 --- a/src/WinFormsUI/Docking/DockContentCollection.cs +++ /dev/null @@ -1,233 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public class DockContentCollection : ReadOnlyCollection - { - #region Fields - - private static readonly List _emptyList = new List(0); - - #endregion - - #region cTor - - internal DockContentCollection() - : base(new List()) - { - } - - internal DockContentCollection(DockPane pane) - : base(_emptyList) - { - DockPane = pane; - } - - #endregion - - #region Properties - - private DockPane DockPane { get; } = null; - - public new IDockContent this[int index] - { - get - { - if (DockPane == null) - { - return Items[index] as IDockContent; - } - else - { - return GetVisibleContent(index); - } - } - } - - public new int Count - { - get - { - if (DockPane == null) - { - return base.Count; - } - else - { - return CountOfVisibleContents; - } - } - } - - private int CountOfVisibleContents - { - get - { -#if DEBUG - if (DockPane == null) - throw new InvalidOperationException(); -#endif - - int count = 0; - foreach (IDockContent content in DockPane.Contents) - { - if (content.DockHandler.DockState == DockPane.DockState) - { - count++; - } - } - return count; - } - } - - #endregion - - #region Public methods - - public new bool Contains(IDockContent content) - { - if (DockPane == null) - { - return Items.Contains(content); - } - else - { - return GetIndexOfVisibleContents(content) != -1; - } - } - - public new int IndexOf(IDockContent content) - { - if (DockPane == null) - { - if (!Contains(content)) - { - return -1; - } - else - { - return Items.IndexOf(content); - } - } - else - { - return GetIndexOfVisibleContents(content); - } - } - - #endregion - - #region Internals - - internal int Add(IDockContent content) - { -#if DEBUG - if (DockPane != null) - throw new InvalidOperationException(); -#endif - - if (Contains(content)) - { - return IndexOf(content); - } - - Items.Add(content); - return Count - 1; - } - - internal void AddAt(IDockContent content, int index) - { -#if DEBUG - if (DockPane != null) - throw new InvalidOperationException(); -#endif - - if (index < 0 || index > Items.Count - 1) - { - return; - } - - if (Contains(content)) - { - return; - } - - Items.Insert(index, content); - } - - internal void Remove(IDockContent content) - { - if (DockPane != null) - { - throw new InvalidOperationException(); - } - - if (!Contains(content)) - { - return; - } - - Items.Remove(content); - } - - #endregion - - #region Private Methods - - private IDockContent GetVisibleContent(int index) - { -#if DEBUG - if (DockPane == null) - throw new InvalidOperationException(); -#endif - - int currentIndex = -1; - foreach (IDockContent content in DockPane.Contents) - { - if (content.DockHandler.DockState == DockPane.DockState) - { - currentIndex++; - } - - if (currentIndex == index) - { - return content; - } - } - throw new ArgumentOutOfRangeException(); - } - - private int GetIndexOfVisibleContents(IDockContent content) - { -#if DEBUG - if (DockPane == null) - throw new InvalidOperationException(); -#endif - - if (content == null) - { - return -1; - } - - int index = -1; - foreach (IDockContent c in DockPane.Contents) - { - if (c.DockHandler.DockState == DockPane.DockState) - { - index++; - - if (c == content) - { - return index; - } - } - } - return -1; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockContentEventArgs.cs b/src/WinFormsUI/Docking/DockContentEventArgs.cs deleted file mode 100644 index 4abbd70d..00000000 --- a/src/WinFormsUI/Docking/DockContentEventArgs.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public class DockContentEventArgs : EventArgs - { - #region Fields - - #endregion - - #region cTor - - public DockContentEventArgs(IDockContent content) - { - Content = content; - } - - #endregion - - #region Properties - - public IDockContent Content { get; } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockContentHandler.cs b/src/WinFormsUI/Docking/DockContentHandler.cs deleted file mode 100644 index 8d20156b..00000000 --- a/src/WinFormsUI/Docking/DockContentHandler.cs +++ /dev/null @@ -1,1320 +0,0 @@ -using System; -using System.Windows.Forms; -using System.Drawing; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public delegate string GetPersistStringCallback(); - - public class DockContentHandler : IDisposable, IDockDragSource - { - #region Fields - - private static readonly object DockStateChangedEvent = new object(); - - private DockAreas m_allowedAreas = DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | - DockAreas.DockBottom | DockAreas.Document | DockAreas.Float; - - private double m_autoHidePortion = 0.25; - - private bool m_closeButton = true; - - private int m_countSetDockState = 0; - - private DockPanel m_dockPanel = null; - - private DockState m_dockState = DockState.Unknown; - - private bool m_flagClipWindow = false; - - private DockPane m_floatPane = null; - - - private bool m_isActivated = false; - - private bool m_isFloat = false; - - private bool m_isHidden = true; - - private DockPane m_panelPane = null; - - private DockState m_showHint = DockState.Unknown; - - private DockPaneStripBase.Tab m_tab = null; - - private string m_tabText = null; - - private DockState m_visibleState = DockState.Unknown; - - #endregion - - #region cTor - - public DockContentHandler(Form form) : this(form, null) - { - } - - public DockContentHandler(Form form, GetPersistStringCallback getPersistStringCallback) - { - if (!(form is IDockContent)) - { - throw new ArgumentException(Strings.DockContent_Constructor_InvalidForm, "form"); - } - - Form = form; - GetPersistStringCallback = getPersistStringCallback; - - Events = new EventHandlerList(); - Form.Disposed += new EventHandler(Form_Disposed); - Form.TextChanged += new EventHandler(Form_TextChanged); - } - - #endregion - - #region Events - - public event EventHandler DockStateChanged - { - add { Events.AddHandler(DockStateChangedEvent, value); } - remove { Events.RemoveHandler(DockStateChangedEvent, value); } - } - - #endregion - - #region Properties - - public Form Form { get; } - - public IDockContent Content - { - get { return Form as IDockContent; } - } - - public IDockContent PreviousActive { get; internal set; } = null; - - public IDockContent NextActive { get; internal set; } = null; - - private EventHandlerList Events { get; } - - public bool AllowEndUserDocking { get; set; } = true; - - public double AutoHidePortion - { - get { return m_autoHidePortion; } - set - { - if (value <= 0) - { - throw new ArgumentOutOfRangeException(Strings.DockContentHandler_AutoHidePortion_OutOfRange); - } - - if (m_autoHidePortion == value) - { - return; - } - - m_autoHidePortion = value; - - if (DockPanel == null) - { - return; - } - - if (DockPanel.ActiveAutoHideContent == Content) - { - DockPanel.PerformLayout(); - } - } - } - - public bool CloseButton - { - get { return m_closeButton; } - set - { - if (m_closeButton == value) - { - return; - } - - m_closeButton = value; - if (Pane != null) - { - if (Pane.ActiveContent.DockHandler == this) - { - Pane.RefreshChanges(); - } - } - } - } - - /// - /// Determines whether the close button is visible on the content - /// - public bool CloseButtonVisible { get; set; } = true; - - private DockState DefaultDockState - { - get - { - if (ShowHint != DockState.Unknown && ShowHint != DockState.Hidden) - { - return ShowHint; - } - - if ((DockAreas & DockAreas.Document) != 0) - { - return DockState.Document; - } - if ((DockAreas & DockAreas.DockRight) != 0) - { - return DockState.DockRight; - } - if ((DockAreas & DockAreas.DockLeft) != 0) - { - return DockState.DockLeft; - } - if ((DockAreas & DockAreas.DockBottom) != 0) - { - return DockState.DockBottom; - } - if ((DockAreas & DockAreas.DockTop) != 0) - { - return DockState.DockTop; - } - - return DockState.Unknown; - } - } - - private DockState DefaultShowState - { - get - { - if (ShowHint != DockState.Unknown) - { - return ShowHint; - } - - if ((DockAreas & DockAreas.Document) != 0) - { - return DockState.Document; - } - if ((DockAreas & DockAreas.DockRight) != 0) - { - return DockState.DockRight; - } - if ((DockAreas & DockAreas.DockLeft) != 0) - { - return DockState.DockLeft; - } - if ((DockAreas & DockAreas.DockBottom) != 0) - { - return DockState.DockBottom; - } - if ((DockAreas & DockAreas.DockTop) != 0) - { - return DockState.DockTop; - } - if ((DockAreas & DockAreas.Float) != 0) - { - return DockState.Float; - } - - return DockState.Unknown; - } - } - - public DockAreas DockAreas - { - get { return m_allowedAreas; } - set - { - if (m_allowedAreas == value) - { - return; - } - - if (!DockHelper.IsDockStateValid(DockState, value)) - { - throw new InvalidOperationException(Strings.DockContentHandler_DockAreas_InvalidValue); - } - - m_allowedAreas = value; - - if (!DockHelper.IsDockStateValid(ShowHint, m_allowedAreas)) - { - ShowHint = DockState.Unknown; - } - } - } - - public DockState DockState - { - get { return m_dockState; } - set - { - if (m_dockState == value) - { - return; - } - - DockPanel.SuspendLayout(true); - - if (value == DockState.Hidden) - { - IsHidden = true; - } - else - { - SetDockState(false, value, Pane); - } - - DockPanel.ResumeLayout(true, true); - } - } - - public DockPanel DockPanel - { - get { return m_dockPanel; } - set - { - if (m_dockPanel == value) - { - return; - } - - Pane = null; - - if (m_dockPanel != null) - { - m_dockPanel.RemoveContent(Content); - } - - if (m_tab != null) - { - m_tab.Dispose(); - m_tab = null; - } - - if (AutoHideTab != null) - { - AutoHideTab.Dispose(); - AutoHideTab = null; - } - - m_dockPanel = value; - - if (m_dockPanel != null) - { - m_dockPanel.AddContent(Content); - Form.TopLevel = false; - Form.FormBorderStyle = FormBorderStyle.None; - Form.ShowInTaskbar = false; - Form.WindowState = FormWindowState.Normal; - NativeMethods.SetWindowPos(Form.Handle, IntPtr.Zero, 0, 0, 0, 0, - Win32.FlagsSetWindowPos.SWP_NOACTIVATE | - Win32.FlagsSetWindowPos.SWP_NOMOVE | - Win32.FlagsSetWindowPos.SWP_NOSIZE | - Win32.FlagsSetWindowPos.SWP_NOZORDER | - Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | - Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); - } - } - } - - public Icon Icon - { - get { return Form.Icon; } - } - - public DockPane Pane - { - get { return IsFloat ? FloatPane : PanelPane; } - set - { - if (Pane == value) - { - return; - } - - DockPanel.SuspendLayout(true); - - DockPane oldPane = Pane; - - SuspendSetDockState(); - FloatPane = value == null ? null : (value.IsFloat ? value : FloatPane); - PanelPane = value == null ? null : (value.IsFloat ? PanelPane : value); - ResumeSetDockState(IsHidden, value != null ? value.DockState : DockState.Unknown, oldPane); - - DockPanel.ResumeLayout(true, true); - } - } - - public bool IsHidden - { - get { return m_isHidden; } - set - { - if (m_isHidden == value) - { - return; - } - - SetDockState(value, VisibleState, Pane); - } - } - - public string TabText - { - get { return m_tabText == null || m_tabText == "" ? Form.Text : m_tabText; } - set - { - if (m_tabText == value) - { - return; - } - - m_tabText = value; - if (Pane != null) - { - Pane.RefreshChanges(); - } - } - } - - public DockState VisibleState - { - get { return m_visibleState; } - set - { - if (m_visibleState == value) - { - return; - } - - SetDockState(IsHidden, value, Pane); - } - } - - public bool IsFloat - { - get { return m_isFloat; } - set - { - if (m_isFloat == value) - { - return; - } - - DockState visibleState = CheckDockState(value); - - if (visibleState == DockState.Unknown) - { - throw new InvalidOperationException(Strings.DockContentHandler_IsFloat_InvalidValue); - } - - SetDockState(IsHidden, visibleState, Pane); - } - } - - public DockPane PanelPane - { - get { return m_panelPane; } - set - { - if (m_panelPane == value) - { - return; - } - - if (value != null) - { - if (value.IsFloat || value.DockPanel != DockPanel) - { - throw new InvalidOperationException(Strings.DockContentHandler_DockPane_InvalidValue); - } - } - - DockPane oldPane = Pane; - - if (m_panelPane != null) - { - RemoveFromPane(m_panelPane); - } - m_panelPane = value; - if (m_panelPane != null) - { - m_panelPane.AddContent(Content); - SetDockState(IsHidden, IsFloat ? DockState.Float : m_panelPane.DockState, oldPane); - } - else - { - SetDockState(IsHidden, DockState.Unknown, oldPane); - } - } - } - - public DockPane FloatPane - { - get { return m_floatPane; } - set - { - if (m_floatPane == value) - { - return; - } - - if (value != null) - { - if (!value.IsFloat || value.DockPanel != DockPanel) - { - throw new InvalidOperationException(Strings.DockContentHandler_FloatPane_InvalidValue); - } - } - - DockPane oldPane = Pane; - - if (m_floatPane != null) - { - RemoveFromPane(m_floatPane); - } - m_floatPane = value; - if (m_floatPane != null) - { - m_floatPane.AddContent(Content); - SetDockState(IsHidden, IsFloat ? DockState.Float : VisibleState, oldPane); - } - else - { - SetDockState(IsHidden, DockState.Unknown, oldPane); - } - } - } - - internal bool IsSuspendSetDockState - { - get { return m_countSetDockState != 0; } - } - - internal string PersistString - { - get { return GetPersistStringCallback == null ? Form.GetType().ToString() : GetPersistStringCallback(); } - } - - public GetPersistStringCallback GetPersistStringCallback { get; set; } = null; - - public bool HideOnClose { get; set; } = false; - - public DockState ShowHint - { - get { return m_showHint; } - set - { - if (!DockHelper.IsDockStateValid(value, DockAreas)) - { - throw new InvalidOperationException(Strings.DockContentHandler_ShowHint_InvalidValue); - } - - if (m_showHint == value) - { - return; - } - - m_showHint = value; - } - } - - public bool IsActivated - { - get { return m_isActivated; } - internal set - { - if (m_isActivated == value) - { - return; - } - - m_isActivated = value; - } - } - - public ContextMenuStrip TabPageContextMenu { get; set; } = null; - - public string ToolTipText { get; set; } = null; - - internal IntPtr ActiveWindowHandle { get; set; } = IntPtr.Zero; - - internal IDisposable AutoHideTab { get; set; } = null; - - internal bool FlagClipWindow - { - get { return m_flagClipWindow; } - set - { - if (m_flagClipWindow == value) - { - return; - } - - m_flagClipWindow = value; - if (m_flagClipWindow) - { - Form.Region = new Region(Rectangle.Empty); - } - else - { - Form.Region = null; - } - } - } - - public ContextMenuStrip TabPageContextMenuStrip { get; set; } = null; - - #endregion - - #region Public methods - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] - public DockState CheckDockState(bool isFloat) - { - DockState dockState; - - if (isFloat) - { - if (!IsDockStateValid(DockState.Float)) - { - dockState = DockState.Unknown; - } - else - { - dockState = DockState.Float; - } - } - else - { - dockState = PanelPane != null ? PanelPane.DockState : DefaultDockState; - if (dockState != DockState.Unknown && !IsDockStateValid(dockState)) - { - dockState = DockState.Unknown; - } - } - - return dockState; - } - - public bool IsDockStateValid(DockState dockState) - { - if (DockPanel != null && dockState == DockState.Document && - DockPanel.DocumentStyle == DocumentStyle.SystemMdi) - { - return false; - } - else - { - return DockHelper.IsDockStateValid(dockState, DockAreas); - } - } - - public void Activate() - { - if (DockPanel == null) - { - Form.Activate(); - } - else if (Pane == null) - { - Show(DockPanel); - } - else - { - IsHidden = false; - Pane.ActiveContent = Content; - if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) - { - Form.Activate(); - return; - } - else if (DockHelper.IsDockStateAutoHide(DockState)) - { - DockPanel.ActiveAutoHideContent = Content; - } - - if (!Form.ContainsFocus) - { - DockPanel.ContentFocusManager.Activate(Content); - } - } - } - - public void GiveUpFocus() - { - DockPanel.ContentFocusManager.GiveUpFocus(Content); - } - - public void Hide() - { - IsHidden = true; - } - - public void Show() - { - if (DockPanel == null) - { - Form.Show(); - } - else - { - Show(DockPanel); - } - } - - public void Show(DockPanel dockPanel) - { - if (dockPanel == null) - { - throw new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel); - } - - if (DockState == DockState.Unknown) - { - Show(dockPanel, DefaultShowState); - } - else - { - Activate(); - } - } - - public void Show(DockPanel dockPanel, DockState dockState) - { - if (dockPanel == null) - { - throw new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel); - } - - if (dockState == DockState.Unknown || dockState == DockState.Hidden) - { - throw new ArgumentException(Strings.DockContentHandler_Show_InvalidDockState); - } - - dockPanel.SuspendLayout(true); - - DockPanel = dockPanel; - - if (dockState == DockState.Float && FloatPane == null) - { - Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, true); - } - else if (PanelPane == null) - { - DockPane paneExisting = null; - foreach (DockPane pane in DockPanel.Panes) - { - if (pane.DockState == dockState) - { - paneExisting = pane; - break; - } - } - - if (paneExisting == null) - { - Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, dockState, true); - } - else - { - Pane = paneExisting; - } - } - - DockState = dockState; - dockPanel.ResumeLayout(true, true); //we'll resume the layout before activating to ensure that the position - Activate(); //and size of the form are finally processed before the form is shown - } - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] - public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) - { - if (dockPanel == null) - { - throw new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel); - } - - dockPanel.SuspendLayout(true); - - DockPanel = dockPanel; - if (FloatPane == null) - { - IsHidden = true; // to reduce the screen flicker - FloatPane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, false); - FloatPane.FloatWindow.StartPosition = FormStartPosition.Manual; - } - - FloatPane.FloatWindow.Bounds = floatWindowBounds; - - Show(dockPanel, DockState.Float); - Activate(); - - dockPanel.ResumeLayout(true, true); - } - - public void Show(DockPane pane, IDockContent beforeContent) - { - if (pane == null) - { - throw new ArgumentNullException(Strings.DockContentHandler_Show_NullPane); - } - - if (beforeContent != null && pane.Contents.IndexOf(beforeContent) == -1) - { - throw new ArgumentException(Strings.DockContentHandler_Show_InvalidBeforeContent); - } - - pane.DockPanel.SuspendLayout(true); - - DockPanel = pane.DockPanel; - Pane = pane; - pane.SetContentIndex(Content, pane.Contents.IndexOf(beforeContent)); - Show(); - - pane.DockPanel.ResumeLayout(true, true); - } - - public void Show(DockPane previousPane, DockAlignment alignment, double proportion) - { - if (previousPane == null) - { - throw new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane); - } - - if (DockHelper.IsDockStateAutoHide(previousPane.DockState)) - { - throw new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane); - } - - previousPane.DockPanel.SuspendLayout(true); - - DockPanel = previousPane.DockPanel; - DockPanel.DockPaneFactory.CreateDockPane(Content, previousPane, alignment, proportion, true); - Show(); - - previousPane.DockPanel.ResumeLayout(true, true); - } - - public void Close() - { - DockPanel dockPanel = DockPanel; - if (dockPanel != null) - { - dockPanel.SuspendLayout(true); - } - Form.Close(); - if (dockPanel != null) - { - dockPanel.ResumeLayout(true, true); - } - } - - #endregion - - #region Internals - - internal void SetDockState(bool isHidden, DockState visibleState, DockPane oldPane) - { - if (IsSuspendSetDockState) - { - return; - } - - if (DockPanel == null && visibleState != DockState.Unknown) - { - throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_NullPanel); - } - - if (visibleState == DockState.Hidden || - visibleState != DockState.Unknown && !IsDockStateValid(visibleState)) - { - throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_InvalidState); - } - - DockPanel dockPanel = DockPanel; - if (dockPanel != null) - { - dockPanel.SuspendLayout(true); - } - - SuspendSetDockState(); - - DockState oldDockState = DockState; - - if (m_isHidden != isHidden || oldDockState == DockState.Unknown) - { - m_isHidden = isHidden; - } - m_visibleState = visibleState; - m_dockState = isHidden ? DockState.Hidden : visibleState; - - if (visibleState == DockState.Unknown) - { - Pane = null; - } - else - { - m_isFloat = m_visibleState == DockState.Float; - - if (Pane == null) - { - Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); - } - else if (Pane.DockState != visibleState) - { - if (Pane.Contents.Count == 1) - { - Pane.SetDockState(visibleState); - } - else - { - Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); - } - } - } - - if (Form.ContainsFocus) - { - if (DockState == DockState.Hidden || DockState == DockState.Unknown) - { - DockPanel.ContentFocusManager.GiveUpFocus(Content); - } - } - - SetPaneAndVisible(Pane); - - if (oldPane != null && !oldPane.IsDisposed && oldDockState == oldPane.DockState) - { - RefreshDockPane(oldPane); - } - - if (Pane != null && DockState == Pane.DockState) - { - if (Pane != oldPane || - Pane == oldPane && oldDockState != oldPane.DockState) - // Avoid early refresh of hidden AutoHide panes - { - if ((Pane.DockWindow == null || Pane.DockWindow.Visible || Pane.IsHidden) && !Pane.IsAutoHide) - { - RefreshDockPane(Pane); - } - } - } - - if (oldDockState != DockState) - { - if (DockState == DockState.Hidden || DockState == DockState.Unknown || - DockHelper.IsDockStateAutoHide(DockState)) - { - DockPanel.ContentFocusManager.RemoveFromList(Content); - } - else - { - DockPanel.ContentFocusManager.AddToList(Content); - } - - OnDockStateChanged(EventArgs.Empty); - } - ResumeSetDockState(); - - if (dockPanel != null) - { - dockPanel.ResumeLayout(true, true); - } - } - - internal void SetPaneAndVisible(DockPane pane) - { - SetPane(pane); - SetVisible(); - } - - internal void SetVisible() - { - bool visible; - - if (IsHidden) - { - visible = false; - } - else if (Pane != null && Pane.DockState == DockState.Document && - DockPanel.DocumentStyle == DocumentStyle.DockingMdi) - { - visible = true; - } - else if (Pane != null && Pane.ActiveContent == Content) - { - visible = true; - } - else if (Pane != null && Pane.ActiveContent != Content) - { - visible = false; - } - else - { - visible = Form.Visible; - } - - if (Form.Visible != visible) - { - Form.Visible = visible; - } - } - - internal DockPaneStripBase.Tab GetTab(DockPaneStripBase dockPaneStrip) - { - if (m_tab == null) - { - m_tab = dockPaneStrip.CreateTab(Content); - } - - return m_tab; - } - - #endregion - - #region Private Methods - - private void RemoveFromPane(DockPane pane) - { - pane.RemoveContent(Content); - SetPane(null); - if (pane.Contents.Count == 0) - { - pane.Dispose(); - } - } - - private void SuspendSetDockState() - { - m_countSetDockState++; - } - - private void ResumeSetDockState() - { - m_countSetDockState--; - if (m_countSetDockState < 0) - { - m_countSetDockState = 0; - } - } - - private void ResumeSetDockState(bool isHidden, DockState visibleState, DockPane oldPane) - { - ResumeSetDockState(); - SetDockState(isHidden, visibleState, oldPane); - } - - private static void RefreshDockPane(DockPane pane) - { - pane.RefreshChanges(); - pane.ValidateActiveContent(); - } - - private void SetPane(DockPane pane) - { - if (pane != null && pane.DockState == DockState.Document && - DockPanel.DocumentStyle == DocumentStyle.DockingMdi) - { - if (Form.Parent is DockPane) - { - SetParent(null); - } - if (Form.MdiParent != DockPanel.ParentForm) - { - FlagClipWindow = true; - Form.MdiParent = DockPanel.ParentForm; - } - } - else - { - FlagClipWindow = true; - if (Form.MdiParent != null) - { - Form.MdiParent = null; - } - if (Form.TopLevel) - { - Form.TopLevel = false; - } - SetParent(pane); - } - } - - private void SetParent(Control value) - { - if (Form.Parent == value) - { - return; - } - - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - // Workaround of .Net Framework bug: - // Change the parent of a control with focus may result in the first - // MDI child form get activated. - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - bool bRestoreFocus = false; - if (Form.ContainsFocus) - { - //Suggested as a fix for a memory leak by bugreports - if (value == null && !IsFloat) - { - DockPanel.ContentFocusManager.GiveUpFocus(this.Content); - } - else - { - DockPanel.SaveFocus(); - bRestoreFocus = true; - } - } - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - - Form.Parent = value; - - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - // Workaround of .Net Framework bug: - // Change the parent of a control with focus may result in the first - // MDI child form get activated. - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - if (bRestoreFocus) - { - Activate(); - } - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - } - - #endregion - - #region Events handler - - private void Form_Disposed(object sender, EventArgs e) - { - Dispose(); - } - - private void Form_TextChanged(object sender, EventArgs e) - { - if (DockHelper.IsDockStateAutoHide(DockState)) - { - DockPanel.RefreshAutoHideStrip(); - } - else if (Pane != null) - { - if (Pane.FloatWindow != null) - { - Pane.FloatWindow.SetText(); - } - Pane.RefreshChanges(); - } - } - - #endregion - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - lock (this) - { - DockPanel = null; - if (AutoHideTab != null) - { - AutoHideTab.Dispose(); - } - if (m_tab != null) - { - m_tab.Dispose(); - } - - Form.Disposed -= new EventHandler(Form_Disposed); - Form.TextChanged -= new EventHandler(Form_TextChanged); - Events.Dispose(); - } - } - } - - protected virtual void OnDockStateChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[DockStateChangedEvent]; - if (handler != null) - { - handler(this, e); - } - } - - #region IDockDragSource Members - - Control IDragSource.DragControl - { - get { return Form; } - } - - bool IDockDragSource.CanDockTo(DockPane pane) - { - if (!IsDockStateValid(pane.DockState)) - { - return false; - } - - if (Pane == pane && pane.DisplayingContents.Count == 1) - { - return false; - } - - return true; - } - - Rectangle IDockDragSource.BeginDrag(Point ptMouse) - { - Size size; - DockPane floatPane = this.FloatPane; - if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) - { - size = DockPanel.DefaultFloatWindowSize; - } - else - { - size = floatPane.FloatWindow.Size; - } - - Point location; - Rectangle rectPane = Pane.ClientRectangle; - if (DockState == DockState.Document) - { - if (Pane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - location = new Point(rectPane.Left, rectPane.Bottom - size.Height); - } - else - { - location = new Point(rectPane.Left, rectPane.Top); - } - } - else - { - location = new Point(rectPane.Left, rectPane.Bottom); - location.Y -= size.Height; - } - location = Pane.PointToScreen(location); - - if (ptMouse.X > location.X + size.Width) - { - location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; - } - - return new Rectangle(location, size); - } - - public void FloatAt(Rectangle floatWindowBounds) - { - DockPane pane = DockPanel.DockPaneFactory.CreateDockPane(Content, floatWindowBounds, true); - } - - public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) - { - if (dockStyle == DockStyle.Fill) - { - bool samePane = Pane == pane; - if (!samePane) - { - Pane = pane; - } - - if (contentIndex == -1 || !samePane) - { - pane.SetContentIndex(Content, contentIndex); - } - else - { - DockContentCollection contents = pane.Contents; - int oldIndex = contents.IndexOf(Content); - int newIndex = contentIndex; - if (oldIndex < newIndex) - { - newIndex += 1; - if (newIndex > contents.Count - 1) - { - newIndex = -1; - } - } - pane.SetContentIndex(Content, newIndex); - } - } - else - { - DockPane paneFrom = DockPanel.DockPaneFactory.CreateDockPane(Content, pane.DockState, true); - INestedPanesContainer container = pane.NestedPanesContainer; - if (dockStyle == DockStyle.Left) - { - paneFrom.DockTo(container, pane, DockAlignment.Left, 0.5); - } - else if (dockStyle == DockStyle.Right) - { - paneFrom.DockTo(container, pane, DockAlignment.Right, 0.5); - } - else if (dockStyle == DockStyle.Top) - { - paneFrom.DockTo(container, pane, DockAlignment.Top, 0.5); - } - else if (dockStyle == DockStyle.Bottom) - { - paneFrom.DockTo(container, pane, DockAlignment.Bottom, 0.5); - } - - paneFrom.DockState = pane.DockState; - } - } - - public void DockTo(DockPanel panel, DockStyle dockStyle) - { - if (panel != DockPanel) - { - throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); - } - - DockPane pane; - - if (dockStyle == DockStyle.Top) - { - pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockTop, true); - } - else if (dockStyle == DockStyle.Bottom) - { - pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockBottom, true); - } - else if (dockStyle == DockStyle.Left) - { - pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockLeft, true); - } - else if (dockStyle == DockStyle.Right) - { - pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockRight, true); - } - else if (dockStyle == DockStyle.Fill) - { - pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Document, true); - } - else - { - return; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockOutlineBase.cs b/src/WinFormsUI/Docking/DockOutlineBase.cs deleted file mode 100644 index 4b817776..00000000 --- a/src/WinFormsUI/Docking/DockOutlineBase.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal abstract class DockOutlineBase - { - #region Fields - - #endregion - - #region cTor - - public DockOutlineBase() - { - Init(); - } - - #endregion - - #region Properties - - protected Rectangle OldFloatWindowBounds { get; private set; } - - protected Control OldDockTo { get; private set; } - - protected DockStyle OldDock { get; private set; } - - protected int OldContentIndex { get; private set; } - - protected bool SameAsOldValue - { - get - { - return FloatWindowBounds == OldFloatWindowBounds && - DockTo == OldDockTo && - Dock == OldDock && - ContentIndex == OldContentIndex; - } - } - - public Rectangle FloatWindowBounds { get; private set; } - - public Control DockTo { get; private set; } - - public DockStyle Dock { get; private set; } - - public int ContentIndex { get; private set; } - - public bool FlagFullEdge - { - get { return ContentIndex != 0; } - } - - public bool FlagTestDrop { get; set; } = false; - - #endregion - - #region Public methods - - public void Show() - { - SaveOldValues(); - SetValues(Rectangle.Empty, null, DockStyle.None, -1); - TestChange(); - } - - public void Show(DockPane pane, DockStyle dock) - { - SaveOldValues(); - SetValues(Rectangle.Empty, pane, dock, -1); - TestChange(); - } - - public void Show(DockPane pane, int contentIndex) - { - SaveOldValues(); - SetValues(Rectangle.Empty, pane, DockStyle.Fill, contentIndex); - TestChange(); - } - - public void Show(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) - { - SaveOldValues(); - SetValues(Rectangle.Empty, dockPanel, dock, fullPanelEdge ? -1 : 0); - TestChange(); - } - - public void Show(Rectangle floatWindowBounds) - { - SaveOldValues(); - SetValues(floatWindowBounds, null, DockStyle.None, -1); - TestChange(); - } - - public void Close() - { - OnClose(); - } - - #endregion - - #region Private Methods - - private void Init() - { - SetValues(Rectangle.Empty, null, DockStyle.None, -1); - SaveOldValues(); - } - - private void SaveOldValues() - { - OldDockTo = DockTo; - OldDock = Dock; - OldContentIndex = ContentIndex; - OldFloatWindowBounds = FloatWindowBounds; - } - - private void SetValues(Rectangle floatWindowBounds, Control dockTo, DockStyle dock, int contentIndex) - { - FloatWindowBounds = floatWindowBounds; - DockTo = dockTo; - Dock = dock; - ContentIndex = contentIndex; - FlagTestDrop = true; - } - - private void TestChange() - { - if (FloatWindowBounds != OldFloatWindowBounds || - DockTo != OldDockTo || - Dock != OldDock || - ContentIndex != OldContentIndex) - { - OnShow(); - } - } - - #endregion - - protected abstract void OnShow(); - - protected abstract void OnClose(); - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPane.SplitterControl.cs b/src/WinFormsUI/Docking/DockPane.SplitterControl.cs deleted file mode 100644 index 9f3854ac..00000000 --- a/src/WinFormsUI/Docking/DockPane.SplitterControl.cs +++ /dev/null @@ -1,199 +0,0 @@ -using System; -using System.Collections; -using System.ComponentModel; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - partial class DockPane - { - #region Fields - - #endregion - - #region Properties - - private SplitterControl Splitter { get; set; } - - internal Rectangle SplitterBounds - { - set { Splitter.Bounds = value; } - } - - internal DockAlignment SplitterAlignment - { - set { Splitter.Alignment = value; } - } - - #endregion - - private class SplitterControl : Control, ISplitterDragSource - { - #region Fields - - private DockAlignment m_alignment; - - #endregion - - #region cTor - - public SplitterControl(DockPane pane) - { - SetStyle(ControlStyles.Selectable, false); - DockPane = pane; - } - - #endregion - - #region Properties - - public DockPane DockPane { get; } - - public DockAlignment Alignment - { - get { return m_alignment; } - set - { - m_alignment = value; - if (m_alignment == DockAlignment.Left || m_alignment == DockAlignment.Right) - { - Cursor = Cursors.VSplit; - } - else if (m_alignment == DockAlignment.Top || m_alignment == DockAlignment.Bottom) - { - Cursor = Cursors.HSplit; - } - else - { - Cursor = Cursors.Default; - } - - if (DockPane.DockState == DockState.Document) - { - Invalidate(); - } - } - } - - #endregion - - #region Overrides - - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - - if (DockPane.DockState != DockState.Document) - { - return; - } - - Graphics g = e.Graphics; - Rectangle rect = ClientRectangle; - if (Alignment == DockAlignment.Top || Alignment == DockAlignment.Bottom) - { - g.DrawLine(SystemPens.ControlDark, rect.Left, rect.Bottom - 1, rect.Right, rect.Bottom - 1); - } - else if (Alignment == DockAlignment.Left || Alignment == DockAlignment.Right) - { - g.DrawLine(SystemPens.ControlDarkDark, rect.Right - 1, rect.Top, rect.Right - 1, rect.Bottom); - } - } - - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - if (e.Button != MouseButtons.Left) - { - return; - } - - DockPane.DockPanel.BeginDrag(this, Parent.RectangleToScreen(Bounds)); - } - - #endregion - - #region ISplitterDragSource Members - - void ISplitterDragSource.BeginDrag(Rectangle rectSplitter) - { - } - - void ISplitterDragSource.EndDrag() - { - } - - bool ISplitterDragSource.IsVertical - { - get - { - NestedDockingStatus status = DockPane.NestedDockingStatus; - return status.DisplayingAlignment == DockAlignment.Left || - status.DisplayingAlignment == DockAlignment.Right; - } - } - - Rectangle ISplitterDragSource.DragLimitBounds - { - get - { - NestedDockingStatus status = DockPane.NestedDockingStatus; - Rectangle rectLimit = Parent.RectangleToScreen(status.LogicalBounds); - if (((ISplitterDragSource) this).IsVertical) - { - rectLimit.X += MeasurePane.MinSize; - rectLimit.Width -= 2 * MeasurePane.MinSize; - } - else - { - rectLimit.Y += MeasurePane.MinSize; - rectLimit.Height -= 2 * MeasurePane.MinSize; - } - - return rectLimit; - } - } - - void ISplitterDragSource.MoveSplitter(int offset) - { - NestedDockingStatus status = DockPane.NestedDockingStatus; - double proportion = status.Proportion; - if (status.LogicalBounds.Width <= 0 || status.LogicalBounds.Height <= 0) - { - return; - } - else if (status.DisplayingAlignment == DockAlignment.Left) - { - proportion += (double) offset / (double) status.LogicalBounds.Width; - } - else if (status.DisplayingAlignment == DockAlignment.Right) - { - proportion -= (double) offset / (double) status.LogicalBounds.Width; - } - else if (status.DisplayingAlignment == DockAlignment.Top) - { - proportion += (double) offset / (double) status.LogicalBounds.Height; - } - else - { - proportion -= (double) offset / (double) status.LogicalBounds.Height; - } - - DockPane.SetNestedDockingProportion(proportion); - } - - #region IDragSource Members - - Control IDragSource.DragControl - { - get { return this; } - } - - #endregion - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPane.cs b/src/WinFormsUI/Docking/DockPane.cs deleted file mode 100644 index ec395b13..00000000 --- a/src/WinFormsUI/Docking/DockPane.cs +++ /dev/null @@ -1,1610 +0,0 @@ -using System; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - [ToolboxItem(false)] - public partial class DockPane : UserControl, IDockDragSource - { - #region Fields - - private static readonly object DockStateChangedEvent = new object(); - - private static readonly object IsActivatedChangedEvent = new object(); - - private static readonly object IsActiveDocumentPaneChangedEvent = new object(); - - private IDockContent m_activeContent = null; - - private int m_countRefreshStateChange = 0; - - private DockState m_dockState = DockState.Unknown; - - #endregion - - #region cTor - - internal protected DockPane(IDockContent content, DockState visibleState, bool show) - { - InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show); - } - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] - internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show) - { - if (floatWindow == null) - { - throw new ArgumentNullException("floatWindow"); - } - - InternalConstruct(content, DockState.Float, false, Rectangle.Empty, - floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show); - } - - internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, - double proportion, bool show) - { - if (previousPane == null) - { - throw new ArgumentNullException("previousPane"); - } - InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, - proportion, show); - } - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] - internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show) - { - InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show); - } - - #endregion - - #region Events - - public event EventHandler DockStateChanged - { - add { Events.AddHandler(DockStateChangedEvent, value); } - remove { Events.RemoveHandler(DockStateChangedEvent, value); } - } - - public event EventHandler IsActivatedChanged - { - add { Events.AddHandler(IsActivatedChangedEvent, value); } - remove { Events.RemoveHandler(IsActivatedChangedEvent, value); } - } - - public event EventHandler IsActiveDocumentPaneChanged - { - add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); } - remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); } - } - - #endregion - - #region Properties - - private DockPaneCaptionBase CaptionControl { get; set; } - - public DockPaneStripBase TabStripControl { get; private set; } - - public virtual IDockContent ActiveContent - { - get { return m_activeContent; } - set - { - if (ActiveContent == value) - { - return; - } - - if (value != null) - { - if (!DisplayingContents.Contains(value)) - { - throw new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue); - } - } - else - { - if (DisplayingContents.Count != 0) - { - throw new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue); - } - } - - IDockContent oldValue = m_activeContent; - - if (DockPanel.ActiveAutoHideContent == oldValue) - { - DockPanel.ActiveAutoHideContent = null; - } - - m_activeContent = value; - - if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) - { - if (m_activeContent != null) - { - m_activeContent.DockHandler.Form.BringToFront(); - } - } - else - { - if (m_activeContent != null) - { - m_activeContent.DockHandler.SetVisible(); - } - if (oldValue != null && DisplayingContents.Contains(oldValue)) - { - oldValue.DockHandler.SetVisible(); - } - if (IsActivated && m_activeContent != null) - { - m_activeContent.DockHandler.Activate(); - } - } - - if (FloatWindow != null) - { - FloatWindow.SetText(); - } - - if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && - DockState == DockState.Document) - { - RefreshChanges(false); // delayed layout to reduce screen flicker - } - else - { - RefreshChanges(); - } - - if (m_activeContent != null) - { - TabStripControl.EnsureTabVisible(m_activeContent); - } - } - } - - public virtual bool AllowDockDragAndDrop { get; set; } = true; - - internal IDisposable AutoHidePane { get; set; } = null; - - internal object AutoHideTabs { get; set; } = null; - - private object TabPageContextMenu - { - get - { - IDockContent content = ActiveContent; - - if (content == null) - { - return null; - } - - if (content.DockHandler.TabPageContextMenuStrip != null) - { - return content.DockHandler.TabPageContextMenuStrip; - } - else if (content.DockHandler.TabPageContextMenu != null) - { - return content.DockHandler.TabPageContextMenu; - } - else - { - return null; - } - } - } - - internal bool HasTabPageContextMenu - { - get { return TabPageContextMenu != null; } - } - - private Rectangle CaptionRectangle - { - get - { - if (!HasCaption) - { - return Rectangle.Empty; - } - - Rectangle rectWindow = DisplayingRectangle; - int x, y, width; - x = rectWindow.X; - y = rectWindow.Y; - width = rectWindow.Width; - int height = CaptionControl.MeasureHeight(); - - return new Rectangle(x, y, width, height); - } - } - - internal Rectangle ContentRectangle - { - get - { - Rectangle rectWindow = DisplayingRectangle; - Rectangle rectCaption = CaptionRectangle; - Rectangle rectTabStrip = TabStripRectangle; - - int x = rectWindow.X; - - int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height); - if (DockState == DockState.Document && - DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top) - { - y += rectTabStrip.Height; - } - - int width = rectWindow.Width; - int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height; - - return new Rectangle(x, y, width, height); - } - } - - internal Rectangle TabStripRectangle - { - get - { - if (Appearance == AppearanceStyle.ToolWindow) - { - return TabStripRectangle_ToolWindow; - } - else - { - return TabStripRectangle_Document; - } - } - } - - private Rectangle TabStripRectangle_ToolWindow - { - get - { - if (DisplayingContents.Count <= 1 || IsAutoHide) - { - return Rectangle.Empty; - } - - Rectangle rectWindow = DisplayingRectangle; - - int width = rectWindow.Width; - int height = TabStripControl.MeasureHeight(); - int x = rectWindow.X; - int y = rectWindow.Bottom - height; - Rectangle rectCaption = CaptionRectangle; - if (rectCaption.Contains(x, y)) - { - y = rectCaption.Y + rectCaption.Height; - } - - return new Rectangle(x, y, width, height); - } - } - - private Rectangle TabStripRectangle_Document - { - get - { - if (DisplayingContents.Count == 0) - { - return Rectangle.Empty; - } - - if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi) - { - return Rectangle.Empty; - } - - Rectangle rectWindow = DisplayingRectangle; - int x = rectWindow.X; - int width = rectWindow.Width; - int height = TabStripControl.MeasureHeight(); - - int y = 0; - if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - y = rectWindow.Height - height; - } - else - { - y = rectWindow.Y; - } - - return new Rectangle(x, y, width, height); - } - } - - public virtual string CaptionText - { - get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; } - } - - public DockContentCollection Contents { get; private set; } - - public DockContentCollection DisplayingContents { get; private set; } - - public DockPanel DockPanel { get; private set; } - - private bool HasCaption - { - get - { - if (DockState == DockState.Document || - DockState == DockState.Hidden || - DockState == DockState.Unknown || - DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1) - { - return false; - } - else - { - return true; - } - } - } - - public bool IsActivated { get; private set; } = false; - - public bool IsActiveDocumentPane { get; private set; } = false; - - public bool IsAutoHide - { - get { return DockHelper.IsDockStateAutoHide(DockState); } - } - - public AppearanceStyle Appearance - { - get { return DockState == DockState.Document ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; } - } - - internal Rectangle DisplayingRectangle - { - get { return ClientRectangle; } - } - - public bool IsHidden { get; private set; } = true; - - public DockWindow DockWindow - { - get - { - return NestedDockingStatus.NestedPanes == null - ? null - : NestedDockingStatus.NestedPanes.Container as DockWindow; - } - set - { - DockWindow oldValue = DockWindow; - if (oldValue == value) - { - return; - } - - DockTo(value); - } - } - - public FloatWindow FloatWindow - { - get - { - return NestedDockingStatus.NestedPanes == null - ? null - : NestedDockingStatus.NestedPanes.Container as FloatWindow; - } - set - { - FloatWindow oldValue = FloatWindow; - if (oldValue == value) - { - return; - } - - DockTo(value); - } - } - - public NestedDockingStatus NestedDockingStatus { get; private set; } - - public bool IsFloat { get; private set; } - - public INestedPanesContainer NestedPanesContainer - { - get - { - if (NestedDockingStatus.NestedPanes == null) - { - return null; - } - else - { - return NestedDockingStatus.NestedPanes.Container; - } - } - } - - public DockState DockState - { - get { return m_dockState; } - set { SetDockState(value); } - } - - private bool IsRefreshStateChangeSuspended - { - get { return m_countRefreshStateChange != 0; } - } - - #endregion - - #region Public methods - - public bool IsDockStateValid(DockState dockState) - { - foreach (IDockContent content in Contents) - { - if (!content.DockHandler.IsDockStateValid(dockState)) - { - return false; - } - } - - return true; - } - - public void Activate() - { - if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent) - { - DockPanel.ActiveAutoHideContent = ActiveContent; - } - else if (!IsActivated && ActiveContent != null) - { - ActiveContent.DockHandler.Activate(); - } - } - - public void CloseActiveContent() - { - CloseContent(ActiveContent); - } - - public void SetContentIndex(IDockContent content, int index) - { - int oldIndex = Contents.IndexOf(content); - if (oldIndex == -1) - { - throw new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent); - } - - if (index < 0 || index > Contents.Count - 1) - { - if (index != -1) - { - throw new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex); - } - } - - if (oldIndex == index) - { - return; - } - if (oldIndex == Contents.Count - 1 && index == -1) - { - return; - } - - Contents.Remove(content); - if (index == -1) - { - Contents.Add(content); - } - else if (oldIndex < index) - { - Contents.AddAt(content, index - 1); - } - else - { - Contents.AddAt(content, index); - } - - RefreshChanges(); - } - - public new void Show() - { - Activate(); - } - - public DockPane SetDockState(DockState value) - { - if (value == DockState.Unknown || value == DockState.Hidden) - { - throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState); - } - - if (value == DockState.Float == this.IsFloat) - { - InternalSetDockState(value); - return this; - } - - if (DisplayingContents.Count == 0) - { - return null; - } - - IDockContent firstContent = null; - for (int i = 0; i < DisplayingContents.Count; i++) - { - IDockContent content = DisplayingContents[i]; - if (content.DockHandler.IsDockStateValid(value)) - { - firstContent = content; - break; - } - } - if (firstContent == null) - { - return null; - } - - firstContent.DockHandler.DockState = value; - DockPane pane = firstContent.DockHandler.Pane; - DockPanel.SuspendLayout(true); - for (int i = 0; i < DisplayingContents.Count; i++) - { - IDockContent content = DisplayingContents[i]; - if (content.DockHandler.IsDockStateValid(value)) - { - content.DockHandler.Pane = pane; - } - } - DockPanel.ResumeLayout(true, true); - return pane; - } - - public DockPane DockTo(INestedPanesContainer container) - { - if (container == null) - { - throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); - } - - DockAlignment alignment; - if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight) - { - alignment = DockAlignment.Bottom; - } - else - { - alignment = DockAlignment.Right; - } - - return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5); - } - - public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, - double proportion) - { - if (container == null) - { - throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); - } - - if (container.IsFloat == this.IsFloat) - { - InternalAddToDockList(container, previousPane, alignment, proportion); - return this; - } - - IDockContent firstContent = GetFirstContent(container.DockState); - if (firstContent == null) - { - return null; - } - - DockPane pane; - DockPanel.DummyContent.DockPanel = DockPanel; - if (container.IsFloat) - { - pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow) container, true); - } - else - { - pane = DockPanel.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true); - } - - pane.DockTo(container, previousPane, alignment, proportion); - SetVisibleContentsToPane(pane); - DockPanel.DummyContent.DockPanel = null; - - return pane; - } - - public void SetNestedDockingProportion(double proportion) - { - NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, - NestedDockingStatus.Alignment, proportion); - if (NestedPanesContainer != null) - { - ((Control) NestedPanesContainer).PerformLayout(); - } - } - - public DockPane Float() - { - DockPanel.SuspendLayout(true); - - IDockContent activeContent = ActiveContent; - - DockPane floatPane = GetFloatPaneFromContents(); - if (floatPane == null) - { - IDockContent firstContent = GetFirstContent(DockState.Float); - if (firstContent == null) - { - DockPanel.ResumeLayout(true, true); - return null; - } - floatPane = DockPanel.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true); - } - SetVisibleContentsToPane(floatPane, activeContent); - - DockPanel.ResumeLayout(true, true); - return floatPane; - } - - public void RestoreToPanel() - { - DockPanel.SuspendLayout(true); - - IDockContent activeContent = DockPanel.ActiveContent; - - for (int i = DisplayingContents.Count - 1; i >= 0; i--) - { - IDockContent content = DisplayingContents[i]; - if (content.DockHandler.CheckDockState(false) != DockState.Unknown) - { - content.DockHandler.IsFloat = false; - } - } - - DockPanel.ResumeLayout(true, true); - } - - #endregion - - #region Internals - - internal void ShowTabPageContextMenu(Control control, Point position) - { - object menu = TabPageContextMenu; - - if (menu == null) - { - return; - } - - if (menu is ContextMenuStrip contextMenuStrip) - { - contextMenuStrip.Show(control, position); - return; - } - - if (menu is ContextMenuStrip contextMenu) - { - contextMenu.Show(this, position); - } - } - - internal void SetIsActivated(bool value) - { - if (IsActivated == value) - { - return; - } - - IsActivated = value; - if (DockState != DockState.Document) - { - RefreshChanges(false); - } - OnIsActivatedChanged(EventArgs.Empty); - } - - internal void SetIsActiveDocumentPane(bool value) - { - if (IsActiveDocumentPane == value) - { - return; - } - - IsActiveDocumentPane = value; - if (DockState == DockState.Document) - { - RefreshChanges(); - } - OnIsActiveDocumentPaneChanged(EventArgs.Empty); - } - - internal void AddContent(IDockContent content) - { - if (Contents.Contains(content)) - { - return; - } - - Contents.Add(content); - } - - internal void Close() - { - Dispose(); - } - - internal void CloseContent(IDockContent content) - { - DockPanel dockPanel = DockPanel; - - if (content == null) - { - return; - } - - if (!content.DockHandler.CloseButton) - { - return; - } - - dockPanel.SuspendLayout(true); - - try - { - if (content.DockHandler.HideOnClose) - { - content.DockHandler.Hide(); - NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); - } - else - { - content.DockHandler.Close(); - } - } - finally - { - dockPanel.ResumeLayout(true, true); - } - } - - internal void SetContentBounds() - { - Rectangle rectContent = ContentRectangle; - if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) - { - rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent)); - } - - Rectangle rectInactive = - new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height); - foreach (IDockContent content in Contents) - { - if (content.DockHandler.Pane == this) - { - if (content == ActiveContent) - { - content.DockHandler.Form.Bounds = rectContent; - } - else - { - content.DockHandler.Form.Bounds = rectInactive; - } - } - } - } - - internal void RefreshChanges() - { - RefreshChanges(true); - } - - internal void RemoveContent(IDockContent content) - { - if (!Contents.Contains(content)) - { - return; - } - - Contents.Remove(content); - } - - internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) - { - if (!dragSource.CanDockTo(this)) - { - return; - } - - Point ptMouse = Control.MousePosition; - - HitTestResult hitTestResult = GetHitTest(ptMouse); - if (hitTestResult.HitArea == HitTestArea.Caption) - { - dockOutline.Show(this, -1); - } - else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1) - { - dockOutline.Show(this, hitTestResult.Index); - } - } - - internal void ValidateActiveContent() - { - if (ActiveContent == null) - { - if (DisplayingContents.Count != 0) - { - ActiveContent = DisplayingContents[0]; - } - return; - } - - if (DisplayingContents.IndexOf(ActiveContent) >= 0) - { - return; - } - - IDockContent prevVisible = null; - for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--) - { - if (Contents[i].DockHandler.DockState == DockState) - { - prevVisible = Contents[i]; - break; - } - } - - IDockContent nextVisible = null; - for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++) - { - if (Contents[i].DockHandler.DockState == DockState) - { - nextVisible = Contents[i]; - break; - } - } - - if (prevVisible != null) - { - ActiveContent = prevVisible; - } - else if (nextVisible != null) - { - ActiveContent = nextVisible; - } - else - { - ActiveContent = null; - } - } - - #endregion - - #region Overrides - - protected override void Dispose(bool disposing) - { - if (disposing) - { - m_dockState = DockState.Unknown; - - if (NestedPanesContainer != null) - { - NestedPanesContainer.NestedPanes.Remove(this); - } - - if (DockPanel != null) - { - DockPanel.RemovePane(this); - DockPanel = null; - } - - Splitter.Dispose(); - if (AutoHidePane != null) - { - AutoHidePane.Dispose(); - } - } - base.Dispose(disposing); - } - - protected override void OnLayout(LayoutEventArgs levent) - { - SetIsHidden(DisplayingContents.Count == 0); - if (!IsHidden) - { - CaptionControl.Bounds = CaptionRectangle; - TabStripControl.Bounds = TabStripRectangle; - - SetContentBounds(); - - foreach (IDockContent content in Contents) - { - if (DisplayingContents.Contains(content)) - { - if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible) - { - content.DockHandler.FlagClipWindow = false; - } - } - } - } - - base.OnLayout(levent); - } - - protected override void WndProc(ref Message m) - { - if (m.Msg == (int) Win32.Msgs.WM_MOUSEACTIVATE) - { - Activate(); - } - - base.WndProc(ref m); - } - - #endregion - - #region Private Methods - - private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, - Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show) - { - if (dockState == DockState.Hidden || dockState == DockState.Unknown) - { - throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState); - } - - if (content == null) - { - throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent); - } - - if (content.DockHandler.DockPanel == null) - { - throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel); - } - - - SuspendLayout(); - SetStyle(ControlStyles.Selectable, false); - - IsFloat = dockState == DockState.Float; - - Contents = new DockContentCollection(); - DisplayingContents = new DockContentCollection(this); - DockPanel = content.DockHandler.DockPanel; - DockPanel.AddPane(this); - - Splitter = new SplitterControl(this); - - NestedDockingStatus = new NestedDockingStatus(this); - - CaptionControl = DockPanel.DockPaneCaptionFactory.CreateDockPaneCaption(this); - TabStripControl = DockPanel.DockPaneStripFactory.CreateDockPaneStrip(this); - Controls.AddRange(new Control[] {CaptionControl, TabStripControl}); - - DockPanel.SuspendLayout(true); - if (flagBounds) - { - FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); - } - else if (prevPane != null) - { - DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion); - } - - SetDockState(dockState); - if (show) - { - content.DockHandler.Pane = this; - } - else if (this.IsFloat) - { - content.DockHandler.FloatPane = this; - } - else - { - content.DockHandler.PanelPane = this; - } - - ResumeLayout(); - DockPanel.ResumeLayout(true, true); - } - - private HitTestResult GetHitTest(Point ptMouse) - { - Point ptMouseClient = PointToClient(ptMouse); - - Rectangle rectCaption = CaptionRectangle; - if (rectCaption.Contains(ptMouseClient)) - { - return new HitTestResult(HitTestArea.Caption, -1); - } - - Rectangle rectContent = ContentRectangle; - if (rectContent.Contains(ptMouseClient)) - { - return new HitTestResult(HitTestArea.Content, -1); - } - - Rectangle rectTabStrip = TabStripRectangle; - if (rectTabStrip.Contains(ptMouseClient)) - { - return new HitTestResult(HitTestArea.TabStrip, - TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse))); - } - - return new HitTestResult(HitTestArea.None, -1); - } - - private void SetIsHidden(bool value) - { - if (IsHidden == value) - { - return; - } - - IsHidden = value; - if (DockHelper.IsDockStateAutoHide(DockState)) - { - DockPanel.RefreshAutoHideStrip(); - DockPanel.PerformLayout(); - } - else if (NestedPanesContainer != null) - { - ((Control) NestedPanesContainer).PerformLayout(); - } - } - - private void RefreshChanges(bool performLayout) - { - if (IsDisposed) - { - return; - } - - CaptionControl.RefreshChanges(); - TabStripControl.RefreshChanges(); - if (DockState == DockState.Float && FloatWindow != null) - { - FloatWindow.RefreshChanges(); - } - if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null) - { - DockPanel.RefreshAutoHideStrip(); - DockPanel.PerformLayout(); - } - - if (performLayout) - { - PerformLayout(); - } - } - - private void SetParent() - { - if (DockState == DockState.Unknown || DockState == DockState.Hidden) - { - SetParent(null); - Splitter.Parent = null; - } - else if (DockState == DockState.Float) - { - SetParent(FloatWindow); - Splitter.Parent = FloatWindow; - } - else if (DockHelper.IsDockStateAutoHide(DockState)) - { - SetParent(DockPanel.AutoHideControl); - Splitter.Parent = null; - } - else - { - SetParent(DockPanel.DockWindows[DockState]); - Splitter.Parent = Parent; - } - } - - private void SetParent(Control value) - { - if (Parent == value) - { - return; - } - - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - // Workaround of .Net Framework bug: - // Change the parent of a control with focus may result in the first - // MDI child form get activated. - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - IDockContent contentFocused = GetFocusedContent(); - if (contentFocused != null) - { - DockPanel.SaveFocus(); - } - - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - - Parent = value; - - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - // Workaround of .Net Framework bug: - // Change the parent of a control with focus may result in the first - // MDI child form get activated. - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - if (contentFocused != null) - { - contentFocused.DockHandler.Activate(); - } - //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! - } - - private void InternalSetDockState(DockState value) - { - if (m_dockState == value) - { - return; - } - - DockState oldDockState = m_dockState; - INestedPanesContainer oldContainer = NestedPanesContainer; - - m_dockState = value; - - SuspendRefreshStateChange(); - - IDockContent contentFocused = GetFocusedContent(); - if (contentFocused != null) - { - DockPanel.SaveFocus(); - } - - if (!IsFloat) - { - DockWindow = DockPanel.DockWindows[DockState]; - } - else if (FloatWindow == null) - { - FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this); - } - - if (contentFocused != null) - { - DockPanel.ContentFocusManager.Activate(contentFocused); - } - - ResumeRefreshStateChange(oldContainer, oldDockState); - } - - private void SuspendRefreshStateChange() - { - m_countRefreshStateChange++; - DockPanel.SuspendLayout(true); - } - - private void ResumeRefreshStateChange() - { - m_countRefreshStateChange--; - System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0); - DockPanel.ResumeLayout(true, true); - } - - private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) - { - ResumeRefreshStateChange(); - RefreshStateChange(oldContainer, oldDockState); - } - - private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) - { - lock (this) - { - if (IsRefreshStateChangeSuspended) - { - return; - } - - SuspendRefreshStateChange(); - } - - DockPanel.SuspendLayout(true); - - IDockContent contentFocused = GetFocusedContent(); - if (contentFocused != null) - { - DockPanel.SaveFocus(); - } - SetParent(); - - if (ActiveContent != null) - { - ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, - ActiveContent.DockHandler.Pane); - } - foreach (IDockContent content in Contents) - { - if (content.DockHandler.Pane == this) - { - content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane); - } - } - - if (oldContainer != null) - { - Control oldContainerControl = (Control) oldContainer; - if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed) - { - oldContainerControl.PerformLayout(); - } - } - if (DockHelper.IsDockStateAutoHide(oldDockState)) - { - DockPanel.RefreshActiveAutoHideContent(); - } - - if (NestedPanesContainer.DockState == DockState) - { - ((Control) NestedPanesContainer).PerformLayout(); - } - if (DockHelper.IsDockStateAutoHide(DockState)) - { - DockPanel.RefreshActiveAutoHideContent(); - } - - if (DockHelper.IsDockStateAutoHide(oldDockState) || - DockHelper.IsDockStateAutoHide(DockState)) - { - DockPanel.RefreshAutoHideStrip(); - DockPanel.PerformLayout(); - } - - ResumeRefreshStateChange(); - - if (contentFocused != null) - { - contentFocused.DockHandler.Activate(); - } - - DockPanel.ResumeLayout(true, true); - - if (oldDockState != DockState) - { - OnDockStateChanged(EventArgs.Empty); - } - } - - private IDockContent GetFocusedContent() - { - IDockContent contentFocused = null; - foreach (IDockContent content in Contents) - { - if (content.DockHandler.Form.ContainsFocus) - { - contentFocused = content; - break; - } - } - - return contentFocused; - } - - private void SetVisibleContentsToPane(DockPane pane) - { - SetVisibleContentsToPane(pane, ActiveContent); - } - - private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent) - { - for (int i = 0; i < DisplayingContents.Count; i++) - { - IDockContent content = DisplayingContents[i]; - if (content.DockHandler.IsDockStateValid(pane.DockState)) - { - content.DockHandler.Pane = pane; - i--; - } - } - - if (activeContent.DockHandler.Pane == pane) - { - pane.ActiveContent = activeContent; - } - } - - private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, - double proportion) - { - if (container.DockState == DockState.Float != IsFloat) - { - throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer); - } - - int count = container.NestedPanes.Count; - if (container.NestedPanes.Contains(this)) - { - count--; - } - if (prevPane == null && count > 0) - { - throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane); - } - - if (prevPane != null && !container.NestedPanes.Contains(prevPane)) - { - throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane); - } - - if (prevPane == this) - { - throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane); - } - - INestedPanesContainer oldContainer = NestedPanesContainer; - DockState oldDockState = DockState; - container.NestedPanes.Add(this); - NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion); - - if (DockHelper.IsDockWindowState(DockState)) - { - m_dockState = container.DockState; - } - - RefreshStateChange(oldContainer, oldDockState); - } - - private DockPane GetFloatPaneFromContents() - { - DockPane floatPane = null; - for (int i = 0; i < DisplayingContents.Count; i++) - { - IDockContent content = DisplayingContents[i]; - if (!content.DockHandler.IsDockStateValid(DockState.Float)) - { - continue; - } - - if (floatPane != null && content.DockHandler.FloatPane != floatPane) - { - return null; - } - else - { - floatPane = content.DockHandler.FloatPane; - } - } - - return floatPane; - } - - private IDockContent GetFirstContent(DockState dockState) - { - for (int i = 0; i < DisplayingContents.Count; i++) - { - IDockContent content = DisplayingContents[i]; - if (content.DockHandler.IsDockStateValid(dockState)) - { - return content; - } - } - return null; - } - - #endregion - - protected virtual void OnDockStateChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[DockStateChangedEvent]; - if (handler != null) - { - handler(this, e); - } - } - - protected virtual void OnIsActivatedChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[IsActivatedChangedEvent]; - if (handler != null) - { - handler(this, e); - } - } - - protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[IsActiveDocumentPaneChangedEvent]; - if (handler != null) - { - handler(this, e); - } - } - - private enum HitTestArea - { - Caption, - TabStrip, - Content, - None - } - - private struct HitTestResult - { - public readonly HitTestArea HitArea; - public readonly int Index; - - public HitTestResult(HitTestArea hitTestArea, int index) - { - HitArea = hitTestArea; - Index = index; - } - } - - public enum AppearanceStyle - { - ToolWindow, - Document - } - - #region IDockDragSource Members - - #region IDragSource Members - - Control IDragSource.DragControl - { - get { return this; } - } - - #endregion - - bool IDockDragSource.IsDockStateValid(DockState dockState) - { - return IsDockStateValid(dockState); - } - - bool IDockDragSource.CanDockTo(DockPane pane) - { - if (!IsDockStateValid(pane.DockState)) - { - return false; - } - - if (pane == this) - { - return false; - } - - return true; - } - - Rectangle IDockDragSource.BeginDrag(Point ptMouse) - { - Point location = PointToScreen(new Point(0, 0)); - Size size; - - DockPane floatPane = ActiveContent.DockHandler.FloatPane; - if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) - { - size = DockPanel.DefaultFloatWindowSize; - } - else - { - size = floatPane.FloatWindow.Size; - } - - if (ptMouse.X > location.X + size.Width) - { - location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; - } - - return new Rectangle(location, size); - } - - public void FloatAt(Rectangle floatWindowBounds) - { - if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1) - { - FloatWindow = DockPanel.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); - } - else - { - FloatWindow.Bounds = floatWindowBounds; - } - - DockState = DockState.Float; - - NestedDockingStatus.NestedPanes.Remove(this); - } - - public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) - { - if (dockStyle == DockStyle.Fill) - { - IDockContent activeContent = ActiveContent; - for (int i = Contents.Count - 1; i >= 0; i--) - { - IDockContent c = Contents[i]; - if (c.DockHandler.DockState == DockState) - { - c.DockHandler.Pane = pane; - if (contentIndex != -1) - { - pane.SetContentIndex(c, contentIndex); - } - } - } - pane.ActiveContent = activeContent; - } - else - { - if (dockStyle == DockStyle.Left) - { - DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5); - } - else if (dockStyle == DockStyle.Right) - { - DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5); - } - else if (dockStyle == DockStyle.Top) - { - DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5); - } - else if (dockStyle == DockStyle.Bottom) - { - DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5); - } - - DockState = pane.DockState; - } - } - - public void DockTo(DockPanel panel, DockStyle dockStyle) - { - if (panel != DockPanel) - { - throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); - } - - if (dockStyle == DockStyle.Top) - { - DockState = DockState.DockTop; - } - else if (dockStyle == DockStyle.Bottom) - { - DockState = DockState.DockBottom; - } - else if (dockStyle == DockStyle.Left) - { - DockState = DockState.DockLeft; - } - else if (dockStyle == DockStyle.Right) - { - DockState = DockState.DockRight; - } - else if (dockStyle == DockStyle.Fill) - { - DockState = DockState.Document; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPaneCaptionBase.cs b/src/WinFormsUI/Docking/DockPaneCaptionBase.cs deleted file mode 100644 index 2c2d5f92..00000000 --- a/src/WinFormsUI/Docking/DockPaneCaptionBase.cs +++ /dev/null @@ -1,122 +0,0 @@ -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public abstract class DockPaneCaptionBase : Control - { - #region Fields - - #endregion - - #region cTor - - protected internal DockPaneCaptionBase(DockPane pane) - { - DockPane = pane; - - SetStyle(ControlStyles.OptimizedDoubleBuffer | - ControlStyles.ResizeRedraw | - ControlStyles.UserPaint | - ControlStyles.AllPaintingInWmPaint, true); - SetStyle(ControlStyles.Selectable, false); - } - - #endregion - - #region Properties - - protected DockPane DockPane { get; } - - protected DockPane.AppearanceStyle Appearance - { - get { return DockPane.Appearance; } - } - - protected bool HasTabPageContextMenu - { - get { return DockPane.HasTabPageContextMenu; } - } - - #endregion - - #region Internals - - internal void RefreshChanges() - { - if (IsDisposed) - { - return; - } - - OnRefreshChanges(); - } - - #endregion - - #region Overrides - - protected override void OnMouseUp(MouseEventArgs e) - { - base.OnMouseUp(e); - - if (e.Button == MouseButtons.Right) - { - ShowTabPageContextMenu(new Point(e.X, e.Y)); - } - } - - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - if (e.Button == MouseButtons.Left && - DockPane.DockPanel.AllowEndUserDocking && - DockPane.AllowDockDragAndDrop && - !DockHelper.IsDockStateAutoHide(DockPane.DockState) && - DockPane.ActiveContent != null) - { - DockPane.DockPanel.BeginDrag(DockPane); - } - } - - protected override void WndProc(ref Message m) - { - if (m.Msg == (int) Win32.Msgs.WM_LBUTTONDBLCLK) - { - if (DockHelper.IsDockStateAutoHide(DockPane.DockState)) - { - DockPane.DockPanel.ActiveAutoHideContent = null; - return; - } - - if (DockPane.IsFloat) - { - DockPane.RestoreToPanel(); - } - else - { - DockPane.Float(); - } - } - base.WndProc(ref m); - } - - #endregion - - protected void ShowTabPageContextMenu(Point position) - { - DockPane.ShowTabPageContextMenu(this, position); - } - - protected virtual void OnRightToLeftLayoutChanged() - { - } - - protected virtual void OnRefreshChanges() - { - } - - protected internal abstract int MeasureHeight(); - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPaneCollection.cs b/src/WinFormsUI/Docking/DockPaneCollection.cs deleted file mode 100644 index 3ff997c3..00000000 --- a/src/WinFormsUI/Docking/DockPaneCollection.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System; -using System.Collections.ObjectModel; -using System.Collections.Generic; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public class DockPaneCollection : ReadOnlyCollection - { - #region cTor - - internal DockPaneCollection() - : base(new List()) - { - } - - #endregion - - #region Internals - - internal int Add(DockPane pane) - { - if (Items.Contains(pane)) - { - return Items.IndexOf(pane); - } - - Items.Add(pane); - return Count - 1; - } - - internal void AddAt(DockPane pane, int index) - { - if (index < 0 || index > Items.Count - 1) - { - return; - } - - if (Contains(pane)) - { - return; - } - - Items.Insert(index, pane); - } - - internal void Dispose() - { - for (int i = Count - 1; i >= 0; i--) - { - this[i].Close(); - } - } - - internal void Remove(DockPane pane) - { - Items.Remove(pane); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPaneStripBase.cs b/src/WinFormsUI/Docking/DockPaneStripBase.cs deleted file mode 100644 index 62fce1bf..00000000 --- a/src/WinFormsUI/Docking/DockPaneStripBase.cs +++ /dev/null @@ -1,327 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public abstract class DockPaneStripBase : Control - { - #region Fields - - private TabCollection m_tabs = null; - - #endregion - - #region cTor - - protected DockPaneStripBase(DockPane pane) - { - DockPane = pane; - - SetStyle(ControlStyles.OptimizedDoubleBuffer, true); - SetStyle(ControlStyles.Selectable, false); - AllowDrop = true; - } - - #endregion - - #region Properties - - protected DockPane DockPane { get; } - - protected DockPane.AppearanceStyle Appearance - { - get { return DockPane.Appearance; } - } - - protected TabCollection Tabs - { - get - { - if (m_tabs == null) - { - m_tabs = new TabCollection(DockPane); - } - - return m_tabs; - } - } - - protected bool HasTabPageContextMenu - { - get { return DockPane.HasTabPageContextMenu; } - } - - #endregion - - #region Internals - - internal void RefreshChanges() - { - if (IsDisposed) - { - return; - } - - OnRefreshChanges(); - } - - #endregion - - #region Overrides - - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - int index = HitTest(); - if (index != -1) - { - IDockContent content = Tabs[index].Content; - if (DockPane.ActiveContent != content) - { - DockPane.ActiveContent = content; - } - } - - if (e.Button == MouseButtons.Left) - { - if (DockPane.DockPanel.AllowEndUserDocking && DockPane.AllowDockDragAndDrop && - DockPane.ActiveContent.DockHandler.AllowEndUserDocking) - { - DockPane.DockPanel.BeginDrag(DockPane.ActiveContent.DockHandler); - } - } - } - - protected override void OnMouseUp(MouseEventArgs e) - { - base.OnMouseUp(e); - - if (e.Button == MouseButtons.Right) - { - ShowTabPageContextMenu(new Point(e.X, e.Y)); - } - else if (e.Button == MouseButtons.Middle && - DockPane.Appearance == Docking.DockPane.AppearanceStyle.Document) - { - // Get the content located under the click (if there is one) - int index = HitTest(); - if (index != -1) - { - // Close the specified content. - IDockContent content = Tabs[index].Content; - DockPane.CloseContent(content); - } - } - } - - protected override void WndProc(ref Message m) - { - if (m.Msg == (int) Win32.Msgs.WM_LBUTTONDBLCLK) - { - base.WndProc(ref m); - - int index = HitTest(); - if (DockPane.DockPanel.AllowEndUserDocking && index != -1) - { - IDockContent content = Tabs[index].Content; - if (content.DockHandler.CheckDockState(!content.DockHandler.IsFloat) != DockState.Unknown) - { - content.DockHandler.IsFloat = !content.DockHandler.IsFloat; - } - } - - return; - } - - base.WndProc(ref m); - return; - } - - protected override void OnDragOver(DragEventArgs drgevent) - { - base.OnDragOver(drgevent); - - int index = HitTest(); - if (index != -1) - { - IDockContent content = Tabs[index].Content; - if (DockPane.ActiveContent != content) - { - DockPane.ActiveContent = content; - } - } - } - - #endregion - - protected virtual void OnRefreshChanges() - { - } - - protected internal abstract int MeasureHeight(); - - protected internal abstract void EnsureTabVisible(IDockContent content); - - protected int HitTest() - { - return HitTest(PointToClient(Control.MousePosition)); - } - - protected internal abstract int HitTest(Point point); - - protected internal abstract GraphicsPath GetOutline(int index); - - protected internal virtual Tab CreateTab(IDockContent content) - { - return new Tab(content); - } - - protected void ShowTabPageContextMenu(Point position) - { - DockPane.ShowTabPageContextMenu(this, position); - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - protected internal class Tab : IDisposable - { - #region Fields - - #endregion - - #region cTor - - public Tab(IDockContent content) - { - Content = content; - } - - #endregion - - #region Properties - - public IDockContent Content { get; } - - public Form ContentForm - { - get { return Content as Form; } - } - - #endregion - - #region Public methods - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - #endregion - - ~Tab() - { - Dispose(false); - } - - protected virtual void Dispose(bool disposing) - { - } - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - protected sealed class TabCollection : IEnumerable - { - #region Fields - - #endregion - - #region cTor - - internal TabCollection(DockPane pane) - { - DockPane = pane; - } - - #endregion - - #region Properties - - public DockPane DockPane { get; } - - public int Count - { - get { return DockPane.DisplayingContents.Count; } - } - - public Tab this[int index] - { - get - { - IDockContent content = DockPane.DisplayingContents[index]; - if (content == null) - { - throw new ArgumentOutOfRangeException("index"); - } - return content.DockHandler.GetTab(DockPane.TabStripControl); - } - } - - #endregion - - #region Public methods - - public bool Contains(Tab tab) - { - return IndexOf(tab) != -1; - } - - public bool Contains(IDockContent content) - { - return IndexOf(content) != -1; - } - - public int IndexOf(Tab tab) - { - if (tab == null) - { - return -1; - } - - return DockPane.DisplayingContents.IndexOf(tab.Content); - } - - public int IndexOf(IDockContent content) - { - return DockPane.DisplayingContents.IndexOf(content); - } - - #endregion - - #region IEnumerable Members - - IEnumerator IEnumerable.GetEnumerator() - { - for (int i = 0; i < Count; i++) - { - yield return this[i]; - } - } - - IEnumerator IEnumerable.GetEnumerator() - { - for (int i = 0; i < Count; i++) - { - yield return this[i]; - } - } - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.AutoHideWindow.cs b/src/WinFormsUI/Docking/DockPanel.AutoHideWindow.cs deleted file mode 100644 index 068dcb29..00000000 --- a/src/WinFormsUI/Docking/DockPanel.AutoHideWindow.cs +++ /dev/null @@ -1,768 +0,0 @@ -using System; -using System.Windows.Forms; -using System.Drawing; -using System.Runtime.InteropServices; - -namespace WeifenLuo.WinFormsUI.Docking -{ - partial class DockPanel - { - #region Properties - - private AutoHideWindowControl AutoHideWindow { get; } - - internal Control AutoHideControl - { - get { return AutoHideWindow; } - } - - internal Rectangle AutoHideWindowRectangle - { - get - { - DockState state = AutoHideWindow.DockState; - Rectangle rectDockArea = DockArea; - if (ActiveAutoHideContent == null) - { - return Rectangle.Empty; - } - - if (Parent == null) - { - return Rectangle.Empty; - } - - Rectangle rect = Rectangle.Empty; - double autoHideSize = ActiveAutoHideContent.DockHandler.AutoHidePortion; - if (state == DockState.DockLeftAutoHide) - { - if (autoHideSize < 1) - { - autoHideSize = rectDockArea.Width * autoHideSize; - } - if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize) - { - autoHideSize = rectDockArea.Width - MeasurePane.MinSize; - } - rect.X = rectDockArea.X; - rect.Y = rectDockArea.Y; - rect.Width = (int) autoHideSize; - rect.Height = rectDockArea.Height; - } - else if (state == DockState.DockRightAutoHide) - { - if (autoHideSize < 1) - { - autoHideSize = rectDockArea.Width * autoHideSize; - } - if (autoHideSize > rectDockArea.Width - MeasurePane.MinSize) - { - autoHideSize = rectDockArea.Width - MeasurePane.MinSize; - } - rect.X = rectDockArea.X + rectDockArea.Width - (int) autoHideSize; - rect.Y = rectDockArea.Y; - rect.Width = (int) autoHideSize; - rect.Height = rectDockArea.Height; - } - else if (state == DockState.DockTopAutoHide) - { - if (autoHideSize < 1) - { - autoHideSize = rectDockArea.Height * autoHideSize; - } - if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize) - { - autoHideSize = rectDockArea.Height - MeasurePane.MinSize; - } - rect.X = rectDockArea.X; - rect.Y = rectDockArea.Y; - rect.Width = rectDockArea.Width; - rect.Height = (int) autoHideSize; - } - else if (state == DockState.DockBottomAutoHide) - { - if (autoHideSize < 1) - { - autoHideSize = rectDockArea.Height * autoHideSize; - } - if (autoHideSize > rectDockArea.Height - MeasurePane.MinSize) - { - autoHideSize = rectDockArea.Height - MeasurePane.MinSize; - } - rect.X = rectDockArea.X; - rect.Y = rectDockArea.Y + rectDockArea.Height - (int) autoHideSize; - rect.Width = rectDockArea.Width; - rect.Height = (int) autoHideSize; - } - - return rect; - } - } - - #endregion - - #region Internals - - internal void RefreshActiveAutoHideContent() - { - AutoHideWindow.RefreshActiveContent(); - } - - internal Rectangle GetAutoHideWindowBounds(Rectangle rectAutoHideWindow) - { - if (DocumentStyle == DocumentStyle.SystemMdi || - DocumentStyle == DocumentStyle.DockingMdi) - { - return Parent == null - ? Rectangle.Empty - : Parent.RectangleToClient(RectangleToScreen(rectAutoHideWindow)); - } - else - { - return rectAutoHideWindow; - } - } - - internal void RefreshAutoHideStrip() - { - AutoHideStripControl.RefreshChanges(); - } - - #endregion - - private class AutoHideWindowControl : Panel, ISplitterDragSource - { - #region Fields - - #region consts - - private const int ANIMATE_TIME = 100; // in mini-seconds - - #endregion - - private IDockContent m_activeContent = null; - - private bool m_flagDragging = false; - private readonly SplitterControl m_splitter; - - private readonly Timer m_timerMouseTrack; - - #endregion - - #region cTor - - public AutoHideWindowControl(DockPanel dockPanel) - { - DockPanel = dockPanel; - - m_timerMouseTrack = new Timer(); - m_timerMouseTrack.Tick += new EventHandler(TimerMouseTrack_Tick); - - Visible = false; - m_splitter = new SplitterControl(this); - Controls.Add(m_splitter); - } - - #endregion - - #region Properties - - public DockPanel DockPanel { get; } = null; - - public DockPane ActivePane { get; private set; } = null; - - public IDockContent ActiveContent - { - get { return m_activeContent; } - set - { - if (value == m_activeContent) - { - return; - } - - if (value != null) - { - if (!DockHelper.IsDockStateAutoHide(value.DockHandler.DockState) || - value.DockHandler.DockPanel != DockPanel) - { - throw new InvalidOperationException(Strings.DockPanel_ActiveAutoHideContent_InvalidValue); - } - } - - DockPanel.SuspendLayout(); - - if (m_activeContent != null) - { - if (m_activeContent.DockHandler.Form.ContainsFocus) - { - DockPanel.ContentFocusManager.GiveUpFocus(m_activeContent); - } - AnimateWindow(false); - } - - m_activeContent = value; - SetActivePane(); - if (ActivePane != null) - { - ActivePane.ActiveContent = m_activeContent; - } - - if (m_activeContent != null) - { - AnimateWindow(true); - } - - DockPanel.ResumeLayout(); - DockPanel.RefreshAutoHideStrip(); - - SetTimerMouseTrack(); - } - } - - public DockState DockState - { - get { return ActiveContent == null ? DockState.Unknown : ActiveContent.DockHandler.DockState; } - } - - private bool FlagAnimate { get; set; } = true; - - internal bool FlagDragging - { - get { return m_flagDragging; } - set - { - if (m_flagDragging == value) - { - return; - } - - m_flagDragging = value; - SetTimerMouseTrack(); - } - } - - protected virtual Rectangle DisplayingRectangle - { - get - { - Rectangle rect = ClientRectangle; - - // exclude the border and the splitter - if (DockState == DockState.DockBottomAutoHide) - { - rect.Y += 2 + Measures.SplitterSize; - rect.Height -= 2 + Measures.SplitterSize; - } - else if (DockState == DockState.DockRightAutoHide) - { - rect.X += 2 + Measures.SplitterSize; - rect.Width -= 2 + Measures.SplitterSize; - } - else if (DockState == DockState.DockTopAutoHide) - { - rect.Height -= 2 + Measures.SplitterSize; - } - else if (DockState == DockState.DockLeftAutoHide) - { - rect.Width -= 2 + Measures.SplitterSize; - } - - return rect; - } - } - - #endregion - - #region Public methods - - public void RefreshActiveContent() - { - if (ActiveContent == null) - { - return; - } - - if (!DockHelper.IsDockStateAutoHide(ActiveContent.DockHandler.DockState)) - { - FlagAnimate = false; - ActiveContent = null; - FlagAnimate = true; - } - } - - public void RefreshActivePane() - { - SetTimerMouseTrack(); - } - - #endregion - - #region Overrides - - protected override void Dispose(bool disposing) - { - if (disposing) - { - m_timerMouseTrack.Dispose(); - } - base.Dispose(disposing); - } - - protected override void OnLayout(LayoutEventArgs levent) - { - DockPadding.All = 0; - if (DockState == DockState.DockLeftAutoHide) - { - DockPadding.Right = 2; - m_splitter.Dock = DockStyle.Right; - } - else if (DockState == DockState.DockRightAutoHide) - { - DockPadding.Left = 2; - m_splitter.Dock = DockStyle.Left; - } - else if (DockState == DockState.DockTopAutoHide) - { - DockPadding.Bottom = 2; - m_splitter.Dock = DockStyle.Bottom; - } - else if (DockState == DockState.DockBottomAutoHide) - { - DockPadding.Top = 2; - m_splitter.Dock = DockStyle.Top; - } - - Rectangle rectDisplaying = DisplayingRectangle; - Rectangle rectHidden = new Rectangle(-rectDisplaying.Width, rectDisplaying.Y, rectDisplaying.Width, - rectDisplaying.Height); - foreach (Control c in Controls) - { - DockPane pane = c as DockPane; - if (pane == null) - { - continue; - } - - - if (pane == ActivePane) - { - pane.Bounds = rectDisplaying; - } - else - { - pane.Bounds = rectHidden; - } - } - - base.OnLayout(levent); - } - - protected override void OnPaint(PaintEventArgs e) - { - // Draw the border - Graphics g = e.Graphics; - - if (DockState == DockState.DockBottomAutoHide) - { - g.DrawLine(SystemPens.ControlLightLight, 0, 1, ClientRectangle.Right, 1); - } - else if (DockState == DockState.DockRightAutoHide) - { - g.DrawLine(SystemPens.ControlLightLight, 1, 0, 1, ClientRectangle.Bottom); - } - else if (DockState == DockState.DockTopAutoHide) - { - g.DrawLine(SystemPens.ControlDark, 0, ClientRectangle.Height - 2, ClientRectangle.Right, - ClientRectangle.Height - 2); - g.DrawLine(SystemPens.ControlDarkDark, 0, ClientRectangle.Height - 1, ClientRectangle.Right, - ClientRectangle.Height - 1); - } - else if (DockState == DockState.DockLeftAutoHide) - { - g.DrawLine(SystemPens.ControlDark, ClientRectangle.Width - 2, 0, ClientRectangle.Width - 2, - ClientRectangle.Bottom); - g.DrawLine(SystemPens.ControlDarkDark, ClientRectangle.Width - 1, 0, ClientRectangle.Width - 1, - ClientRectangle.Bottom); - } - - base.OnPaint(e); - } - - #endregion - - #region Private Methods - - private void SetActivePane() - { - DockPane value = ActiveContent == null ? null : ActiveContent.DockHandler.Pane; - - if (value == ActivePane) - { - return; - } - - ActivePane = value; - } - - private void AnimateWindow(bool show) - { - if (!FlagAnimate && Visible != show) - { - Visible = show; - return; - } - - Parent.SuspendLayout(); - - Rectangle rectSource = GetRectangle(!show); - Rectangle rectTarget = GetRectangle(show); - int dxLoc, dyLoc; - int dWidth, dHeight; - dxLoc = dyLoc = dWidth = dHeight = 0; - if (DockState == DockState.DockTopAutoHide) - { - dHeight = show ? 1 : -1; - } - else if (DockState == DockState.DockLeftAutoHide) - { - dWidth = show ? 1 : -1; - } - else if (DockState == DockState.DockRightAutoHide) - { - dxLoc = show ? -1 : 1; - dWidth = show ? 1 : -1; - } - else if (DockState == DockState.DockBottomAutoHide) - { - dyLoc = show ? -1 : 1; - dHeight = show ? 1 : -1; - } - - if (show) - { - Bounds = DockPanel.GetAutoHideWindowBounds(new Rectangle(-rectTarget.Width, -rectTarget.Height, - rectTarget.Width, rectTarget.Height)); - if (Visible == false) - { - Visible = true; - } - PerformLayout(); - } - - SuspendLayout(); - - LayoutAnimateWindow(rectSource); - if (Visible == false) - { - Visible = true; - } - - int speedFactor = 1; - int totalPixels = rectSource.Width != rectTarget.Width - ? Math.Abs(rectSource.Width - rectTarget.Width) - : Math.Abs(rectSource.Height - rectTarget.Height); - int remainPixels = totalPixels; - DateTime startingTime = DateTime.Now; - while (rectSource != rectTarget) - { - DateTime startPerMove = DateTime.Now; - - rectSource.X += dxLoc * speedFactor; - rectSource.Y += dyLoc * speedFactor; - rectSource.Width += dWidth * speedFactor; - rectSource.Height += dHeight * speedFactor; - if (Math.Sign(rectTarget.X - rectSource.X) != Math.Sign(dxLoc)) - { - rectSource.X = rectTarget.X; - } - if (Math.Sign(rectTarget.Y - rectSource.Y) != Math.Sign(dyLoc)) - { - rectSource.Y = rectTarget.Y; - } - if (Math.Sign(rectTarget.Width - rectSource.Width) != Math.Sign(dWidth)) - { - rectSource.Width = rectTarget.Width; - } - if (Math.Sign(rectTarget.Height - rectSource.Height) != Math.Sign(dHeight)) - { - rectSource.Height = rectTarget.Height; - } - - LayoutAnimateWindow(rectSource); - if (Parent != null) - { - Parent.Update(); - } - - remainPixels -= speedFactor; - - while (true) - { - TimeSpan time = new TimeSpan(0, 0, 0, 0, ANIMATE_TIME); - TimeSpan elapsedPerMove = DateTime.Now - startPerMove; - TimeSpan elapsedTime = DateTime.Now - startingTime; - if ((int) (time - elapsedTime).TotalMilliseconds <= 0) - { - speedFactor = remainPixels; - break; - } - else - { - speedFactor = remainPixels * (int) elapsedPerMove.TotalMilliseconds / - (int) (time - elapsedTime).TotalMilliseconds; - } - if (speedFactor >= 1) - { - break; - } - } - } - ResumeLayout(); - Parent.ResumeLayout(); - } - - private void LayoutAnimateWindow(Rectangle rect) - { - Bounds = DockPanel.GetAutoHideWindowBounds(rect); - - Rectangle rectClient = ClientRectangle; - - if (DockState == DockState.DockLeftAutoHide) - { - ActivePane.Location = new Point(rectClient.Right - 2 - Measures.SplitterSize - ActivePane.Width, - ActivePane.Location.Y); - } - else if (DockState == DockState.DockTopAutoHide) - { - ActivePane.Location = new Point(ActivePane.Location.X, - rectClient.Bottom - 2 - Measures.SplitterSize - ActivePane.Height); - } - } - - private Rectangle GetRectangle(bool show) - { - if (DockState == DockState.Unknown) - { - return Rectangle.Empty; - } - - Rectangle rect = DockPanel.AutoHideWindowRectangle; - - if (show) - { - return rect; - } - - if (DockState == DockState.DockLeftAutoHide) - { - rect.Width = 0; - } - else if (DockState == DockState.DockRightAutoHide) - { - rect.X += rect.Width; - rect.Width = 0; - } - else if (DockState == DockState.DockTopAutoHide) - { - rect.Height = 0; - } - else - { - rect.Y += rect.Height; - rect.Height = 0; - } - - return rect; - } - - private void SetTimerMouseTrack() - { - if (ActivePane == null || ActivePane.IsActivated || FlagDragging) - { - m_timerMouseTrack.Enabled = false; - return; - } - - // start the timer - int hovertime = SystemInformation.MouseHoverTime; - - // assign a default value 400 in case of setting Timer.Interval invalid value exception - if (hovertime <= 0) - { - hovertime = 400; - } - - m_timerMouseTrack.Interval = 2 * (int) hovertime; - m_timerMouseTrack.Enabled = true; - } - - #endregion - - #region Events handler - - private void TimerMouseTrack_Tick(object sender, EventArgs e) - { - if (IsDisposed) - { - return; - } - - if (ActivePane == null || ActivePane.IsActivated) - { - m_timerMouseTrack.Enabled = false; - return; - } - - DockPane pane = ActivePane; - Point ptMouseInAutoHideWindow = PointToClient(Control.MousePosition); - Point ptMouseInDockPanel = DockPanel.PointToClient(Control.MousePosition); - - Rectangle rectTabStrip = DockPanel.GetTabStripRectangle(pane.DockState); - - if (!ClientRectangle.Contains(ptMouseInAutoHideWindow) && !rectTabStrip.Contains(ptMouseInDockPanel)) - { - ActiveContent = null; - m_timerMouseTrack.Enabled = false; - } - } - - #endregion - - private class SplitterControl : SplitterBase - { - #region Fields - - #endregion - - #region cTor - - public SplitterControl(AutoHideWindowControl autoHideWindow) - { - AutoHideWindow = autoHideWindow; - } - - #endregion - - #region Properties - - private AutoHideWindowControl AutoHideWindow { get; } - - protected override int SplitterSize - { - get { return Measures.SplitterSize; } - } - - #endregion - - #region Overrides - - protected override void StartDrag() - { - AutoHideWindow.DockPanel.BeginDrag(AutoHideWindow, AutoHideWindow.RectangleToScreen(Bounds)); - } - - #endregion - } - - #region ISplitterDragSource Members - - void ISplitterDragSource.BeginDrag(Rectangle rectSplitter) - { - FlagDragging = true; - } - - void ISplitterDragSource.EndDrag() - { - FlagDragging = false; - } - - bool ISplitterDragSource.IsVertical - { - get { return DockState == DockState.DockLeftAutoHide || DockState == DockState.DockRightAutoHide; } - } - - Rectangle ISplitterDragSource.DragLimitBounds - { - get - { - Rectangle rectLimit = DockPanel.DockArea; - - if ((this as ISplitterDragSource).IsVertical) - { - rectLimit.X += MeasurePane.MinSize; - rectLimit.Width -= 2 * MeasurePane.MinSize; - } - else - { - rectLimit.Y += MeasurePane.MinSize; - rectLimit.Height -= 2 * MeasurePane.MinSize; - } - - return DockPanel.RectangleToScreen(rectLimit); - } - } - - void ISplitterDragSource.MoveSplitter(int offset) - { - Rectangle rectDockArea = DockPanel.DockArea; - IDockContent content = ActiveContent; - if (DockState == DockState.DockLeftAutoHide && rectDockArea.Width > 0) - { - if (content.DockHandler.AutoHidePortion < 1) - { - content.DockHandler.AutoHidePortion += (double) offset / (double) rectDockArea.Width; - } - else - { - content.DockHandler.AutoHidePortion = Width + offset; - } - } - else if (DockState == DockState.DockRightAutoHide && rectDockArea.Width > 0) - { - if (content.DockHandler.AutoHidePortion < 1) - { - content.DockHandler.AutoHidePortion -= (double) offset / (double) rectDockArea.Width; - } - else - { - content.DockHandler.AutoHidePortion = Width - offset; - } - } - else if (DockState == DockState.DockBottomAutoHide && rectDockArea.Height > 0) - { - if (content.DockHandler.AutoHidePortion < 1) - { - content.DockHandler.AutoHidePortion -= (double) offset / (double) rectDockArea.Height; - } - else - { - content.DockHandler.AutoHidePortion = Height - offset; - } - } - else if (DockState == DockState.DockTopAutoHide && rectDockArea.Height > 0) - { - if (content.DockHandler.AutoHidePortion < 1) - { - content.DockHandler.AutoHidePortion += (double) offset / (double) rectDockArea.Height; - } - else - { - content.DockHandler.AutoHidePortion = Height + offset; - } - } - } - - #region IDragSource Members - - Control IDragSource.DragControl - { - get { return this; } - } - - #endregion - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.DockDragHandler.cs b/src/WinFormsUI/Docking/DockPanel.DockDragHandler.cs deleted file mode 100644 index 3d57c302..00000000 --- a/src/WinFormsUI/Docking/DockPanel.DockDragHandler.cs +++ /dev/null @@ -1,1073 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.ComponentModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - partial class DockPanel - { - #region Fields - - private DockDragHandler m_dockDragHandler = null; - - #endregion - - #region Internals - - internal void BeginDrag(IDockDragSource dragSource) - { - GetDockDragHandler().BeginDrag(dragSource); - } - - #endregion - - #region Private Methods - - private DockDragHandler GetDockDragHandler() - { - if (m_dockDragHandler == null) - { - m_dockDragHandler = new DockDragHandler(this); - } - return m_dockDragHandler; - } - - #endregion - - private sealed class DockDragHandler : DragHandler - { - #region Fields - - #endregion - - #region cTor - - public DockDragHandler(DockPanel panel) - : base(panel) - { - } - - #endregion - - #region Properties - - public new IDockDragSource DragSource - { - get { return base.DragSource as IDockDragSource; } - set { base.DragSource = value; } - } - - public DockOutlineBase Outline { get; private set; } - - private DockIndicator Indicator { get; set; } - - private Rectangle FloatOutlineBounds { get; set; } - - #endregion - - #region Public methods - - public void BeginDrag(IDockDragSource dragSource) - { - DragSource = dragSource; - - if (!BeginDrag()) - { - DragSource = null; - return; - } - - Outline = new DockOutline(); - Indicator = new DockIndicator(this); - Indicator.Show(false); - - FloatOutlineBounds = DragSource.BeginDrag(StartMousePosition); - } - - #endregion - - #region Overrides - - protected override void OnDragging() - { - TestDrop(); - } - - protected override void OnEndDrag(bool abort) - { - DockPanel.SuspendLayout(true); - - Outline.Close(); - Indicator.Close(); - - EndDrag(abort); - - // Queue a request to layout all children controls - DockPanel.PerformMdiClientLayout(); - - DockPanel.ResumeLayout(true, true); - - DragSource = null; - } - - #endregion - - #region Private Methods - - private void TestDrop() - { - Outline.FlagTestDrop = false; - - Indicator.FullPanelEdge = (Control.ModifierKeys & Keys.Shift) != 0; - - if ((Control.ModifierKeys & Keys.Control) == 0) - { - Indicator.TestDrop(); - - if (!Outline.FlagTestDrop) - { - DockPane pane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); - if (pane != null && DragSource.IsDockStateValid(pane.DockState)) - { - pane.TestDrop(DragSource, Outline); - } - } - - if (!Outline.FlagTestDrop && DragSource.IsDockStateValid(DockState.Float)) - { - FloatWindow floatWindow = DockHelper.FloatWindowAtPoint(Control.MousePosition, DockPanel); - if (floatWindow != null) - { - floatWindow.TestDrop(DragSource, Outline); - } - } - } - else - { - Indicator.DockPane = DockHelper.PaneAtPoint(Control.MousePosition, DockPanel); - } - - if (!Outline.FlagTestDrop) - { - if (DragSource.IsDockStateValid(DockState.Float)) - { - Rectangle rect = FloatOutlineBounds; - rect.Offset(Control.MousePosition.X - StartMousePosition.X, - Control.MousePosition.Y - StartMousePosition.Y); - Outline.Show(rect); - } - } - - if (!Outline.FlagTestDrop) - { - Cursor.Current = Cursors.No; - Outline.Show(); - } - else - { - Cursor.Current = DragControl.Cursor; - } - } - - private void EndDrag(bool abort) - { - if (abort) - { - return; - } - - if (!Outline.FloatWindowBounds.IsEmpty) - { - DragSource.FloatAt(Outline.FloatWindowBounds); - } - else if (Outline.DockTo is DockPane) - { - DockPane pane = Outline.DockTo as DockPane; - DragSource.DockTo(pane, Outline.Dock, Outline.ContentIndex); - } - else if (Outline.DockTo is DockPanel) - { - DockPanel panel = Outline.DockTo as DockPanel; - panel.UpdateDockWindowZOrder(Outline.Dock, Outline.FlagFullEdge); - DragSource.DockTo(panel, Outline.Dock); - } - } - - #endregion - - private class DockIndicator : DragForm - { - #region Fields - - #region consts - - private readonly int _PanelIndicatorMargin = 10; - - #endregion - - private DockPane m_dockPane = null; - - private bool m_fullPanelEdge = false; - - private IHitTest m_hitTest = null; - - private PaneIndicator m_paneDiamond = null; - - private PanelIndicator m_panelBottom = null; - - private PanelIndicator m_panelFill = null; - - private PanelIndicator m_panelLeft = null; - - private PanelIndicator m_panelRight = null; - - private PanelIndicator m_panelTop = null; - - #endregion - - #region cTor - - public DockIndicator(DockDragHandler dragHandler) - { - DragHandler = dragHandler; - Controls.AddRange(new Control[] - { - PaneDiamond, - PanelLeft, - PanelRight, - PanelTop, - PanelBottom, - PanelFill - }); - Region = new Region(Rectangle.Empty); - } - - #endregion - - #region Properties - - private PaneIndicator PaneDiamond - { - get - { - if (m_paneDiamond == null) - { - m_paneDiamond = new PaneIndicator(); - } - - return m_paneDiamond; - } - } - - private PanelIndicator PanelLeft - { - get - { - if (m_panelLeft == null) - { - m_panelLeft = new PanelIndicator(DockStyle.Left); - } - - return m_panelLeft; - } - } - - private PanelIndicator PanelRight - { - get - { - if (m_panelRight == null) - { - m_panelRight = new PanelIndicator(DockStyle.Right); - } - - return m_panelRight; - } - } - - private PanelIndicator PanelTop - { - get - { - if (m_panelTop == null) - { - m_panelTop = new PanelIndicator(DockStyle.Top); - } - - return m_panelTop; - } - } - - private PanelIndicator PanelBottom - { - get - { - if (m_panelBottom == null) - { - m_panelBottom = new PanelIndicator(DockStyle.Bottom); - } - - return m_panelBottom; - } - } - - private PanelIndicator PanelFill - { - get - { - if (m_panelFill == null) - { - m_panelFill = new PanelIndicator(DockStyle.Fill); - } - - return m_panelFill; - } - } - - public bool FullPanelEdge - { - get { return m_fullPanelEdge; } - set - { - if (m_fullPanelEdge == value) - { - return; - } - - m_fullPanelEdge = value; - RefreshChanges(); - } - } - - public DockDragHandler DragHandler { get; } - - public DockPanel DockPanel - { - get { return DragHandler.DockPanel; } - } - - public DockPane DockPane - { - get { return m_dockPane; } - internal set - { - if (m_dockPane == value) - { - return; - } - - DockPane oldDisplayingPane = DisplayingPane; - m_dockPane = value; - if (oldDisplayingPane != DisplayingPane) - { - RefreshChanges(); - } - } - } - - private IHitTest HitTestResult - { - get { return m_hitTest; } - set - { - if (m_hitTest == value) - { - return; - } - - if (m_hitTest != null) - { - m_hitTest.Status = DockStyle.None; - } - - m_hitTest = value; - } - } - - private DockPane DisplayingPane - { - get { return ShouldPaneDiamondVisible() ? DockPane : null; } - } - - #endregion - - #region Public methods - - public override void Show(bool bActivate) - { - base.Show(bActivate); - Bounds = SystemInformation.VirtualScreen; - RefreshChanges(); - } - - public void TestDrop() - { - Point pt = Control.MousePosition; - DockPane = DockHelper.PaneAtPoint(pt, DockPanel); - - if (TestDrop(PanelLeft, pt) != DockStyle.None) - { - HitTestResult = PanelLeft; - } - else if (TestDrop(PanelRight, pt) != DockStyle.None) - { - HitTestResult = PanelRight; - } - else if (TestDrop(PanelTop, pt) != DockStyle.None) - { - HitTestResult = PanelTop; - } - else if (TestDrop(PanelBottom, pt) != DockStyle.None) - { - HitTestResult = PanelBottom; - } - else if (TestDrop(PanelFill, pt) != DockStyle.None) - { - HitTestResult = PanelFill; - } - else if (TestDrop(PaneDiamond, pt) != DockStyle.None) - { - HitTestResult = PaneDiamond; - } - else - { - HitTestResult = null; - } - - if (HitTestResult != null) - { - if (HitTestResult is PaneIndicator) - { - DragHandler.Outline.Show(DockPane, HitTestResult.Status); - } - else - { - DragHandler.Outline.Show(DockPanel, HitTestResult.Status, FullPanelEdge); - } - } - } - - #endregion - - #region Private Methods - - private void RefreshChanges() - { - Region region = new Region(Rectangle.Empty); - Rectangle rectDockArea = FullPanelEdge ? DockPanel.DockArea : DockPanel.DocumentWindowBounds; - - rectDockArea = RectangleToClient(DockPanel.RectangleToScreen(rectDockArea)); - if (ShouldPanelIndicatorVisible(DockState.DockLeft)) - { - PanelLeft.Location = new Point(rectDockArea.X + _PanelIndicatorMargin, - rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); - PanelLeft.Visible = true; - region.Union(PanelLeft.Bounds); - } - else - { - PanelLeft.Visible = false; - } - - if (ShouldPanelIndicatorVisible(DockState.DockRight)) - { - PanelRight.Location = - new Point(rectDockArea.X + rectDockArea.Width - PanelRight.Width - _PanelIndicatorMargin, - rectDockArea.Y + (rectDockArea.Height - PanelRight.Height) / 2); - PanelRight.Visible = true; - region.Union(PanelRight.Bounds); - } - else - { - PanelRight.Visible = false; - } - - if (ShouldPanelIndicatorVisible(DockState.DockTop)) - { - PanelTop.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelTop.Width) / 2, - rectDockArea.Y + _PanelIndicatorMargin); - PanelTop.Visible = true; - region.Union(PanelTop.Bounds); - } - else - { - PanelTop.Visible = false; - } - - if (ShouldPanelIndicatorVisible(DockState.DockBottom)) - { - PanelBottom.Location = new Point(rectDockArea.X + (rectDockArea.Width - PanelBottom.Width) / 2, - rectDockArea.Y + rectDockArea.Height - PanelBottom.Height - _PanelIndicatorMargin); - PanelBottom.Visible = true; - region.Union(PanelBottom.Bounds); - } - else - { - PanelBottom.Visible = false; - } - - if (ShouldPanelIndicatorVisible(DockState.Document)) - { - Rectangle rectDocumentWindow = - RectangleToClient(DockPanel.RectangleToScreen(DockPanel.DocumentWindowBounds)); - PanelFill.Location = - new Point(rectDocumentWindow.X + (rectDocumentWindow.Width - PanelFill.Width) / 2, - rectDocumentWindow.Y + (rectDocumentWindow.Height - PanelFill.Height) / 2); - PanelFill.Visible = true; - region.Union(PanelFill.Bounds); - } - else - { - PanelFill.Visible = false; - } - - if (ShouldPaneDiamondVisible()) - { - Rectangle rect = RectangleToClient(DockPane.RectangleToScreen(DockPane.ClientRectangle)); - PaneDiamond.Location = new Point(rect.Left + (rect.Width - PaneDiamond.Width) / 2, - rect.Top + (rect.Height - PaneDiamond.Height) / 2); - PaneDiamond.Visible = true; - using (GraphicsPath graphicsPath = PaneIndicator.DisplayingGraphicsPath.Clone() as GraphicsPath) - { - Point[] pts = new Point[] - { - new Point(PaneDiamond.Left, PaneDiamond.Top), - new Point(PaneDiamond.Right, PaneDiamond.Top), - new Point(PaneDiamond.Left, PaneDiamond.Bottom) - }; - using (Matrix matrix = new Matrix(PaneDiamond.ClientRectangle, pts)) - { - graphicsPath.Transform(matrix); - } - region.Union(graphicsPath); - } - } - else - { - PaneDiamond.Visible = false; - } - - Region = region; - } - - private bool ShouldPanelIndicatorVisible(DockState dockState) - { - if (!Visible) - { - return false; - } - - if (DockPanel.DockWindows[dockState].Visible) - { - return false; - } - - return DragHandler.DragSource.IsDockStateValid(dockState); - } - - private bool ShouldPaneDiamondVisible() - { - if (DockPane == null) - { - return false; - } - - if (!DockPanel.AllowEndUserNestedDocking) - { - return false; - } - - return DragHandler.DragSource.CanDockTo(DockPane); - } - - private static DockStyle TestDrop(IHitTest hitTest, Point pt) - { - return hitTest.Status = hitTest.HitTest(pt); - } - - #endregion - - #region IHitTest - - private interface IHitTest - { - #region Properties - - DockStyle Status { get; set; } - - #endregion - - #region Public methods - - DockStyle HitTest(Point pt); - - #endregion - } - - #endregion - - #region PanelIndicator - - private class PanelIndicator : PictureBox, IHitTest - { - #region Fields - - private static readonly Image _imagePanelLeft = Resources.DockIndicator_PanelLeft; - private static readonly Image _imagePanelRight = Resources.DockIndicator_PanelRight; - private static readonly Image _imagePanelTop = Resources.DockIndicator_PanelTop; - private static readonly Image _imagePanelBottom = Resources.DockIndicator_PanelBottom; - private static readonly Image _imagePanelFill = Resources.DockIndicator_PanelFill; - private static readonly Image _imagePanelLeftActive = Resources.DockIndicator_PanelLeft_Active; - private static readonly Image _imagePanelRightActive = Resources.DockIndicator_PanelRight_Active; - private static readonly Image _imagePanelTopActive = Resources.DockIndicator_PanelTop_Active; - private static readonly Image _imagePanelBottomActive = Resources.DockIndicator_PanelBottom_Active; - private static readonly Image _imagePanelFillActive = Resources.DockIndicator_PanelFill_Active; - - private bool m_isActivated = false; - - private DockStyle m_status; - - #endregion - - #region cTor - - public PanelIndicator(DockStyle dockStyle) - { - DockStyle = dockStyle; - SizeMode = PictureBoxSizeMode.AutoSize; - Image = ImageInactive; - } - - #endregion - - #region Properties - - private DockStyle DockStyle { get; } - - public DockStyle Status - { - get { return m_status; } - set - { - if (value != DockStyle && value != DockStyle.None) - { - throw new InvalidEnumArgumentException(); - } - - if (m_status == value) - { - return; - } - - m_status = value; - IsActivated = m_status != DockStyle.None; - } - } - - private Image ImageInactive - { - get - { - if (DockStyle == DockStyle.Left) - { - return _imagePanelLeft; - } - else if (DockStyle == DockStyle.Right) - { - return _imagePanelRight; - } - else if (DockStyle == DockStyle.Top) - { - return _imagePanelTop; - } - else if (DockStyle == DockStyle.Bottom) - { - return _imagePanelBottom; - } - else if (DockStyle == DockStyle.Fill) - { - return _imagePanelFill; - } - else - { - return null; - } - } - } - - private Image ImageActive - { - get - { - if (DockStyle == DockStyle.Left) - { - return _imagePanelLeftActive; - } - else if (DockStyle == DockStyle.Right) - { - return _imagePanelRightActive; - } - else if (DockStyle == DockStyle.Top) - { - return _imagePanelTopActive; - } - else if (DockStyle == DockStyle.Bottom) - { - return _imagePanelBottomActive; - } - else if (DockStyle == DockStyle.Fill) - { - return _imagePanelFillActive; - } - else - { - return null; - } - } - } - - private bool IsActivated - { - get { return m_isActivated; } - set - { - m_isActivated = value; - Image = IsActivated ? ImageActive : ImageInactive; - } - } - - #endregion - - #region Public methods - - public DockStyle HitTest(Point pt) - { - return this.Visible && ClientRectangle.Contains(PointToClient(pt)) ? DockStyle : DockStyle.None; - } - - #endregion - } - - #endregion PanelIndicator - - #region PaneIndicator - - private class PaneIndicator : PictureBox, IHitTest - { - #region Fields - - private static readonly Bitmap _bitmapPaneDiamond = Resources.DockIndicator_PaneDiamond; - private static readonly Bitmap _bitmapPaneDiamondLeft = Resources.DockIndicator_PaneDiamond_Left; - private static readonly Bitmap _bitmapPaneDiamondRight = Resources.DockIndicator_PaneDiamond_Right; - private static readonly Bitmap _bitmapPaneDiamondTop = Resources.DockIndicator_PaneDiamond_Top; - - private static readonly Bitmap _bitmapPaneDiamondBottom = Resources.DockIndicator_PaneDiamond_Bottom - ; - - private static readonly Bitmap _bitmapPaneDiamondFill = Resources.DockIndicator_PaneDiamond_Fill; - - private static readonly Bitmap _bitmapPaneDiamondHotSpot = - Resources.DockIndicator_PaneDiamond_HotSpot; - - private static readonly Bitmap _bitmapPaneDiamondHotSpotIndex = - Resources.DockIndicator_PaneDiamond_HotSpotIndex; - - private static readonly HotSpotIndex[] _hotSpots = new HotSpotIndex[] - { - new HotSpotIndex(1, 0, DockStyle.Top), - new HotSpotIndex(0, 1, DockStyle.Left), - new HotSpotIndex(1, 1, DockStyle.Fill), - new HotSpotIndex(2, 1, DockStyle.Right), - new HotSpotIndex(1, 2, DockStyle.Bottom) - }; - - private DockStyle m_status = DockStyle.None; - - #endregion - - #region cTor - - public PaneIndicator() - { - SizeMode = PictureBoxSizeMode.AutoSize; - Image = _bitmapPaneDiamond; - Region = new Region(DisplayingGraphicsPath); - } - - #endregion - - #region Properties - - public static GraphicsPath DisplayingGraphicsPath { get; } = - DrawHelper.CalculateGraphicsPathFromBitmap(_bitmapPaneDiamond); - - public DockStyle Status - { - get { return m_status; } - set - { - m_status = value; - if (m_status == DockStyle.None) - { - Image = _bitmapPaneDiamond; - } - else if (m_status == DockStyle.Left) - { - Image = _bitmapPaneDiamondLeft; - } - else if (m_status == DockStyle.Right) - { - Image = _bitmapPaneDiamondRight; - } - else if (m_status == DockStyle.Top) - { - Image = _bitmapPaneDiamondTop; - } - else if (m_status == DockStyle.Bottom) - { - Image = _bitmapPaneDiamondBottom; - } - else if (m_status == DockStyle.Fill) - { - Image = _bitmapPaneDiamondFill; - } - } - } - - #endregion - - #region Public methods - - public DockStyle HitTest(Point pt) - { - if (!Visible) - { - return DockStyle.None; - } - - pt = PointToClient(pt); - if (!ClientRectangle.Contains(pt)) - { - return DockStyle.None; - } - - for (int i = _hotSpots.GetLowerBound(0); i <= _hotSpots.GetUpperBound(0); i++) - { - if (_bitmapPaneDiamondHotSpot.GetPixel(pt.X, pt.Y) == - _bitmapPaneDiamondHotSpotIndex.GetPixel(_hotSpots[i].X, _hotSpots[i].Y)) - { - return _hotSpots[i].DockStyle; - } - } - - return DockStyle.None; - } - - #endregion - - private struct HotSpotIndex - { - public HotSpotIndex(int x, int y, DockStyle dockStyle) - { - X = x; - Y = y; - DockStyle = dockStyle; - } - - public int X { get; } - - public int Y { get; } - - public DockStyle DockStyle { get; } - } - } - - #endregion PaneIndicator - } - - private class DockOutline : DockOutlineBase - { - #region Fields - - #endregion - - #region cTor - - public DockOutline() - { - DragForm = new DragForm(); - SetDragForm(Rectangle.Empty); - DragForm.BackColor = SystemColors.ActiveCaption; - DragForm.Opacity = 0.5; - DragForm.Show(false); - } - - #endregion - - #region Properties - - private DragForm DragForm { get; } - - #endregion - - #region Overrides - - protected override void OnShow() - { - CalculateRegion(); - } - - protected override void OnClose() - { - DragForm.Close(); - } - - #endregion - - #region Private Methods - - private void CalculateRegion() - { - if (SameAsOldValue) - { - return; - } - - if (!FloatWindowBounds.IsEmpty) - { - SetOutline(FloatWindowBounds); - } - else if (DockTo is DockPanel) - { - SetOutline(DockTo as DockPanel, Dock, ContentIndex != 0); - } - else if (DockTo is DockPane) - { - SetOutline(DockTo as DockPane, Dock, ContentIndex); - } - else - { - SetOutline(); - } - } - - private void SetOutline() - { - SetDragForm(Rectangle.Empty); - } - - private void SetOutline(Rectangle floatWindowBounds) - { - SetDragForm(floatWindowBounds); - } - - private void SetOutline(DockPanel dockPanel, DockStyle dock, bool fullPanelEdge) - { - Rectangle rect = fullPanelEdge ? dockPanel.DockArea : dockPanel.DocumentWindowBounds; - rect.Location = dockPanel.PointToScreen(rect.Location); - if (dock == DockStyle.Top) - { - int height = dockPanel.GetDockWindowSize(DockState.DockTop); - rect = new Rectangle(rect.X, rect.Y, rect.Width, height); - } - else if (dock == DockStyle.Bottom) - { - int height = dockPanel.GetDockWindowSize(DockState.DockBottom); - rect = new Rectangle(rect.X, rect.Bottom - height, rect.Width, height); - } - else if (dock == DockStyle.Left) - { - int width = dockPanel.GetDockWindowSize(DockState.DockLeft); - rect = new Rectangle(rect.X, rect.Y, width, rect.Height); - } - else if (dock == DockStyle.Right) - { - int width = dockPanel.GetDockWindowSize(DockState.DockRight); - rect = new Rectangle(rect.Right - width, rect.Y, width, rect.Height); - } - else if (dock == DockStyle.Fill) - { - rect = dockPanel.DocumentWindowBounds; - rect.Location = dockPanel.PointToScreen(rect.Location); - } - - SetDragForm(rect); - } - - private void SetOutline(DockPane pane, DockStyle dock, int contentIndex) - { - if (dock != DockStyle.Fill) - { - Rectangle rect = pane.DisplayingRectangle; - if (dock == DockStyle.Right) - { - rect.X += rect.Width / 2; - } - if (dock == DockStyle.Bottom) - { - rect.Y += rect.Height / 2; - } - if (dock == DockStyle.Left || dock == DockStyle.Right) - { - rect.Width -= rect.Width / 2; - } - if (dock == DockStyle.Top || dock == DockStyle.Bottom) - { - rect.Height -= rect.Height / 2; - } - rect.Location = pane.PointToScreen(rect.Location); - - SetDragForm(rect); - } - else if (contentIndex == -1) - { - Rectangle rect = pane.DisplayingRectangle; - rect.Location = pane.PointToScreen(rect.Location); - SetDragForm(rect); - } - else - { - using (GraphicsPath path = pane.TabStripControl.GetOutline(contentIndex)) - { - RectangleF rectF = path.GetBounds(); - Rectangle rect = new Rectangle((int) rectF.X, (int) rectF.Y, (int) rectF.Width, - (int) rectF.Height); - using (Matrix matrix = new Matrix(rect, - new Point[] {new Point(0, 0), new Point(rect.Width, 0), new Point(0, rect.Height)})) - { - path.Transform(matrix); - } - Region region = new Region(path); - SetDragForm(rect, region); - } - } - } - - private void SetDragForm(Rectangle rect) - { - DragForm.Bounds = rect; - if (rect == Rectangle.Empty) - { - DragForm.Region = new Region(Rectangle.Empty); - } - else if (DragForm.Region != null) - { - DragForm.Region = null; - } - } - - private void SetDragForm(Rectangle rect, Region region) - { - DragForm.Bounds = rect; - DragForm.Region = region; - } - - #endregion - } - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.DragHandler.cs b/src/WinFormsUI/Docking/DockPanel.DragHandler.cs deleted file mode 100644 index eb29365b..00000000 --- a/src/WinFormsUI/Docking/DockPanel.DragHandler.cs +++ /dev/null @@ -1,169 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.ComponentModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - partial class DockPanel - { - /// - /// DragHandlerBase is the base class for drag handlers. The derived class should: - /// 1. Define its public method BeginDrag. From within this public BeginDrag method, - /// DragHandlerBase.BeginDrag should be called to initialize the mouse capture - /// and message filtering. - /// 2. Override the OnDragging and OnEndDrag methods. - /// - private abstract class DragHandlerBase : NativeWindow, IMessageFilter - { - #region Fields - - #endregion - - #region cTor - - protected DragHandlerBase() - { - } - - #endregion - - #region Properties - - protected abstract Control DragControl { get; } - - protected Point StartMousePosition { get; private set; } = Point.Empty; - - #endregion - - #region Overrides - - protected sealed override void WndProc(ref Message m) - { - if (m.Msg == (int) Win32.Msgs.WM_CANCELMODE || m.Msg == (int) Win32.Msgs.WM_CAPTURECHANGED) - { - EndDrag(true); - } - - base.WndProc(ref m); - } - - #endregion - - #region Private Methods - - private void EndDrag(bool abort) - { - ReleaseHandle(); - Application.RemoveMessageFilter(this); - DragControl.FindForm().Capture = false; - - OnEndDrag(abort); - } - - bool IMessageFilter.PreFilterMessage(ref Message m) - { - if (m.Msg == (int) Win32.Msgs.WM_MOUSEMOVE) - { - OnDragging(); - } - else if (m.Msg == (int) Win32.Msgs.WM_LBUTTONUP) - { - EndDrag(false); - } - else if (m.Msg == (int) Win32.Msgs.WM_CAPTURECHANGED) - { - EndDrag(true); - } - else if (m.Msg == (int) Win32.Msgs.WM_KEYDOWN && (int) m.WParam == (int) Keys.Escape) - { - EndDrag(true); - } - - return OnPreFilterMessage(ref m); - } - - #endregion - - protected bool BeginDrag() - { - // Avoid re-entrance; - lock (this) - { - if (DragControl == null) - { - return false; - } - - StartMousePosition = Control.MousePosition; - - if (!NativeMethods.DragDetect(DragControl.Handle, StartMousePosition)) - { - return false; - } - - DragControl.FindForm().Capture = true; - AssignHandle(DragControl.FindForm().Handle); - Application.AddMessageFilter(this); - return true; - } - } - - protected abstract void OnDragging(); - - protected abstract void OnEndDrag(bool abort); - - protected virtual bool OnPreFilterMessage(ref Message m) - { - return false; - } - } - - private abstract class DragHandler : DragHandlerBase - { - #region Fields - - #endregion - - #region cTor - - protected DragHandler(DockPanel dockPanel) - { - DockPanel = dockPanel; - } - - #endregion - - #region Properties - - public DockPanel DockPanel { get; } - - protected IDragSource DragSource { get; set; } - - protected sealed override Control DragControl - { - get { return DragSource == null ? null : DragSource.DragControl; } - } - - #endregion - - #region Overrides - - protected sealed override bool OnPreFilterMessage(ref Message m) - { - if ((m.Msg == (int) Win32.Msgs.WM_KEYDOWN || m.Msg == (int) Win32.Msgs.WM_KEYUP) && - ((int) m.WParam == (int) Keys.ControlKey || (int) m.WParam == (int) Keys.ShiftKey)) - { - OnDragging(); - } - - return base.OnPreFilterMessage(ref m); - } - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.FocusManager.cs b/src/WinFormsUI/Docking/DockPanel.FocusManager.cs deleted file mode 100644 index 1c425557..00000000 --- a/src/WinFormsUI/Docking/DockPanel.FocusManager.cs +++ /dev/null @@ -1,731 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.ComponentModel; -using System.Runtime.InteropServices; -using System.Windows.Forms; -using System.Diagnostics.CodeAnalysis; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal interface IContentFocusManager - { - #region Public methods - - void Activate(IDockContent content); - void GiveUpFocus(IDockContent content); - void AddToList(IDockContent content); - void RemoveFromList(IDockContent content); - - #endregion - } - - partial class DockPanel - { - #region Fields - - private static readonly object ActiveDocumentChangedEvent = new object(); - - private static readonly object ActiveContentChangedEvent = new object(); - - private static readonly object ActivePaneChangedEvent = new object(); - - #endregion - - #region Events - - [LocalizedCategory("Category_PropertyChanged")] - [LocalizedDescription("DockPanel_ActiveDocumentChanged_Description")] - public event EventHandler ActiveDocumentChanged - { - add { Events.AddHandler(ActiveDocumentChangedEvent, value); } - remove { Events.RemoveHandler(ActiveDocumentChangedEvent, value); } - } - - [LocalizedCategory("Category_PropertyChanged")] - [LocalizedDescription("DockPanel_ActiveContentChanged_Description")] - public event EventHandler ActiveContentChanged - { - add { Events.AddHandler(ActiveContentChangedEvent, value); } - remove { Events.RemoveHandler(ActiveContentChangedEvent, value); } - } - - [LocalizedCategory("Category_PropertyChanged")] - [LocalizedDescription("DockPanel_ActivePaneChanged_Description")] - public event EventHandler ActivePaneChanged - { - add { Events.AddHandler(ActivePaneChangedEvent, value); } - remove { Events.RemoveHandler(ActivePaneChangedEvent, value); } - } - - #endregion - - #region Properties - - private IFocusManager FocusManager - { - get { return m_focusManager; } - } - - internal IContentFocusManager ContentFocusManager - { - get { return m_focusManager; } - } - - [Browsable(false)] - public IDockContent ActiveContent - { - get { return FocusManager.ActiveContent; } - } - - [Browsable(false)] - public DockPane ActivePane - { - get { return FocusManager.ActivePane; } - } - - [Browsable(false)] - public IDockContent ActiveDocument - { - get { return FocusManager.ActiveDocument; } - } - - [Browsable(false)] - public DockPane ActiveDocumentPane - { - get { return FocusManager.ActiveDocumentPane; } - } - - #endregion - - #region Internals - - internal void SaveFocus() - { - DummyControl.Focus(); - } - - #endregion - - protected virtual void OnActiveDocumentChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[ActiveDocumentChangedEvent]; - if (handler != null) - { - handler(this, e); - } - } - - protected void OnActiveContentChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[ActiveContentChangedEvent]; - if (handler != null) - { - handler(this, e); - } - } - - protected virtual void OnActivePaneChanged(EventArgs e) - { - EventHandler handler = (EventHandler) Events[ActivePaneChangedEvent]; - if (handler != null) - { - handler(this, e); - } - } - - private interface IFocusManager - { - #region Properties - - bool IsFocusTrackingSuspended { get; } - IDockContent ActiveContent { get; } - DockPane ActivePane { get; } - IDockContent ActiveDocument { get; } - DockPane ActiveDocumentPane { get; } - - #endregion - - #region Public methods - - void SuspendFocusTracking(); - void ResumeFocusTracking(); - - #endregion - } - - private class FocusManagerImpl : Component, IContentFocusManager, IFocusManager - { - #region Fields - - private int m_countSuspendFocusTracking = 0; - - private bool m_disposed = false; - - private readonly LocalWindowsHook.HookEventHandler m_hookEventHandler; - - private readonly LocalWindowsHook m_localWindowsHook; - - #endregion - - #region cTor - - public FocusManagerImpl(DockPanel dockPanel) - { - DockPanel = dockPanel; - m_localWindowsHook = new LocalWindowsHook(Win32.HookType.WH_CALLWNDPROCRET); - m_hookEventHandler = new LocalWindowsHook.HookEventHandler(HookEventHandler); - m_localWindowsHook.HookInvoked += m_hookEventHandler; - m_localWindowsHook.Install(); - } - - #endregion - - #region Properties - - public DockPanel DockPanel { get; } - - private IDockContent ContentActivating { get; set; } = null; - - private List ListContent { get; } = new List(); - - private IDockContent LastActiveContent { get; set; } = null; - - public bool IsFocusTrackingSuspended - { - get { return m_countSuspendFocusTracking != 0; } - } - - private bool InRefreshActiveWindow { get; set; } = false; - - public DockPane ActivePane { get; private set; } = null; - - public IDockContent ActiveContent { get; private set; } = null; - - public DockPane ActiveDocumentPane { get; private set; } = null; - - public IDockContent ActiveDocument { get; private set; } = null; - - #endregion - - #region Public methods - - public void Activate(IDockContent content) - { - if (IsFocusTrackingSuspended) - { - ContentActivating = content; - return; - } - - if (content == null) - { - return; - } - DockContentHandler handler = content.DockHandler; - if (handler.Form.IsDisposed) - { - return; // Should not reach here, but better than throwing an exception - } - if (ContentContains(content, handler.ActiveWindowHandle)) - { - NativeMethods.SetFocus(handler.ActiveWindowHandle); - } - if (!handler.Form.ContainsFocus) - { - if (!handler.Form.SelectNextControl(handler.Form.ActiveControl, true, true, true, true)) - // Since DockContent Form is not selectalbe, use Win32 SetFocus instead - { - NativeMethods.SetFocus(handler.Form.Handle); - } - } - } - - public void AddToList(IDockContent content) - { - if (ListContent.Contains(content) || IsInActiveList(content)) - { - return; - } - - ListContent.Add(content); - } - - public void RemoveFromList(IDockContent content) - { - if (IsInActiveList(content)) - { - RemoveFromActiveList(content); - } - if (ListContent.Contains(content)) - { - ListContent.Remove(content); - } - } - - public void GiveUpFocus(IDockContent content) - { - DockContentHandler handler = content.DockHandler; - if (!handler.Form.ContainsFocus) - { - return; - } - - if (IsFocusTrackingSuspended) - { - DockPanel.DummyControl.Focus(); - } - - if (LastActiveContent == content) - { - IDockContent prev = handler.PreviousActive; - if (prev != null) - { - Activate(prev); - } - else if (ListContent.Count > 0) - { - Activate(ListContent[ListContent.Count - 1]); - } - } - else if (LastActiveContent != null) - { - Activate(LastActiveContent); - } - else if (ListContent.Count > 0) - { - Activate(ListContent[ListContent.Count - 1]); - } - } - - public void SuspendFocusTracking() - { - m_countSuspendFocusTracking++; - m_localWindowsHook.HookInvoked -= m_hookEventHandler; - } - - public void ResumeFocusTracking() - { - if (m_countSuspendFocusTracking > 0) - { - m_countSuspendFocusTracking--; - } - - if (m_countSuspendFocusTracking == 0) - { - if (ContentActivating != null) - { - Activate(ContentActivating); - ContentActivating = null; - } - m_localWindowsHook.HookInvoked += m_hookEventHandler; - if (!InRefreshActiveWindow) - { - RefreshActiveWindow(); - } - } - } - - #endregion - - #region Internals - - internal void SetActiveContent() - { - IDockContent value = ActivePane == null ? null : ActivePane.ActiveContent; - - if (ActiveContent == value) - { - return; - } - - if (ActiveContent != null) - { - ActiveContent.DockHandler.IsActivated = false; - } - - ActiveContent = value; - - if (ActiveContent != null) - { - ActiveContent.DockHandler.IsActivated = true; - if (!DockHelper.IsDockStateAutoHide(ActiveContent.DockHandler.DockState)) - { - AddLastToActiveList(ActiveContent); - } - } - } - - #endregion - - #region Overrides - - protected override void Dispose(bool disposing) - { - lock (this) - { - if (!m_disposed && disposing) - { - m_localWindowsHook.Dispose(); - m_disposed = true; - } - - base.Dispose(disposing); - } - } - - #endregion - - #region Private Methods - - private bool IsInActiveList(IDockContent content) - { - return !(content.DockHandler.NextActive == null && LastActiveContent != content); - } - - private void AddLastToActiveList(IDockContent content) - { - IDockContent last = LastActiveContent; - if (last == content) - { - return; - } - - DockContentHandler handler = content.DockHandler; - - if (IsInActiveList(content)) - { - RemoveFromActiveList(content); - } - - handler.PreviousActive = last; - handler.NextActive = null; - LastActiveContent = content; - if (last != null) - { - last.DockHandler.NextActive = LastActiveContent; - } - } - - private void RemoveFromActiveList(IDockContent content) - { - if (LastActiveContent == content) - { - LastActiveContent = content.DockHandler.PreviousActive; - } - - IDockContent prev = content.DockHandler.PreviousActive; - IDockContent next = content.DockHandler.NextActive; - if (prev != null) - { - prev.DockHandler.NextActive = next; - } - if (next != null) - { - next.DockHandler.PreviousActive = prev; - } - - content.DockHandler.PreviousActive = null; - content.DockHandler.NextActive = null; - } - - private static bool ContentContains(IDockContent content, IntPtr hWnd) - { - Control control = Control.FromChildHandle(hWnd); - for (Control parent = control; parent != null; parent = parent.Parent) - { - if (parent == content.DockHandler.Form) - { - return true; - } - } - - return false; - } - - private DockPane GetPaneFromHandle(IntPtr hWnd) - { - Control control = Control.FromChildHandle(hWnd); - - IDockContent content = null; - DockPane pane = null; - for (; control != null; control = control.Parent) - { - content = control as IDockContent; - if (content != null) - { - content.DockHandler.ActiveWindowHandle = hWnd; - } - - if (content != null && content.DockHandler.DockPanel == DockPanel) - { - return content.DockHandler.Pane; - } - - pane = control as DockPane; - if (pane != null && pane.DockPanel == DockPanel) - { - break; - } - } - - return pane; - } - - private void RefreshActiveWindow() - { - SuspendFocusTracking(); - InRefreshActiveWindow = true; - - DockPane oldActivePane = ActivePane; - IDockContent oldActiveContent = ActiveContent; - IDockContent oldActiveDocument = ActiveDocument; - - SetActivePane(); - SetActiveContent(); - SetActiveDocumentPane(); - SetActiveDocument(); - DockPanel.AutoHideWindow.RefreshActivePane(); - - ResumeFocusTracking(); - InRefreshActiveWindow = false; - - if (oldActiveContent != ActiveContent) - { - DockPanel.OnActiveContentChanged(EventArgs.Empty); - } - if (oldActiveDocument != ActiveDocument) - { - DockPanel.OnActiveDocumentChanged(EventArgs.Empty); - } - if (oldActivePane != ActivePane) - { - DockPanel.OnActivePaneChanged(EventArgs.Empty); - } - } - - private void SetActivePane() - { - DockPane value = GetPaneFromHandle(NativeMethods.GetFocus()); - if (ActivePane == value) - { - return; - } - - if (ActivePane != null) - { - ActivePane.SetIsActivated(false); - } - - ActivePane = value; - - if (ActivePane != null) - { - ActivePane.SetIsActivated(true); - } - } - - private void SetActiveDocumentPane() - { - DockPane value = null; - - if (ActivePane != null && ActivePane.DockState == DockState.Document) - { - value = ActivePane; - } - - if (value == null && DockPanel.DockWindows != null) - { - if (ActiveDocumentPane == null) - { - value = DockPanel.DockWindows[DockState.Document].DefaultPane; - } - else if (ActiveDocumentPane.DockPanel != DockPanel || - ActiveDocumentPane.DockState != DockState.Document) - { - value = DockPanel.DockWindows[DockState.Document].DefaultPane; - } - else - { - value = ActiveDocumentPane; - } - } - - if (ActiveDocumentPane == value) - { - return; - } - - if (ActiveDocumentPane != null) - { - ActiveDocumentPane.SetIsActiveDocumentPane(false); - } - - ActiveDocumentPane = value; - - if (ActiveDocumentPane != null) - { - ActiveDocumentPane.SetIsActiveDocumentPane(true); - } - } - - private void SetActiveDocument() - { - IDockContent value = ActiveDocumentPane == null ? null : ActiveDocumentPane.ActiveContent; - - if (ActiveDocument == value) - { - return; - } - - ActiveDocument = value; - } - - #endregion - - #region Events handler - - // Windows hook event handler - private void HookEventHandler(object sender, HookEventArgs e) - { - Win32.Msgs msg = (Win32.Msgs) Marshal.ReadInt32(e.lParam, IntPtr.Size * 3); - - if (msg == Win32.Msgs.WM_KILLFOCUS) - { - IntPtr wParam = Marshal.ReadIntPtr(e.lParam, IntPtr.Size * 2); - DockPane pane = GetPaneFromHandle(wParam); - if (pane == null) - { - RefreshActiveWindow(); - } - } - else if (msg == Win32.Msgs.WM_SETFOCUS) - { - RefreshActiveWindow(); - } - } - - #endregion - - private class HookEventArgs : EventArgs - { - #region Fields - - [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] public int HookCode; - - public IntPtr lParam; - - [SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")] public IntPtr wParam; - - #endregion - } - - private class LocalWindowsHook : IDisposable - { - #region Fields - - private readonly NativeMethods.HookProc m_filterFunc = null; - - // Internal properties - private IntPtr m_hHook = IntPtr.Zero; - - private readonly Win32.HookType m_hookType; - - #endregion - - #region cTor - - public LocalWindowsHook(Win32.HookType hook) - { - m_hookType = hook; - m_filterFunc = new NativeMethods.HookProc(this.CoreHookProc); - } - - #endregion - - #region Delegates - - // Event delegate - public delegate void HookEventHandler(object sender, HookEventArgs e); - - #endregion - - #region Events - - // Event: HookInvoked - public event HookEventHandler HookInvoked; - - #endregion - - #region Public methods - - // Default filter function - public IntPtr CoreHookProc(int code, IntPtr wParam, IntPtr lParam) - { - if (code < 0) - { - return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam); - } - - // Let clients determine what to do - HookEventArgs e = new HookEventArgs(); - e.HookCode = code; - e.wParam = wParam; - e.lParam = lParam; - OnHookInvoked(e); - - // Yield to the next hook in the chain - return NativeMethods.CallNextHookEx(m_hHook, code, wParam, lParam); - } - - // Install the hook - public void Install() - { - if (m_hHook != IntPtr.Zero) - { - Uninstall(); - } - - int threadId = NativeMethods.GetCurrentThreadId(); - m_hHook = NativeMethods.SetWindowsHookEx(m_hookType, m_filterFunc, IntPtr.Zero, threadId); - } - - // Uninstall the hook - public void Uninstall() - { - if (m_hHook != IntPtr.Zero) - { - NativeMethods.UnhookWindowsHookEx(m_hHook); - m_hHook = IntPtr.Zero; - } - } - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - #endregion - - protected void OnHookInvoked(HookEventArgs e) - { - if (HookInvoked != null) - { - HookInvoked(this, e); - } - } - - ~LocalWindowsHook() - { - Dispose(false); - } - - protected virtual void Dispose(bool disposing) - { - Uninstall(); - } - } - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.MdiClientController.cs b/src/WinFormsUI/Docking/DockPanel.MdiClientController.cs deleted file mode 100644 index 996896c8..00000000 --- a/src/WinFormsUI/Docking/DockPanel.MdiClientController.cs +++ /dev/null @@ -1,534 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using System.ComponentModel; -using System.ComponentModel.Design; -using System.Runtime.InteropServices; - -namespace WeifenLuo.WinFormsUI.Docking -{ - partial class DockPanel - { - #region Fields - - private MdiClientController m_mdiClientController = null; - - #endregion - - #region Properties - - private bool MdiClientExists - { - get { return GetMdiClientController().MdiClient != null; } - } - - #endregion - - #region Internals - - internal Rectangle RectangleToMdiClient(Rectangle rect) - { - if (MdiClientExists) - { - return GetMdiClientController().MdiClient.RectangleToClient(rect); - } - else - { - return Rectangle.Empty; - } - } - - #endregion - - #region Private Methods - - private MdiClientController GetMdiClientController() - { - if (m_mdiClientController == null) - { - m_mdiClientController = new MdiClientController(); - m_mdiClientController.HandleAssigned += new EventHandler(MdiClientHandleAssigned); - m_mdiClientController.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate); - m_mdiClientController.Layout += new LayoutEventHandler(MdiClient_Layout); - } - - return m_mdiClientController; - } - - private void SetMdiClientBounds(Rectangle bounds) - { - GetMdiClientController().MdiClient.Bounds = bounds; - } - - private void SuspendMdiClientLayout() - { - if (GetMdiClientController().MdiClient != null) - { - GetMdiClientController().MdiClient.SuspendLayout(); - } - } - - private void ResumeMdiClientLayout(bool perform) - { - if (GetMdiClientController().MdiClient != null) - { - GetMdiClientController().MdiClient.ResumeLayout(perform); - } - } - - private void PerformMdiClientLayout() - { - if (GetMdiClientController().MdiClient != null) - { - GetMdiClientController().MdiClient.PerformLayout(); - } - } - - // Called when: - // 1. DockPanel.DocumentStyle changed - // 2. DockPanel.Visible changed - // 3. MdiClientController.Handle assigned - private void SetMdiClient() - { - MdiClientController controller = GetMdiClientController(); - - if (this.DocumentStyle == DocumentStyle.DockingMdi) - { - controller.AutoScroll = false; - controller.BorderStyle = BorderStyle.None; - if (MdiClientExists) - { - controller.MdiClient.Dock = DockStyle.Fill; - } - } - else if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow) - { - controller.AutoScroll = true; - controller.BorderStyle = BorderStyle.Fixed3D; - if (MdiClientExists) - { - controller.MdiClient.Dock = DockStyle.Fill; - } - } - else if (this.DocumentStyle == DocumentStyle.SystemMdi) - { - controller.AutoScroll = true; - controller.BorderStyle = BorderStyle.Fixed3D; - if (controller.MdiClient != null) - { - controller.MdiClient.Dock = DockStyle.None; - controller.MdiClient.Bounds = SystemMdiClientBounds; - } - } - } - - #endregion - - #region Events handler - - private void ParentFormMdiChildActivate(object sender, EventArgs e) - { - if (GetMdiClientController().ParentForm == null) - { - return; - } - - IDockContent content = GetMdiClientController().ParentForm.ActiveMdiChild as IDockContent; - if (content == null) - { - return; - } - - if (content.DockHandler.DockPanel == this && content.DockHandler.Pane != null) - { - content.DockHandler.Pane.ActiveContent = content; - } - } - - #endregion - - // This class comes from Jacob Slusser's MdiClientController class: - // http://www.codeproject.com/cs/miscctrl/mdiclientcontroller.asp - private class MdiClientController : NativeWindow, IComponent, IDisposable - { - #region Fields - - private bool m_autoScroll = true; - private BorderStyle m_borderStyle = BorderStyle.Fixed3D; - private Form m_parentForm = null; - private ISite m_site = null; - - #endregion - - #region cTor - - public MdiClientController() - { - } - - #endregion - - #region Events - - public event EventHandler Disposed; - - public event EventHandler HandleAssigned; - - public event EventHandler MdiChildActivate; - - public event LayoutEventHandler Layout; - - public event PaintEventHandler Paint; - - #endregion - - #region Properties - - public bool AutoScroll - { - get { return m_autoScroll; } - set - { - // By default the MdiClient control scrolls. It can appear though that - // there are no scrollbars by turning them off when the non-client - // area is calculated. I decided to expose this method following - // the .NET vernacular of an AutoScroll property. - m_autoScroll = value; - if (MdiClient != null) - { - UpdateStyles(); - } - } - } - - public BorderStyle BorderStyle - { - set - { - // Error-check the enum. - if (!Enum.IsDefined(typeof(BorderStyle), value)) - { - throw new InvalidEnumArgumentException(); - } - - m_borderStyle = value; - - if (MdiClient == null) - { - return; - } - - // This property can actually be visible in design-mode, - // but to keep it consistent with the others, - // prevent this from being show at design-time. - if (Site != null && Site.DesignMode) - { - return; - } - - // There is no BorderStyle property exposed by the MdiClient class, - // but this can be controlled by Win32 functions. A Win32 ExStyle - // of WS_EX_CLIENTEDGE is equivalent to a Fixed3D border and a - // Style of WS_BORDER is equivalent to a FixedSingle border. - - // This code is inspired Jason Dori's article: - // "Adding designable borders to user controls". - // http://www.codeproject.com/cs/miscctrl/CsAddingBorders.asp - - // Get styles using Win32 calls - int style = NativeMethods.GetWindowLong(MdiClient.Handle, (int) Win32.GetWindowLongIndex.GWL_STYLE); - int exStyle = - NativeMethods.GetWindowLong(MdiClient.Handle, (int) Win32.GetWindowLongIndex.GWL_EXSTYLE); - - // Add or remove style flags as necessary. - switch (m_borderStyle) - { - case BorderStyle.Fixed3D: - exStyle |= (int) Win32.WindowExStyles.WS_EX_CLIENTEDGE; - style &= ~(int) Win32.WindowStyles.WS_BORDER; - break; - - case BorderStyle.FixedSingle: - exStyle &= ~(int) Win32.WindowExStyles.WS_EX_CLIENTEDGE; - style |= (int) Win32.WindowStyles.WS_BORDER; - break; - - case BorderStyle.None: - style &= ~(int) Win32.WindowStyles.WS_BORDER; - exStyle &= ~(int) Win32.WindowExStyles.WS_EX_CLIENTEDGE; - break; - } - - // Set the styles using Win32 calls - NativeMethods.SetWindowLong(MdiClient.Handle, (int) Win32.GetWindowLongIndex.GWL_STYLE, style); - NativeMethods.SetWindowLong(MdiClient.Handle, (int) Win32.GetWindowLongIndex.GWL_EXSTYLE, exStyle); - - // Cause an update of the non-client area. - UpdateStyles(); - } - } - - public MdiClient MdiClient { get; private set; } = null; - - [Browsable(false)] - public Form ParentForm - { - get { return m_parentForm; } - set - { - // If the ParentForm has previously been set, - // unwire events connected to the old parent. - if (m_parentForm != null) - { - m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated); - m_parentForm.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate); - } - - m_parentForm = value; - - if (m_parentForm == null) - { - return; - } - - // If the parent form has not been created yet, - // wait to initialize the MDI client until it is. - if (m_parentForm.IsHandleCreated) - { - InitializeMdiClient(); - RefreshProperties(); - } - else - { - m_parentForm.HandleCreated += new EventHandler(ParentFormHandleCreated); - } - - m_parentForm.MdiChildActivate += new EventHandler(ParentFormMdiChildActivate); - } - } - - public ISite Site - { - get { return m_site; } - set - { - m_site = value; - - if (m_site == null) - { - return; - } - - // If the component is dropped onto a form during design-time, - // set the ParentForm property. - IDesignerHost host = value.GetService(typeof(IDesignerHost)) as IDesignerHost; - if (host != null) - { - Form parent = host.RootComponent as Form; - if (parent != null) - { - ParentForm = parent; - } - } - } - } - - #endregion - - #region Public methods - - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - public void RenewMdiClient() - { - // Reinitialize the MdiClient and its properties. - InitializeMdiClient(); - RefreshProperties(); - } - - #endregion - - #region Overrides - - protected override void WndProc(ref Message m) - { - switch (m.Msg) - { - case (int) Win32.Msgs.WM_NCCALCSIZE: - // If AutoScroll is set to false, hide the scrollbars when the control - // calculates its non-client area. - if (!AutoScroll) - { - NativeMethods.ShowScrollBar(m.HWnd, (int) Win32.ScrollBars.SB_BOTH, 0 /*false*/); - } - break; - } - - base.WndProc(ref m); - } - - #endregion - - #region Private Methods - - private void InitializeMdiClient() - { - // If the mdiClient has previously been set, unwire events connected - // to the old MDI. - if (MdiClient != null) - { - MdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed); - MdiClient.Layout -= new LayoutEventHandler(MdiClientLayout); - } - - if (ParentForm == null) - { - return; - } - - // Get the MdiClient from the parent form. - foreach (Control control in ParentForm.Controls) - { - // If the form is an MDI container, it will contain an MdiClient control - // just as it would any other control. - - MdiClient = control as MdiClient; - if (MdiClient == null) - { - continue; - } - - // Assign the MdiClient Handle to the NativeWindow. - ReleaseHandle(); - AssignHandle(MdiClient.Handle); - - // Raise the HandleAssigned event. - OnHandleAssigned(EventArgs.Empty); - - // Monitor the MdiClient for when its handle is destroyed. - MdiClient.HandleDestroyed += new EventHandler(MdiClientHandleDestroyed); - MdiClient.Layout += new LayoutEventHandler(MdiClientLayout); - - break; - } - } - - private void RefreshProperties() - { - // Refresh all the properties - BorderStyle = m_borderStyle; - AutoScroll = m_autoScroll; - } - - private void UpdateStyles() - { - // To show style changes, the non-client area must be repainted. Using the - // control's Invalidate method does not affect the non-client area. - // Instead use a Win32 call to signal the style has changed. - NativeMethods.SetWindowPos(MdiClient.Handle, IntPtr.Zero, 0, 0, 0, 0, - Win32.FlagsSetWindowPos.SWP_NOACTIVATE | - Win32.FlagsSetWindowPos.SWP_NOMOVE | - Win32.FlagsSetWindowPos.SWP_NOSIZE | - Win32.FlagsSetWindowPos.SWP_NOZORDER | - Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | - Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); - } - - #endregion - - #region Events handler - - private void ParentFormHandleCreated(object sender, EventArgs e) - { - // The form has been created, unwire the event, and initialize the MdiClient. - this.m_parentForm.HandleCreated -= new EventHandler(ParentFormHandleCreated); - InitializeMdiClient(); - RefreshProperties(); - } - - private void ParentFormMdiChildActivate(object sender, EventArgs e) - { - OnMdiChildActivate(e); - } - - private void MdiClientLayout(object sender, LayoutEventArgs e) - { - OnLayout(e); - } - - private void MdiClientHandleDestroyed(object sender, EventArgs e) - { - // If the MdiClient handle has been released, drop the reference and - // release the handle. - if (MdiClient != null) - { - MdiClient.HandleDestroyed -= new EventHandler(MdiClientHandleDestroyed); - MdiClient = null; - } - - ReleaseHandle(); - } - - #endregion - - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - lock (this) - { - if (Site != null && Site.Container != null) - { - Site.Container.Remove(this); - } - - if (Disposed != null) - { - Disposed(this, EventArgs.Empty); - } - } - } - } - - protected virtual void OnHandleAssigned(EventArgs e) - { - // Raise the HandleAssigned event. - if (HandleAssigned != null) - { - HandleAssigned(this, e); - } - } - - protected virtual void OnMdiChildActivate(EventArgs e) - { - // Raise the MdiChildActivate event - if (MdiChildActivate != null) - { - MdiChildActivate(this, e); - } - } - - protected virtual void OnLayout(LayoutEventArgs e) - { - // Raise the Layout event - if (Layout != null) - { - Layout(this, e); - } - } - - protected virtual void OnPaint(PaintEventArgs e) - { - // Raise the Paint event. - if (Paint != null) - { - Paint(this, e); - } - } - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.Persistor.cs b/src/WinFormsUI/Docking/DockPanel.Persistor.cs deleted file mode 100644 index 49d54ff2..00000000 --- a/src/WinFormsUI/Docking/DockPanel.Persistor.cs +++ /dev/null @@ -1,816 +0,0 @@ -using System; -using System.ComponentModel; -using System.Windows.Forms; -using System.Drawing; -using WeifenLuo.WinFormsUI.Docking; -using System.IO; -using System.Text; -using System.Xml; -using System.Globalization; - -namespace WeifenLuo.WinFormsUI.Docking -{ - partial class DockPanel - { - #region Public methods - - public void SaveAsXml(string fileName) - { - Persistor.SaveAsXml(this, fileName); - } - - public void SaveAsXml(string fileName, Encoding encoding) - { - Persistor.SaveAsXml(this, fileName, encoding); - } - - public void SaveAsXml(Stream stream, Encoding encoding) - { - Persistor.SaveAsXml(this, stream, encoding); - } - - public void SaveAsXml(Stream stream, Encoding encoding, bool upstream) - { - Persistor.SaveAsXml(this, stream, encoding, upstream); - } - - public void LoadFromXml(string fileName, DeserializeDockContent deserializeContent) - { - Persistor.LoadFromXml(this, fileName, deserializeContent); - } - - public void LoadFromXml(Stream stream, DeserializeDockContent deserializeContent) - { - Persistor.LoadFromXml(this, stream, deserializeContent); - } - - public void LoadFromXml(Stream stream, DeserializeDockContent deserializeContent, bool closeStream) - { - Persistor.LoadFromXml(this, stream, deserializeContent, closeStream); - } - - #endregion - - private static class Persistor - { - #region Fields - - private const string ConfigFileVersion = "1.0"; - private static readonly string[] CompatibleConfigFileVersions = new string[] { }; - - #endregion - - #region Public methods - - public static void SaveAsXml(DockPanel dockPanel, string fileName) - { - SaveAsXml(dockPanel, fileName, Encoding.Unicode); - } - - public static void SaveAsXml(DockPanel dockPanel, string fileName, Encoding encoding) - { - FileStream fs = new FileStream(fileName, FileMode.Create); - try - { - SaveAsXml(dockPanel, fs, encoding); - } - finally - { - fs.Close(); - } - } - - public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding) - { - SaveAsXml(dockPanel, stream, encoding, false); - } - - public static void SaveAsXml(DockPanel dockPanel, Stream stream, Encoding encoding, bool upstream) - { - XmlTextWriter xmlOut = new XmlTextWriter(stream, encoding); - - // Use indenting for readability - xmlOut.Formatting = Formatting.Indented; - - if (!upstream) - { - xmlOut.WriteStartDocument(); - } - - // Always begin file with identification and warning - xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment1); - xmlOut.WriteComment(Strings.DockPanel_Persistor_XmlFileComment2); - - // Associate a version number with the root element so that future version of the code - // will be able to be backwards compatible or at least recognise out of date versions - xmlOut.WriteStartElement("DockPanel"); - xmlOut.WriteAttributeString("FormatVersion", ConfigFileVersion); - xmlOut.WriteAttributeString("DockLeftPortion", - dockPanel.DockLeftPortion.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("DockRightPortion", - dockPanel.DockRightPortion.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("DockTopPortion", - dockPanel.DockTopPortion.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("DockBottomPortion", - dockPanel.DockBottomPortion.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("ActiveDocumentPane", - dockPanel.Panes.IndexOf(dockPanel.ActiveDocumentPane).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("ActivePane", - dockPanel.Panes.IndexOf(dockPanel.ActivePane).ToString(CultureInfo.InvariantCulture)); - - // Contents - xmlOut.WriteStartElement("Contents"); - xmlOut.WriteAttributeString("Count", dockPanel.Contents.Count.ToString(CultureInfo.InvariantCulture)); - foreach (IDockContent content in dockPanel.Contents) - { - xmlOut.WriteStartElement("Content"); - xmlOut.WriteAttributeString("ID", - dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("PersistString", content.DockHandler.PersistString); - xmlOut.WriteAttributeString("AutoHidePortion", - content.DockHandler.AutoHidePortion.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("IsHidden", - content.DockHandler.IsHidden.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("IsFloat", - content.DockHandler.IsFloat.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteEndElement(); - } - xmlOut.WriteEndElement(); - - // Panes - xmlOut.WriteStartElement("Panes"); - xmlOut.WriteAttributeString("Count", dockPanel.Panes.Count.ToString(CultureInfo.InvariantCulture)); - foreach (DockPane pane in dockPanel.Panes) - { - xmlOut.WriteStartElement("Pane"); - xmlOut.WriteAttributeString("ID", - dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("DockState", pane.DockState.ToString()); - xmlOut.WriteAttributeString("ActiveContent", - dockPanel.Contents.IndexOf(pane.ActiveContent).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteStartElement("Contents"); - xmlOut.WriteAttributeString("Count", pane.Contents.Count.ToString(CultureInfo.InvariantCulture)); - foreach (IDockContent content in pane.Contents) - { - xmlOut.WriteStartElement("Content"); - xmlOut.WriteAttributeString("ID", - pane.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("RefID", - dockPanel.Contents.IndexOf(content).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteEndElement(); - } - xmlOut.WriteEndElement(); - xmlOut.WriteEndElement(); - } - xmlOut.WriteEndElement(); - - // DockWindows - xmlOut.WriteStartElement("DockWindows"); - int dockWindowId = 0; - foreach (DockWindow dw in dockPanel.DockWindows) - { - xmlOut.WriteStartElement("DockWindow"); - xmlOut.WriteAttributeString("ID", dockWindowId.ToString(CultureInfo.InvariantCulture)); - dockWindowId++; - xmlOut.WriteAttributeString("DockState", dw.DockState.ToString()); - xmlOut.WriteAttributeString("ZOrderIndex", - dockPanel.Controls.IndexOf(dw).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteStartElement("NestedPanes"); - xmlOut.WriteAttributeString("Count", dw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture)); - foreach (DockPane pane in dw.NestedPanes) - { - xmlOut.WriteStartElement("Pane"); - xmlOut.WriteAttributeString("ID", - dw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("RefID", - dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture)); - NestedDockingStatus status = pane.NestedDockingStatus; - xmlOut.WriteAttributeString("PrevPane", - dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString()); - xmlOut.WriteAttributeString("Proportion", - status.Proportion.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteEndElement(); - } - xmlOut.WriteEndElement(); - xmlOut.WriteEndElement(); - } - xmlOut.WriteEndElement(); - - // FloatWindows - RectangleConverter rectConverter = new RectangleConverter(); - xmlOut.WriteStartElement("FloatWindows"); - xmlOut.WriteAttributeString("Count", - dockPanel.FloatWindows.Count.ToString(CultureInfo.InvariantCulture)); - foreach (FloatWindow fw in dockPanel.FloatWindows) - { - xmlOut.WriteStartElement("FloatWindow"); - xmlOut.WriteAttributeString("ID", - dockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("Bounds", rectConverter.ConvertToInvariantString(fw.Bounds)); - xmlOut.WriteAttributeString("ZOrderIndex", - fw.DockPanel.FloatWindows.IndexOf(fw).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteStartElement("NestedPanes"); - xmlOut.WriteAttributeString("Count", fw.NestedPanes.Count.ToString(CultureInfo.InvariantCulture)); - foreach (DockPane pane in fw.NestedPanes) - { - xmlOut.WriteStartElement("Pane"); - xmlOut.WriteAttributeString("ID", - fw.NestedPanes.IndexOf(pane).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("RefID", - dockPanel.Panes.IndexOf(pane).ToString(CultureInfo.InvariantCulture)); - NestedDockingStatus status = pane.NestedDockingStatus; - xmlOut.WriteAttributeString("PrevPane", - dockPanel.Panes.IndexOf(status.PreviousPane).ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteAttributeString("Alignment", status.Alignment.ToString()); - xmlOut.WriteAttributeString("Proportion", - status.Proportion.ToString(CultureInfo.InvariantCulture)); - xmlOut.WriteEndElement(); - } - xmlOut.WriteEndElement(); - xmlOut.WriteEndElement(); - } - xmlOut.WriteEndElement(); // - - xmlOut.WriteEndElement(); - - if (!upstream) - { - xmlOut.WriteEndDocument(); - xmlOut.Close(); - } - else - { - xmlOut.Flush(); - } - } - - public static void LoadFromXml(DockPanel dockPanel, string fileName, - DeserializeDockContent deserializeContent) - { - FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); - try - { - LoadFromXml(dockPanel, fs, deserializeContent); - } - finally - { - fs.Close(); - } - } - - public static void LoadFromXml(DockPanel dockPanel, Stream stream, - DeserializeDockContent deserializeContent) - { - LoadFromXml(dockPanel, stream, deserializeContent, true); - } - - public static void LoadFromXml(DockPanel dockPanel, Stream stream, - DeserializeDockContent deserializeContent, bool closeStream) - { - if (dockPanel.Contents.Count != 0) - { - //TODO this happens if a session is loaded and the dialog is just closed, this needs to be adressed - throw new InvalidOperationException(Strings.DockPanel_LoadFromXml_AlreadyInitialized); - } - - XmlTextReader xmlIn = new XmlTextReader(stream); - xmlIn.WhitespaceHandling = WhitespaceHandling.None; - xmlIn.MoveToContent(); - - while (!xmlIn.Name.Equals("DockPanel")) - { - if (!MoveToNextElement(xmlIn)) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - } - - string formatVersion = xmlIn.GetAttribute("FormatVersion"); - if (!IsFormatVersionValid(formatVersion)) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidFormatVersion); - } - - DockPanelStruct dockPanelStruct = new DockPanelStruct(); - dockPanelStruct.DockLeftPortion = - Convert.ToDouble(xmlIn.GetAttribute("DockLeftPortion"), CultureInfo.InvariantCulture); - dockPanelStruct.DockRightPortion = Convert.ToDouble(xmlIn.GetAttribute("DockRightPortion"), - CultureInfo.InvariantCulture); - dockPanelStruct.DockTopPortion = - Convert.ToDouble(xmlIn.GetAttribute("DockTopPortion"), CultureInfo.InvariantCulture); - dockPanelStruct.DockBottomPortion = Convert.ToDouble(xmlIn.GetAttribute("DockBottomPortion"), - CultureInfo.InvariantCulture); - dockPanelStruct.IndexActiveDocumentPane = Convert.ToInt32(xmlIn.GetAttribute("ActiveDocumentPane"), - CultureInfo.InvariantCulture); - dockPanelStruct.IndexActivePane = - Convert.ToInt32(xmlIn.GetAttribute("ActivePane"), CultureInfo.InvariantCulture); - - // Load Contents - MoveToNextElement(xmlIn); - if (xmlIn.Name != "Contents") - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - ContentStruct[] contents = LoadContents(xmlIn); - - // Load Panes - if (xmlIn.Name != "Panes") - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - PaneStruct[] panes = LoadPanes(xmlIn); - - // Load DockWindows - if (xmlIn.Name != "DockWindows") - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - DockWindowStruct[] dockWindows = LoadDockWindows(xmlIn, dockPanel); - - // Load FloatWindows - if (xmlIn.Name != "FloatWindows") - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - FloatWindowStruct[] floatWindows = LoadFloatWindows(xmlIn); - - if (closeStream) - { - xmlIn.Close(); - } - - dockPanel.SuspendLayout(true); - - dockPanel.DockLeftPortion = dockPanelStruct.DockLeftPortion; - dockPanel.DockRightPortion = dockPanelStruct.DockRightPortion; - dockPanel.DockTopPortion = dockPanelStruct.DockTopPortion; - dockPanel.DockBottomPortion = dockPanelStruct.DockBottomPortion; - - // Set DockWindow ZOrders - int prevMaxDockWindowZOrder = int.MaxValue; - for (int i = 0; i < dockWindows.Length; i++) - { - int maxDockWindowZOrder = -1; - int index = -1; - for (int j = 0; j < dockWindows.Length; j++) - { - if (dockWindows[j].ZOrderIndex > maxDockWindowZOrder && - dockWindows[j].ZOrderIndex < prevMaxDockWindowZOrder) - { - maxDockWindowZOrder = dockWindows[j].ZOrderIndex; - index = j; - } - } - - dockPanel.DockWindows[dockWindows[index].DockState].BringToFront(); - prevMaxDockWindowZOrder = maxDockWindowZOrder; - } - - // Create Contents - for (int i = 0; i < contents.Length; i++) - { - IDockContent content = deserializeContent(contents[i].PersistString); - if (content == null) - { - content = new DummyContent(); - } - content.DockHandler.DockPanel = dockPanel; - content.DockHandler.AutoHidePortion = contents[i].AutoHidePortion; - content.DockHandler.IsHidden = true; - content.DockHandler.IsFloat = contents[i].IsFloat; - } - - // Create panes - for (int i = 0; i < panes.Length; i++) - { - DockPane pane = null; - for (int j = 0; j < panes[i].IndexContents.Length; j++) - { - IDockContent content = dockPanel.Contents[panes[i].IndexContents[j]]; - if (j == 0) - { - pane = dockPanel.DockPaneFactory.CreateDockPane(content, panes[i].DockState, false); - } - else if (panes[i].DockState == DockState.Float) - { - content.DockHandler.FloatPane = pane; - } - else - { - content.DockHandler.PanelPane = pane; - } - } - } - - // Assign Panes to DockWindows - for (int i = 0; i < dockWindows.Length; i++) - { - for (int j = 0; j < dockWindows[i].NestedPanes.Length; j++) - { - DockWindow dw = dockPanel.DockWindows[dockWindows[i].DockState]; - int indexPane = dockWindows[i].NestedPanes[j].IndexPane; - DockPane pane = dockPanel.Panes[indexPane]; - int indexPrevPane = dockWindows[i].NestedPanes[j].IndexPrevPane; - DockPane prevPane = indexPrevPane == -1 - ? dw.NestedPanes.GetDefaultPreviousPane(pane) - : dockPanel.Panes[indexPrevPane]; - DockAlignment alignment = dockWindows[i].NestedPanes[j].Alignment; - double proportion = dockWindows[i].NestedPanes[j].Proportion; - pane.DockTo(dw, prevPane, alignment, proportion); - if (panes[indexPane].DockState == dw.DockState) - { - panes[indexPane].ZOrderIndex = dockWindows[i].ZOrderIndex; - } - } - } - - // Create float windows - for (int i = 0; i < floatWindows.Length; i++) - { - FloatWindow fw = null; - for (int j = 0; j < floatWindows[i].NestedPanes.Length; j++) - { - int indexPane = floatWindows[i].NestedPanes[j].IndexPane; - DockPane pane = dockPanel.Panes[indexPane]; - if (j == 0) - { - fw = dockPanel.FloatWindowFactory.CreateFloatWindow(dockPanel, pane, - floatWindows[i].Bounds); - } - else - { - int indexPrevPane = floatWindows[i].NestedPanes[j].IndexPrevPane; - DockPane prevPane = indexPrevPane == -1 ? null : dockPanel.Panes[indexPrevPane]; - DockAlignment alignment = floatWindows[i].NestedPanes[j].Alignment; - double proportion = floatWindows[i].NestedPanes[j].Proportion; - pane.DockTo(fw, prevPane, alignment, proportion); - } - - if (panes[indexPane].DockState == fw.DockState) - { - panes[indexPane].ZOrderIndex = floatWindows[i].ZOrderIndex; - } - } - } - - // sort IDockContent by its Pane's ZOrder - int[] sortedContents = null; - if (contents.Length > 0) - { - sortedContents = new int[contents.Length]; - for (int i = 0; i < contents.Length; i++) - { - sortedContents[i] = i; - } - - int lastDocument = contents.Length; - for (int i = 0; i < contents.Length - 1; i++) - { - for (int j = i + 1; j < contents.Length; j++) - { - DockPane pane1 = dockPanel.Contents[sortedContents[i]].DockHandler.Pane; - int ZOrderIndex1 = pane1 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane1)].ZOrderIndex; - DockPane pane2 = dockPanel.Contents[sortedContents[j]].DockHandler.Pane; - int ZOrderIndex2 = pane2 == null ? 0 : panes[dockPanel.Panes.IndexOf(pane2)].ZOrderIndex; - if (ZOrderIndex1 > ZOrderIndex2) - { - int temp = sortedContents[i]; - sortedContents[i] = sortedContents[j]; - sortedContents[j] = temp; - } - } - } - } - - // show non-document IDockContent first to avoid screen flickers - for (int i = 0; i < contents.Length; i++) - { - IDockContent content = dockPanel.Contents[sortedContents[i]]; - if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState != DockState.Document) - { - content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden; - } - } - - // after all non-document IDockContent, show document IDockContent - for (int i = 0; i < contents.Length; i++) - { - IDockContent content = dockPanel.Contents[sortedContents[i]]; - if (content.DockHandler.Pane != null && content.DockHandler.Pane.DockState == DockState.Document) - { - content.DockHandler.IsHidden = contents[sortedContents[i]].IsHidden; - } - } - - for (int i = 0; i < panes.Length; i++) - { - dockPanel.Panes[i].ActiveContent = panes[i].IndexActiveContent == -1 - ? null - : dockPanel.Contents[panes[i].IndexActiveContent]; - } - - if (dockPanelStruct.IndexActiveDocumentPane != -1) - { - dockPanel.Panes[dockPanelStruct.IndexActiveDocumentPane].Activate(); - } - - if (dockPanelStruct.IndexActivePane != -1) - { - dockPanel.Panes[dockPanelStruct.IndexActivePane].Activate(); - } - - for (int i = dockPanel.Contents.Count - 1; i >= 0; i--) - { - if (dockPanel.Contents[i] is DummyContent) - { - dockPanel.Contents[i].DockHandler.Form.Close(); - } - } - - dockPanel.ResumeLayout(true, true); - } - - #endregion - - #region Private Methods - - private static ContentStruct[] LoadContents(XmlTextReader xmlIn) - { - int countOfContents = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture); - ContentStruct[] contents = new ContentStruct[countOfContents]; - MoveToNextElement(xmlIn); - for (int i = 0; i < countOfContents; i++) - { - int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture); - if (xmlIn.Name != "Content" || id != i) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - - contents[i].PersistString = xmlIn.GetAttribute("PersistString"); - contents[i].AutoHidePortion = Convert.ToDouble(xmlIn.GetAttribute("AutoHidePortion"), - CultureInfo.InvariantCulture); - contents[i].IsHidden = - Convert.ToBoolean(xmlIn.GetAttribute("IsHidden"), CultureInfo.InvariantCulture); - contents[i].IsFloat = - Convert.ToBoolean(xmlIn.GetAttribute("IsFloat"), CultureInfo.InvariantCulture); - MoveToNextElement(xmlIn); - } - - return contents; - } - - private static PaneStruct[] LoadPanes(XmlTextReader xmlIn) - { - EnumConverter dockStateConverter = new EnumConverter(typeof(DockState)); - int countOfPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture); - PaneStruct[] panes = new PaneStruct[countOfPanes]; - MoveToNextElement(xmlIn); - for (int i = 0; i < countOfPanes; i++) - { - int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture); - if (xmlIn.Name != "Pane" || id != i) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - - panes[i].DockState = (DockState) dockStateConverter.ConvertFrom(xmlIn.GetAttribute("DockState")); - panes[i].IndexActiveContent = Convert.ToInt32(xmlIn.GetAttribute("ActiveContent"), - CultureInfo.InvariantCulture); - panes[i].ZOrderIndex = -1; - - MoveToNextElement(xmlIn); - if (xmlIn.Name != "Contents") - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - int countOfPaneContents = - Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture); - panes[i].IndexContents = new int[countOfPaneContents]; - MoveToNextElement(xmlIn); - for (int j = 0; j < countOfPaneContents; j++) - { - int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture); - if (xmlIn.Name != "Content" || id2 != j) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - - panes[i].IndexContents[j] = - Convert.ToInt32(xmlIn.GetAttribute("RefID"), CultureInfo.InvariantCulture); - MoveToNextElement(xmlIn); - } - } - - return panes; - } - - private static DockWindowStruct[] LoadDockWindows(XmlTextReader xmlIn, DockPanel dockPanel) - { - EnumConverter dockStateConverter = new EnumConverter(typeof(DockState)); - EnumConverter dockAlignmentConverter = new EnumConverter(typeof(DockAlignment)); - int countOfDockWindows = dockPanel.DockWindows.Count; - DockWindowStruct[] dockWindows = new DockWindowStruct[countOfDockWindows]; - MoveToNextElement(xmlIn); - for (int i = 0; i < countOfDockWindows; i++) - { - int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture); - if (xmlIn.Name != "DockWindow" || id != i) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - - dockWindows[i].DockState = - (DockState) dockStateConverter.ConvertFrom(xmlIn.GetAttribute("DockState")); - dockWindows[i].ZOrderIndex = - Convert.ToInt32(xmlIn.GetAttribute("ZOrderIndex"), CultureInfo.InvariantCulture); - MoveToNextElement(xmlIn); - if (xmlIn.Name != "DockList" && xmlIn.Name != "NestedPanes") - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - int countOfNestedPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture); - dockWindows[i].NestedPanes = new NestedPane[countOfNestedPanes]; - MoveToNextElement(xmlIn); - for (int j = 0; j < countOfNestedPanes; j++) - { - int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture); - if (xmlIn.Name != "Pane" || id2 != j) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - dockWindows[i].NestedPanes[j].IndexPane = Convert.ToInt32(xmlIn.GetAttribute("RefID"), - CultureInfo.InvariantCulture); - dockWindows[i].NestedPanes[j].IndexPrevPane = Convert.ToInt32(xmlIn.GetAttribute("PrevPane"), - CultureInfo.InvariantCulture); - dockWindows[i].NestedPanes[j].Alignment = - (DockAlignment) dockAlignmentConverter.ConvertFrom(xmlIn.GetAttribute("Alignment")); - dockWindows[i].NestedPanes[j].Proportion = Convert.ToDouble(xmlIn.GetAttribute("Proportion"), - CultureInfo.InvariantCulture); - MoveToNextElement(xmlIn); - } - } - - return dockWindows; - } - - private static FloatWindowStruct[] LoadFloatWindows(XmlTextReader xmlIn) - { - EnumConverter dockAlignmentConverter = new EnumConverter(typeof(DockAlignment)); - RectangleConverter rectConverter = new RectangleConverter(); - int countOfFloatWindows = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture); - FloatWindowStruct[] floatWindows = new FloatWindowStruct[countOfFloatWindows]; - MoveToNextElement(xmlIn); - for (int i = 0; i < countOfFloatWindows; i++) - { - int id = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture); - if (xmlIn.Name != "FloatWindow" || id != i) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - - floatWindows[i].Bounds = - (Rectangle) rectConverter.ConvertFromInvariantString(xmlIn.GetAttribute("Bounds")); - floatWindows[i].ZOrderIndex = - Convert.ToInt32(xmlIn.GetAttribute("ZOrderIndex"), CultureInfo.InvariantCulture); - MoveToNextElement(xmlIn); - if (xmlIn.Name != "DockList" && xmlIn.Name != "NestedPanes") - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - int countOfNestedPanes = Convert.ToInt32(xmlIn.GetAttribute("Count"), CultureInfo.InvariantCulture); - floatWindows[i].NestedPanes = new NestedPane[countOfNestedPanes]; - MoveToNextElement(xmlIn); - for (int j = 0; j < countOfNestedPanes; j++) - { - int id2 = Convert.ToInt32(xmlIn.GetAttribute("ID"), CultureInfo.InvariantCulture); - if (xmlIn.Name != "Pane" || id2 != j) - { - throw new ArgumentException(Strings.DockPanel_LoadFromXml_InvalidXmlFormat); - } - floatWindows[i].NestedPanes[j].IndexPane = Convert.ToInt32(xmlIn.GetAttribute("RefID"), - CultureInfo.InvariantCulture); - floatWindows[i].NestedPanes[j].IndexPrevPane = Convert.ToInt32(xmlIn.GetAttribute("PrevPane"), - CultureInfo.InvariantCulture); - floatWindows[i].NestedPanes[j].Alignment = - (DockAlignment) dockAlignmentConverter.ConvertFrom(xmlIn.GetAttribute("Alignment")); - floatWindows[i].NestedPanes[j].Proportion = Convert.ToDouble(xmlIn.GetAttribute("Proportion"), - CultureInfo.InvariantCulture); - MoveToNextElement(xmlIn); - } - } - - return floatWindows; - } - - private static bool MoveToNextElement(XmlTextReader xmlIn) - { - if (!xmlIn.Read()) - { - return false; - } - - while (xmlIn.NodeType == XmlNodeType.EndElement) - { - if (!xmlIn.Read()) - { - return false; - } - } - - return true; - } - - private static bool IsFormatVersionValid(string formatVersion) - { - if (formatVersion == ConfigFileVersion) - { - return true; - } - - foreach (string s in CompatibleConfigFileVersions) - { - if (s == formatVersion) - { - return true; - } - } - - return false; - } - - #endregion - - private class DummyContent : DockContent - { - } - - private struct DockPanelStruct - { - public double DockLeftPortion { get; set; } - - public double DockRightPortion { get; set; } - - public double DockTopPortion { get; set; } - - public double DockBottomPortion { get; set; } - - public int IndexActiveDocumentPane { get; set; } - - public int IndexActivePane { get; set; } - } - - private struct ContentStruct - { - public string PersistString { get; set; } - - public double AutoHidePortion { get; set; } - - public bool IsHidden { get; set; } - - public bool IsFloat { get; set; } - } - - private struct PaneStruct - { - public DockState DockState { get; set; } - - public int IndexActiveContent { get; set; } - - public int[] IndexContents { get; set; } - - public int ZOrderIndex { get; set; } - } - - private struct NestedPane - { - public int IndexPane { get; set; } - - public int IndexPrevPane { get; set; } - - public DockAlignment Alignment { get; set; } - - public double Proportion { get; set; } - } - - private struct DockWindowStruct - { - public DockState DockState { get; set; } - - public int ZOrderIndex { get; set; } - - public NestedPane[] NestedPanes { get; set; } - } - - private struct FloatWindowStruct - { - public Rectangle Bounds { get; set; } - - public int ZOrderIndex { get; set; } - - public NestedPane[] NestedPanes { get; set; } - } - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.SplitterDragHandler.cs b/src/WinFormsUI/Docking/DockPanel.SplitterDragHandler.cs deleted file mode 100644 index 74838ae2..00000000 --- a/src/WinFormsUI/Docking/DockPanel.SplitterDragHandler.cs +++ /dev/null @@ -1,230 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.ComponentModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - partial class DockPanel - { - #region Fields - - private SplitterDragHandler m_splitterDragHandler = null; - - #endregion - - #region Internals - - internal void BeginDrag(ISplitterDragSource dragSource, Rectangle rectSplitter) - { - GetSplitterDragHandler().BeginDrag(dragSource, rectSplitter); - } - - #endregion - - #region Private Methods - - private SplitterDragHandler GetSplitterDragHandler() - { - if (m_splitterDragHandler == null) - { - m_splitterDragHandler = new SplitterDragHandler(this); - } - return m_splitterDragHandler; - } - - #endregion - - private sealed class SplitterDragHandler : DragHandler - { - #region Fields - - #endregion - - #region cTor - - public SplitterDragHandler(DockPanel dockPanel) - : base(dockPanel) - { - } - - #endregion - - #region Properties - - public new ISplitterDragSource DragSource - { - get { return base.DragSource as ISplitterDragSource; } - private set { base.DragSource = value; } - } - - private SplitterOutline Outline { get; set; } - - private Rectangle RectSplitter { get; set; } - - #endregion - - #region Public methods - - public void BeginDrag(ISplitterDragSource dragSource, Rectangle rectSplitter) - { - DragSource = dragSource; - RectSplitter = rectSplitter; - - if (!BeginDrag()) - { - DragSource = null; - return; - } - - Outline = new SplitterOutline(); - Outline.Show(rectSplitter); - DragSource.BeginDrag(rectSplitter); - } - - #endregion - - #region Overrides - - protected override void OnDragging() - { - Outline.Show(GetSplitterOutlineBounds(Control.MousePosition)); - } - - protected override void OnEndDrag(bool abort) - { - DockPanel.SuspendLayout(true); - - Outline.Close(); - - if (!abort) - { - DragSource.MoveSplitter(GetMovingOffset(Control.MousePosition)); - } - - DragSource.EndDrag(); - DockPanel.ResumeLayout(true, true); - } - - #endregion - - #region Private Methods - - private int GetMovingOffset(Point ptMouse) - { - Rectangle rect = GetSplitterOutlineBounds(ptMouse); - if (DragSource.IsVertical) - { - return rect.X - RectSplitter.X; - } - else - { - return rect.Y - RectSplitter.Y; - } - } - - private Rectangle GetSplitterOutlineBounds(Point ptMouse) - { - Rectangle rectLimit = DragSource.DragLimitBounds; - - Rectangle rect = RectSplitter; - if (rectLimit.Width <= 0 || rectLimit.Height <= 0) - { - return rect; - } - - if (DragSource.IsVertical) - { - rect.X += ptMouse.X - StartMousePosition.X; - rect.Height = rectLimit.Height; - } - else - { - rect.Y += ptMouse.Y - StartMousePosition.Y; - rect.Width = rectLimit.Width; - } - - if (rect.Left < rectLimit.Left) - { - rect.X = rectLimit.X; - } - if (rect.Top < rectLimit.Top) - { - rect.Y = rectLimit.Y; - } - if (rect.Right > rectLimit.Right) - { - rect.X -= rect.Right - rectLimit.Right; - } - if (rect.Bottom > rectLimit.Bottom) - { - rect.Y -= rect.Bottom - rectLimit.Bottom; - } - - return rect; - } - - #endregion - - private class SplitterOutline - { - #region Fields - - #endregion - - #region cTor - - public SplitterOutline() - { - DragForm = new DragForm(); - SetDragForm(Rectangle.Empty); - DragForm.BackColor = Color.Black; - DragForm.Opacity = 0.7; - DragForm.Show(false); - } - - #endregion - - #region Properties - - private DragForm DragForm { get; } - - #endregion - - #region Public methods - - public void Show(Rectangle rect) - { - SetDragForm(rect); - } - - public void Close() - { - DragForm.Close(); - } - - #endregion - - #region Private Methods - - private void SetDragForm(Rectangle rect) - { - DragForm.Bounds = rect; - if (rect == Rectangle.Empty) - { - DragForm.Region = new Region(Rectangle.Empty); - } - else if (DragForm.Region != null) - { - DragForm.Region = null; - } - } - - #endregion - } - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanel.bmp b/src/WinFormsUI/Docking/DockPanel.bmp deleted file mode 100644 index 10d6858f..00000000 Binary files a/src/WinFormsUI/Docking/DockPanel.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/DockPanel.cs b/src/WinFormsUI/Docking/DockPanel.cs deleted file mode 100644 index 6012c27b..00000000 --- a/src/WinFormsUI/Docking/DockPanel.cs +++ /dev/null @@ -1,1208 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Windows.Forms; - -// To simplify the process of finding the toolbox bitmap resource: -// #1 Create an internal class called "resfinder" outside of the root namespace. -// #2 Use "resfinder" in the toolbox bitmap attribute instead of the control name. -// #3 use the "." string to locate the resource. -// See: http://www.bobpowell.net/toolboxbitmap.htm -#pragma warning disable CS8981 // The type name only contains lower-cased ascii characters. Such names may become reserved for the language. -internal class resfinder -#pragma warning restore CS8981 // The type name only contains lower-cased ascii characters. Such names may become reserved for the language. -{ -} - -namespace WeifenLuo.WinFormsUI.Docking -{ - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "0#")] - public delegate IDockContent DeserializeDockContent(string persistString); - - [LocalizedDescription("DockPanel_Description")] - [Designer(typeof(System.Windows.Forms.Design.ControlDesigner))] - [ToolboxBitmap(typeof(resfinder), "WeifenLuo.WinFormsUI.Docking.DockPanel.bmp")] - [DefaultProperty("DocumentStyle")] - [DefaultEvent("ActiveContentChanged")] - public partial class DockPanel : Panel - { - #region Fields - - private static readonly object ContentAddedEvent = new object(); - - private static readonly object ContentRemovedEvent = new object(); - - private AutoHideStripBase m_autoHideStripControl = null; - - private Color m_BackColor; - - private Rectangle[] m_clipRects = null; - - private bool m_disposed = false; - - private double m_dockBottomPortion = 0.25; - - private double m_dockLeftPortion = 0.25; - - private double m_dockRightPortion = 0.25; - - private double m_dockTopPortion = 0.25; - - private DocumentStyle m_documentStyle = DocumentStyle.DockingMdi; - - private PaintEventHandler m_dummyControlPaintEventHandler = null; - private readonly FocusManagerImpl m_focusManager; - - private bool m_rightToLeftLayout = false; - - private bool m_showDocumentIcon = false; - - #endregion - - #region cTor - - public DockPanel() - { - m_focusManager = new FocusManagerImpl(this); - Extender = new DockPanelExtender(this); - Panes = new DockPaneCollection(); - FloatWindows = new FloatWindowCollection(); - - SuspendLayout(); - - AutoHideWindow = new AutoHideWindowControl(this); - AutoHideWindow.Visible = false; - SetAutoHideWindowParent(); - - DummyControl = new DummyControl(); - DummyControl.Bounds = new Rectangle(0, 0, 1, 1); - Controls.Add(DummyControl); - - DockWindows = new DockWindowCollection(this); - Controls.AddRange(new Control[] - { - DockWindows[DockState.Document], - DockWindows[DockState.DockLeft], - DockWindows[DockState.DockRight], - DockWindows[DockState.DockTop], - DockWindows[DockState.DockBottom] - }); - - DummyContent = new DockContent(); - ResumeLayout(); - } - - #endregion - - #region Events - - [LocalizedCategory("Category_DockingNotification")] - [LocalizedDescription("DockPanel_ContentAdded_Description")] - public event EventHandler ContentAdded - { - add { Events.AddHandler(ContentAddedEvent, value); } - remove { Events.RemoveHandler(ContentAddedEvent, value); } - } - - [LocalizedCategory("Category_DockingNotification")] - [LocalizedDescription("DockPanel_ContentRemoved_Description")] - public event EventHandler ContentRemoved - { - add { Events.AddHandler(ContentRemovedEvent, value); } - remove { Events.RemoveHandler(ContentRemovedEvent, value); } - } - - #endregion - - #region Properties - - /// - /// Determines the color with which the client rectangle will be drawn. - /// If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane). - /// The BackColor property changes the borders of surrounding controls (DockPane). - /// Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle). - /// For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control) - /// - [Description("Determines the color with which the client rectangle will be drawn.\r\n" + - "If this property is used instead of the BackColor it will not have any influence on the borders to the surrounding controls (DockPane).\r\n" + - "The BackColor property changes the borders of surrounding controls (DockPane).\r\n" + - "Alternatively both properties may be used (BackColor to draw and define the color of the borders and DockBackColor to define the color of the client rectangle).\r\n" + - "For Backgroundimages: Set your prefered Image, then set the DockBackColor and the BackColor to the same Color (Control).")] - public Color DockBackColor - { - get { return !m_BackColor.IsEmpty ? m_BackColor : base.BackColor; } - set - { - if (m_BackColor != value) - { - m_BackColor = value; - Refresh(); - } - } - } - - internal AutoHideStripBase AutoHideStripControl - { - get - { - if (m_autoHideStripControl == null) - { - m_autoHideStripControl = AutoHideStripFactory.CreateAutoHideStrip(this); - Controls.Add(m_autoHideStripControl); - } - return m_autoHideStripControl; - } - } - - [Browsable(false)] - public IDockContent ActiveAutoHideContent - { - get { return AutoHideWindow.ActiveContent; } - set { AutoHideWindow.ActiveContent = value; } - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_AllowEndUserDocking_Description")] - [DefaultValue(true)] - public bool AllowEndUserDocking { get; set; } = true; - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_AllowEndUserNestedDocking_Description")] - [DefaultValue(true)] - public bool AllowEndUserNestedDocking { get; set; } = true; - - [Browsable(false)] - public DockContentCollection Contents { get; } = new DockContentCollection(); - - internal DockContent DummyContent { get; } - - [DefaultValue(false)] - [LocalizedCategory("Appearance")] - [LocalizedDescription("DockPanel_RightToLeftLayout_Description")] - public bool RightToLeftLayout - { - get { return m_rightToLeftLayout; } - set - { - if (m_rightToLeftLayout == value) - { - return; - } - - m_rightToLeftLayout = value; - foreach (FloatWindow floatWindow in FloatWindows) - { - floatWindow.RightToLeftLayout = value; - } - } - } - - [DefaultValue(false)] - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_ShowDocumentIcon_Description")] - public bool ShowDocumentIcon - { - get { return m_showDocumentIcon; } - set - { - if (m_showDocumentIcon == value) - { - return; - } - - m_showDocumentIcon = value; - Refresh(); - } - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_DockPanelSkin")] - public DockPanelSkin Skin { get; set; } = new DockPanelSkin(); - - [DefaultValue(DocumentTabStripLocation.Top)] - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_DocumentTabStripLocation")] - public DocumentTabStripLocation DocumentTabStripLocation { get; set; } = DocumentTabStripLocation.Top; - - [Browsable(false)] - public DockPanelExtender Extender { get; } - - [Browsable(false)] - public DockPanelExtender.IDockPaneFactory DockPaneFactory - { - get { return Extender.DockPaneFactory; } - } - - [Browsable(false)] - public DockPanelExtender.IFloatWindowFactory FloatWindowFactory - { - get { return Extender.FloatWindowFactory; } - } - - internal DockPanelExtender.IDockPaneCaptionFactory DockPaneCaptionFactory - { - get { return Extender.DockPaneCaptionFactory; } - } - - internal DockPanelExtender.IDockPaneStripFactory DockPaneStripFactory - { - get { return Extender.DockPaneStripFactory; } - } - - internal DockPanelExtender.IAutoHideStripFactory AutoHideStripFactory - { - get { return Extender.AutoHideStripFactory; } - } - - [Browsable(false)] - public DockPaneCollection Panes { get; } - - internal Rectangle DockArea - { - get - { - return new Rectangle(DockPadding.Left, DockPadding.Top, - ClientRectangle.Width - DockPadding.Left - DockPadding.Right, - ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom); - } - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_DockBottomPortion_Description")] - [DefaultValue(0.25)] - public double DockBottomPortion - { - get { return m_dockBottomPortion; } - set - { - if (value <= 0) - { - throw new ArgumentOutOfRangeException("value"); - } - - if (value == m_dockBottomPortion) - { - return; - } - - m_dockBottomPortion = value; - - if (m_dockBottomPortion < 1 && m_dockTopPortion < 1) - { - if (m_dockTopPortion + m_dockBottomPortion > 1) - { - m_dockTopPortion = 1 - m_dockBottomPortion; - } - } - - PerformLayout(); - } - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_DockLeftPortion_Description")] - [DefaultValue(0.25)] - public double DockLeftPortion - { - get { return m_dockLeftPortion; } - set - { - if (value <= 0) - { - throw new ArgumentOutOfRangeException("value"); - } - - if (value == m_dockLeftPortion) - { - return; - } - - m_dockLeftPortion = value; - - if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) - { - if (m_dockLeftPortion + m_dockRightPortion > 1) - { - m_dockRightPortion = 1 - m_dockLeftPortion; - } - } - PerformLayout(); - } - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_DockRightPortion_Description")] - [DefaultValue(0.25)] - public double DockRightPortion - { - get { return m_dockRightPortion; } - set - { - if (value <= 0) - { - throw new ArgumentOutOfRangeException("value"); - } - - if (value == m_dockRightPortion) - { - return; - } - - m_dockRightPortion = value; - - if (m_dockLeftPortion < 1 && m_dockRightPortion < 1) - { - if (m_dockLeftPortion + m_dockRightPortion > 1) - { - m_dockLeftPortion = 1 - m_dockRightPortion; - } - } - PerformLayout(); - } - } - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_DockTopPortion_Description")] - [DefaultValue(0.25)] - public double DockTopPortion - { - get { return m_dockTopPortion; } - set - { - if (value <= 0) - { - throw new ArgumentOutOfRangeException("value"); - } - - if (value == m_dockTopPortion) - { - return; - } - - m_dockTopPortion = value; - - if (m_dockTopPortion < 1 && m_dockBottomPortion < 1) - { - if (m_dockTopPortion + m_dockBottomPortion > 1) - { - m_dockBottomPortion = 1 - m_dockTopPortion; - } - } - PerformLayout(); - } - } - - [Browsable(false)] - public DockWindowCollection DockWindows { get; } - - [Browsable(false)] - public int DocumentsCount - { - get - { - int count = 0; - foreach (IDockContent content in Documents) - { - count++; - } - - return count; - } - } - - [Browsable(false)] - public IEnumerable Documents - { - get - { - foreach (IDockContent content in Contents) - { - if (content.DockHandler.DockState == DockState.Document) - { - yield return content; - } - } - } - } - - private Rectangle DocumentRectangle - { - get - { - Rectangle rect = DockArea; - if (DockWindows[DockState.DockLeft].VisibleNestedPanes.Count != 0) - { - rect.X += (int)(DockArea.Width * DockLeftPortion); - rect.Width -= (int)(DockArea.Width * DockLeftPortion); - } - if (DockWindows[DockState.DockRight].VisibleNestedPanes.Count != 0) - { - rect.Width -= (int)(DockArea.Width * DockRightPortion); - } - if (DockWindows[DockState.DockTop].VisibleNestedPanes.Count != 0) - { - rect.Y += (int)(DockArea.Height * DockTopPortion); - rect.Height -= (int)(DockArea.Height * DockTopPortion); - } - if (DockWindows[DockState.DockBottom].VisibleNestedPanes.Count != 0) - { - rect.Height -= (int)(DockArea.Height * DockBottomPortion); - } - - return rect; - } - } - - private Control DummyControl { get; } - - [Browsable(false)] - public FloatWindowCollection FloatWindows { get; } - - [Category("Layout")] - [LocalizedDescription("DockPanel_DefaultFloatWindowSize_Description")] - public Size DefaultFloatWindowSize { get; set; } = new Size(300, 300); - - [LocalizedCategory("Category_Docking")] - [LocalizedDescription("DockPanel_DocumentStyle_Description")] - [DefaultValue(DocumentStyle.DockingMdi)] - public DocumentStyle DocumentStyle - { - get { return m_documentStyle; } - set - { - if (value == m_documentStyle) - { - return; - } - - if (!Enum.IsDefined(typeof(DocumentStyle), value)) - { - throw new InvalidEnumArgumentException(); - } - - if (value == DocumentStyle.SystemMdi && DockWindows[DockState.Document].VisibleNestedPanes.Count > 0) - { - throw new InvalidEnumArgumentException(); - } - - m_documentStyle = value; - - SuspendLayout(true); - - SetAutoHideWindowParent(); - SetMdiClient(); - InvalidateWindowRegion(); - - foreach (IDockContent content in Contents) - { - if (content.DockHandler.DockState == DockState.Document) - { - content.DockHandler.SetPaneAndVisible(content.DockHandler.Pane); - } - } - - PerformMdiClientLayout(); - - ResumeLayout(true, true); - } - } - - internal Form ParentForm - { - get - { - if (!IsParentFormValid()) - { - throw new InvalidOperationException(Strings.DockPanel_ParentForm_Invalid); - } - - return GetMdiClientController().ParentForm; - } - } - - private Rectangle SystemMdiClientBounds - { - get - { - if (!IsParentFormValid() || !Visible) - { - return Rectangle.Empty; - } - - Rectangle rect = ParentForm.RectangleToClient(RectangleToScreen(DocumentWindowBounds)); - return rect; - } - } - - internal Rectangle DocumentWindowBounds - { - get - { - Rectangle rectDocumentBounds = DisplayRectangle; - if (DockWindows[DockState.DockLeft].Visible) - { - rectDocumentBounds.X += DockWindows[DockState.DockLeft].Width; - rectDocumentBounds.Width -= DockWindows[DockState.DockLeft].Width; - } - if (DockWindows[DockState.DockRight].Visible) - { - rectDocumentBounds.Width -= DockWindows[DockState.DockRight].Width; - } - if (DockWindows[DockState.DockTop].Visible) - { - rectDocumentBounds.Y += DockWindows[DockState.DockTop].Height; - rectDocumentBounds.Height -= DockWindows[DockState.DockTop].Height; - } - if (DockWindows[DockState.DockBottom].Visible) - { - rectDocumentBounds.Height -= DockWindows[DockState.DockBottom].Height; - } - - return rectDocumentBounds; - } - } - - #endregion - - #region Public methods - - public void UpdateDockWindowZOrder(DockStyle dockStyle, bool fullPanelEdge) - { - if (dockStyle == DockStyle.Left) - { - if (fullPanelEdge) - { - DockWindows[DockState.DockLeft].SendToBack(); - } - else - { - DockWindows[DockState.DockLeft].BringToFront(); - } - } - else if (dockStyle == DockStyle.Right) - { - if (fullPanelEdge) - { - DockWindows[DockState.DockRight].SendToBack(); - } - else - { - DockWindows[DockState.DockRight].BringToFront(); - } - } - else if (dockStyle == DockStyle.Top) - { - if (fullPanelEdge) - { - DockWindows[DockState.DockTop].SendToBack(); - } - else - { - DockWindows[DockState.DockTop].BringToFront(); - } - } - else if (dockStyle == DockStyle.Bottom) - { - if (fullPanelEdge) - { - DockWindows[DockState.DockBottom].SendToBack(); - } - else - { - DockWindows[DockState.DockBottom].BringToFront(); - } - } - } - - public IDockContent[] DocumentsToArray() - { - int count = DocumentsCount; - IDockContent[] documents = new IDockContent[count]; - int i = 0; - foreach (IDockContent content in Documents) - { - documents[i] = content; - i++; - } - - return documents; - } - - public void SetPaneIndex(DockPane pane, int index) - { - int oldIndex = Panes.IndexOf(pane); - if (oldIndex == -1) - { - throw new ArgumentException(Strings.DockPanel_SetPaneIndex_InvalidPane); - } - - if (index < 0 || index > Panes.Count - 1) - { - if (index != -1) - { - throw new ArgumentOutOfRangeException(Strings.DockPanel_SetPaneIndex_InvalidIndex); - } - } - - if (oldIndex == index) - { - return; - } - if (oldIndex == Panes.Count - 1 && index == -1) - { - return; - } - - Panes.Remove(pane); - if (index == -1) - { - Panes.Add(pane); - } - else if (oldIndex < index) - { - Panes.AddAt(pane, index - 1); - } - else - { - Panes.AddAt(pane, index); - } - } - - public void SuspendLayout(bool allWindows) - { - FocusManager.SuspendFocusTracking(); - SuspendLayout(); - if (allWindows) - { - SuspendMdiClientLayout(); - } - } - - public void ResumeLayout(bool performLayout, bool allWindows) - { - FocusManager.ResumeFocusTracking(); - ResumeLayout(performLayout); - if (allWindows) - { - ResumeMdiClientLayout(performLayout); - } - } - - #endregion - - #region Internals - - internal void ResetAutoHideStripControl() - { - if (m_autoHideStripControl != null) - { - m_autoHideStripControl.Dispose(); - } - - m_autoHideStripControl = null; - } - - internal Rectangle GetTabStripRectangle(DockState dockState) - { - return AutoHideStripControl.GetTabStripRectangle(dockState); - } - - internal void AddContent(IDockContent content) - { - if (content == null) - { - throw new ArgumentNullException(); - } - - if (!Contents.Contains(content)) - { - Contents.Add(content); - OnContentAdded(new DockContentEventArgs(content)); - } - } - - internal void AddPane(DockPane pane) - { - if (Panes.Contains(pane)) - { - return; - } - - Panes.Add(pane); - } - - internal void AddFloatWindow(FloatWindow floatWindow) - { - if (FloatWindows.Contains(floatWindow)) - { - return; - } - - FloatWindows.Add(floatWindow); - } - - internal void RemoveContent(IDockContent content) - { - if (content == null) - { - throw new ArgumentNullException(); - } - - if (Contents.Contains(content)) - { - Contents.Remove(content); - OnContentRemoved(new DockContentEventArgs(content)); - } - } - - internal void RemovePane(DockPane pane) - { - if (!Panes.Contains(pane)) - { - return; - } - - Panes.Remove(pane); - } - - internal void RemoveFloatWindow(FloatWindow floatWindow) - { - if (!FloatWindows.Contains(floatWindow)) - { - return; - } - - FloatWindows.Remove(floatWindow); - } - - #endregion - - #region Overrides - - protected override void Dispose(bool disposing) - { - lock (this) - { - if (!m_disposed && disposing) - { - m_focusManager.Dispose(); - if (m_mdiClientController != null) - { - m_mdiClientController.HandleAssigned -= new EventHandler(MdiClientHandleAssigned); - m_mdiClientController.MdiChildActivate -= new EventHandler(ParentFormMdiChildActivate); - m_mdiClientController.Layout -= new LayoutEventHandler(MdiClient_Layout); - m_mdiClientController.Dispose(); - } - FloatWindows.Dispose(); - Panes.Dispose(); - DummyContent.Dispose(); - - m_disposed = true; - } - - base.Dispose(disposing); - } - } - - protected override void OnRightToLeftChanged(EventArgs e) - { - base.OnRightToLeftChanged(e); - foreach (FloatWindow floatWindow in FloatWindows) - { - if (floatWindow.RightToLeft != RightToLeft) - { - floatWindow.RightToLeft = RightToLeft; - } - } - } - - protected override void OnLayout(LayoutEventArgs levent) - { - SuspendLayout(true); - - AutoHideStripControl.Bounds = ClientRectangle; - - CalculateDockPadding(); - - DockWindows[DockState.DockLeft].Width = GetDockWindowSize(DockState.DockLeft); - DockWindows[DockState.DockRight].Width = GetDockWindowSize(DockState.DockRight); - DockWindows[DockState.DockTop].Height = GetDockWindowSize(DockState.DockTop); - DockWindows[DockState.DockBottom].Height = GetDockWindowSize(DockState.DockBottom); - - AutoHideWindow.Bounds = GetAutoHideWindowBounds(AutoHideWindowRectangle); - - DockWindows[DockState.Document].BringToFront(); - AutoHideWindow.BringToFront(); - - base.OnLayout(levent); - - if (DocumentStyle == DocumentStyle.SystemMdi && MdiClientExists) - { - SetMdiClientBounds(SystemMdiClientBounds); - InvalidateWindowRegion(); - } - else if (DocumentStyle == DocumentStyle.DockingMdi) - { - InvalidateWindowRegion(); - } - - ResumeLayout(true, true); - } - - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - - if (DockBackColor == BackColor) - { - return; - } - - Graphics g = e.Graphics; - SolidBrush bgBrush = new SolidBrush(DockBackColor); - g.FillRectangle(bgBrush, ClientRectangle); - } - - protected override void OnParentChanged(EventArgs e) - { - SetAutoHideWindowParent(); - GetMdiClientController().ParentForm = this.Parent as Form; - base.OnParentChanged(e); - } - - protected override void OnVisibleChanged(EventArgs e) - { - base.OnVisibleChanged(e); - - if (Visible) - { - SetMdiClient(); - } - } - - #endregion - - #region Private Methods - - private bool ShouldSerializeDefaultFloatWindowSize() - { - return DefaultFloatWindowSize != new Size(300, 300); - } - - private int GetDockWindowSize(DockState dockState) - { - if (dockState == DockState.DockLeft || dockState == DockState.DockRight) - { - int width = ClientRectangle.Width - DockPadding.Left - DockPadding.Right; - int dockLeftSize = m_dockLeftPortion >= 1 ? (int)m_dockLeftPortion : (int)(width * m_dockLeftPortion); - int dockRightSize = m_dockRightPortion >= 1 - ? (int)m_dockRightPortion - : (int)(width * m_dockRightPortion); - - if (dockLeftSize < MeasurePane.MinSize) - { - dockLeftSize = MeasurePane.MinSize; - } - if (dockRightSize < MeasurePane.MinSize) - { - dockRightSize = MeasurePane.MinSize; - } - - if (dockLeftSize + dockRightSize > width - MeasurePane.MinSize) - { - int adjust = dockLeftSize + dockRightSize - (width - MeasurePane.MinSize); - dockLeftSize -= adjust / 2; - dockRightSize -= adjust / 2; - } - - return dockState == DockState.DockLeft ? dockLeftSize : dockRightSize; - } - else if (dockState == DockState.DockTop || dockState == DockState.DockBottom) - { - int height = ClientRectangle.Height - DockPadding.Top - DockPadding.Bottom; - int dockTopSize = m_dockTopPortion >= 1 ? (int)m_dockTopPortion : (int)(height * m_dockTopPortion); - int dockBottomSize = m_dockBottomPortion >= 1 - ? (int)m_dockBottomPortion - : (int)(height * m_dockBottomPortion); - - if (dockTopSize < MeasurePane.MinSize) - { - dockTopSize = MeasurePane.MinSize; - } - if (dockBottomSize < MeasurePane.MinSize) - { - dockBottomSize = MeasurePane.MinSize; - } - - if (dockTopSize + dockBottomSize > height - MeasurePane.MinSize) - { - int adjust = dockTopSize + dockBottomSize - (height - MeasurePane.MinSize); - dockTopSize -= adjust / 2; - dockBottomSize -= adjust / 2; - } - - return dockState == DockState.DockTop ? dockTopSize : dockBottomSize; - } - else - { - return 0; - } - } - - private void CalculateDockPadding() - { - DockPadding.All = 0; - - int height = AutoHideStripControl.MeasureHeight(); - - if (AutoHideStripControl.GetNumberOfPanes(DockState.DockLeftAutoHide) > 0) - { - DockPadding.Left = height; - } - if (AutoHideStripControl.GetNumberOfPanes(DockState.DockRightAutoHide) > 0) - { - DockPadding.Right = height; - } - if (AutoHideStripControl.GetNumberOfPanes(DockState.DockTopAutoHide) > 0) - { - DockPadding.Top = height; - } - if (AutoHideStripControl.GetNumberOfPanes(DockState.DockBottomAutoHide) > 0) - { - DockPadding.Bottom = height; - } - } - - private bool IsParentFormValid() - { - if (DocumentStyle == DocumentStyle.DockingSdi || DocumentStyle == DocumentStyle.DockingWindow) - { - return true; - } - - if (!MdiClientExists) - { - GetMdiClientController().RenewMdiClient(); - } - - return MdiClientExists; - } - - private void SetAutoHideWindowParent() - { - Control parent; - if (DocumentStyle == DocumentStyle.DockingMdi || - DocumentStyle == DocumentStyle.SystemMdi) - { - parent = this.Parent; - } - else - { - parent = this; - } - if (AutoHideWindow.Parent != parent) - { - AutoHideWindow.Parent = parent; - AutoHideWindow.BringToFront(); - } - } - - private void InvalidateWindowRegion() - { - if (DesignMode) - { - return; - } - - if (m_dummyControlPaintEventHandler == null) - { - m_dummyControlPaintEventHandler = new PaintEventHandler(DummyControl_Paint); - } - - DummyControl.Paint += m_dummyControlPaintEventHandler; - DummyControl.Invalidate(); - } - - private void UpdateWindowRegion() - { - if (this.DocumentStyle == DocumentStyle.DockingMdi) - { - UpdateWindowRegion_ClipContent(); - } - else if (this.DocumentStyle == DocumentStyle.DockingSdi || - this.DocumentStyle == DocumentStyle.DockingWindow) - { - UpdateWindowRegion_FullDocumentArea(); - } - else if (this.DocumentStyle == DocumentStyle.SystemMdi) - { - UpdateWindowRegion_EmptyDocumentArea(); - } - } - - private void UpdateWindowRegion_FullDocumentArea() - { - SetRegion(null); - } - - private void UpdateWindowRegion_EmptyDocumentArea() - { - Rectangle rect = DocumentWindowBounds; - SetRegion(new Rectangle[] { rect }); - } - - private void UpdateWindowRegion_ClipContent() - { - int count = 0; - foreach (DockPane pane in this.Panes) - { - if (!pane.Visible || pane.DockState != DockState.Document) - { - continue; - } - - count++; - } - - if (count == 0) - { - SetRegion(null); - return; - } - - Rectangle[] rects = new Rectangle[count]; - int i = 0; - foreach (DockPane pane in this.Panes) - { - if (!pane.Visible || pane.DockState != DockState.Document) - { - continue; - } - - rects[i] = RectangleToClient(pane.RectangleToScreen(pane.ContentRectangle)); - i++; - } - - SetRegion(rects); - } - - private void SetRegion(Rectangle[] clipRects) - { - if (!IsClipRectsChanged(clipRects)) - { - return; - } - - m_clipRects = clipRects; - - if (m_clipRects == null || m_clipRects.GetLength(0) == 0) - { - Region = null; - } - else - { - Region region = new Region(new Rectangle(0, 0, this.Width, this.Height)); - foreach (Rectangle rect in m_clipRects) - { - region.Exclude(rect); - } - Region = region; - } - } - - private bool IsClipRectsChanged(Rectangle[] clipRects) - { - if (clipRects == null && m_clipRects == null) - { - return false; - } - else if (clipRects == null != (m_clipRects == null)) - { - return true; - } - - foreach (Rectangle rect in clipRects) - { - bool matched = false; - foreach (Rectangle rect2 in m_clipRects) - { - if (rect == rect2) - { - matched = true; - break; - } - } - if (!matched) - { - return true; - } - } - - foreach (Rectangle rect2 in m_clipRects) - { - bool matched = false; - foreach (Rectangle rect in clipRects) - { - if (rect == rect2) - { - matched = true; - break; - } - } - if (!matched) - { - return true; - } - } - return false; - } - - #endregion - - #region Events handler - - private void MdiClientHandleAssigned(object sender, EventArgs e) - { - SetMdiClient(); - PerformLayout(); - } - - private void MdiClient_Layout(object sender, LayoutEventArgs e) - { - if (DocumentStyle != DocumentStyle.DockingMdi) - { - return; - } - - foreach (DockPane pane in Panes) - { - if (pane.DockState == DockState.Document) - { - pane.SetContentBounds(); - } - } - - InvalidateWindowRegion(); - } - - private void DummyControl_Paint(object sender, PaintEventArgs e) - { - DummyControl.Paint -= m_dummyControlPaintEventHandler; - UpdateWindowRegion(); - } - - #endregion - - protected virtual void OnContentAdded(DockContentEventArgs e) - { - ((EventHandler)Events[ContentAddedEvent])?.Invoke(this, e); - } - - protected virtual void OnContentRemoved(DockContentEventArgs e) - { - ((EventHandler)Events[ContentRemovedEvent])?.Invoke(this, e); - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanelExtender.cs b/src/WinFormsUI/Docking/DockPanelExtender.cs deleted file mode 100644 index ddda208e..00000000 --- a/src/WinFormsUI/Docking/DockPanelExtender.cs +++ /dev/null @@ -1,315 +0,0 @@ -using System; -using System.Drawing; -using System.Diagnostics.CodeAnalysis; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public sealed class DockPanelExtender - { - #region Fields - - private IAutoHideStripFactory m_autoHideStripFactory = null; - - private IDockPaneCaptionFactory m_dockPaneCaptionFactory = null; - - private IDockPaneFactory m_dockPaneFactory = null; - - private IDockPaneStripFactory m_dockPaneStripFactory = null; - - private IFloatWindowFactory m_floatWindowFactory = null; - - #endregion - - #region cTor - - internal DockPanelExtender(DockPanel dockPanel) - { - DockPanel = dockPanel; - } - - #endregion - - #region Properties - - private DockPanel DockPanel { get; } - - public IDockPaneFactory DockPaneFactory - { - get - { - if (m_dockPaneFactory == null) - { - m_dockPaneFactory = new DefaultDockPaneFactory(); - } - - return m_dockPaneFactory; - } - set - { - if (DockPanel.Panes.Count > 0) - { - throw new InvalidOperationException(); - } - - m_dockPaneFactory = value; - } - } - - public IFloatWindowFactory FloatWindowFactory - { - get - { - if (m_floatWindowFactory == null) - { - m_floatWindowFactory = new DefaultFloatWindowFactory(); - } - - return m_floatWindowFactory; - } - set - { - if (DockPanel.FloatWindows.Count > 0) - { - throw new InvalidOperationException(); - } - - m_floatWindowFactory = value; - } - } - - public IDockPaneCaptionFactory DockPaneCaptionFactory - { - get - { - if (m_dockPaneCaptionFactory == null) - { - m_dockPaneCaptionFactory = new DefaultDockPaneCaptionFactory(); - } - - return m_dockPaneCaptionFactory; - } - set - { - if (DockPanel.Panes.Count > 0) - { - throw new InvalidOperationException(); - } - - m_dockPaneCaptionFactory = value; - } - } - - public IDockPaneStripFactory DockPaneStripFactory - { - get - { - if (m_dockPaneStripFactory == null) - { - m_dockPaneStripFactory = new DefaultDockPaneStripFactory(); - } - - return m_dockPaneStripFactory; - } - set - { - if (DockPanel.Contents.Count > 0) - { - throw new InvalidOperationException(); - } - - m_dockPaneStripFactory = value; - } - } - - public IAutoHideStripFactory AutoHideStripFactory - { - get - { - if (m_autoHideStripFactory == null) - { - m_autoHideStripFactory = new DefaultAutoHideStripFactory(); - } - - return m_autoHideStripFactory; - } - set - { - if (DockPanel.Contents.Count > 0) - { - throw new InvalidOperationException(); - } - - if (m_autoHideStripFactory == value) - { - return; - } - - m_autoHideStripFactory = value; - DockPanel.ResetAutoHideStripControl(); - } - } - - #endregion - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public interface IDockPaneFactory - { - #region Public methods - - DockPane CreateDockPane(IDockContent content, DockState visibleState, bool show); - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] - DockPane CreateDockPane(IDockContent content, FloatWindow floatWindow, bool show); - - DockPane CreateDockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, - double proportion, bool show); - - [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] - DockPane CreateDockPane(IDockContent content, Rectangle floatWindowBounds, bool show); - - #endregion - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public interface IFloatWindowFactory - { - #region Public methods - - FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane); - FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds); - - #endregion - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public interface IDockPaneCaptionFactory - { - #region Public methods - - DockPaneCaptionBase CreateDockPaneCaption(DockPane pane); - - #endregion - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public interface IDockPaneStripFactory - { - #region Public methods - - DockPaneStripBase CreateDockPaneStrip(DockPane pane); - - #endregion - } - - [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] - public interface IAutoHideStripFactory - { - #region Public methods - - AutoHideStripBase CreateAutoHideStrip(DockPanel panel); - - #endregion - } - - #region DefaultDockPaneFactory - - private class DefaultDockPaneFactory : IDockPaneFactory - { - #region Public methods - - public DockPane CreateDockPane(IDockContent content, DockState visibleState, bool show) - { - return new DockPane(content, visibleState, show); - } - - public DockPane CreateDockPane(IDockContent content, FloatWindow floatWindow, bool show) - { - return new DockPane(content, floatWindow, show); - } - - public DockPane CreateDockPane(IDockContent content, DockPane prevPane, DockAlignment alignment, - double proportion, bool show) - { - return new DockPane(content, prevPane, alignment, proportion, show); - } - - public DockPane CreateDockPane(IDockContent content, Rectangle floatWindowBounds, bool show) - { - return new DockPane(content, floatWindowBounds, show); - } - - #endregion - } - - #endregion - - #region DefaultFloatWindowFactory - - private class DefaultFloatWindowFactory : IFloatWindowFactory - { - #region Public methods - - public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane) - { - return new FloatWindow(dockPanel, pane); - } - - public FloatWindow CreateFloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds) - { - return new FloatWindow(dockPanel, pane, bounds); - } - - #endregion - } - - #endregion - - #region DefaultDockPaneCaptionFactory - - private class DefaultDockPaneCaptionFactory : IDockPaneCaptionFactory - { - #region Public methods - - public DockPaneCaptionBase CreateDockPaneCaption(DockPane pane) - { - return new VS2005DockPaneCaption(pane); - } - - #endregion - } - - #endregion - - #region DefaultDockPaneTabStripFactory - - private class DefaultDockPaneStripFactory : IDockPaneStripFactory - { - #region Public methods - - public DockPaneStripBase CreateDockPaneStrip(DockPane pane) - { - return new VS2005DockPaneStrip(pane); - } - - #endregion - } - - #endregion - - #region DefaultAutoHideStripFactory - - private class DefaultAutoHideStripFactory : IAutoHideStripFactory - { - #region Public methods - - public AutoHideStripBase CreateAutoHideStrip(DockPanel panel) - { - return new VS2005AutoHideStrip(panel); - } - - #endregion - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockPanelSkin.cs b/src/WinFormsUI/Docking/DockPanelSkin.cs deleted file mode 100644 index 1ab2758e..00000000 --- a/src/WinFormsUI/Docking/DockPanelSkin.cs +++ /dev/null @@ -1,482 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Design; -using System.Windows.Forms.Design; -using System.ComponentModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - #region DockPanelSkin classes - - /// - /// The skin to use when displaying the DockPanel. - /// The skin allows custom gradient color schemes to be used when drawing the - /// DockStrips and Tabs. - /// - [TypeConverter(typeof(DockPanelSkinConverter))] - public class DockPanelSkin - { - #region Fields - - #endregion - - #region cTor - - public DockPanelSkin() - { - AutoHideStripSkin = new AutoHideStripSkin(); - DockPaneStripSkin = new DockPaneStripSkin(); - } - - #endregion - - #region Properties - - /// - /// The skin used to display the auto hide strips and tabs. - /// - public AutoHideStripSkin AutoHideStripSkin { get; set; } - - /// - /// The skin used to display the Document and ToolWindow style DockStrips and Tabs. - /// - public DockPaneStripSkin DockPaneStripSkin { get; set; } - - #endregion - } - - /// - /// The skin used to display the auto hide strip and tabs. - /// - [TypeConverter(typeof(AutoHideStripConverter))] - public class AutoHideStripSkin - { - #region Fields - - #endregion - - #region cTor - - public AutoHideStripSkin() - { - DockStripGradient = new DockPanelGradient(); - DockStripGradient.StartColor = SystemColors.ControlLight; - DockStripGradient.EndColor = SystemColors.ControlLight; - - TabGradient = new TabGradient(); - TabGradient.TextColor = SystemColors.ControlDarkDark; - - TextFont = SystemFonts.MenuFont; - } - - #endregion - - #region Properties - - /// - /// The gradient color skin for the DockStrips. - /// - public DockPanelGradient DockStripGradient { get; set; } - - /// - /// The gradient color skin for the Tabs. - /// - public TabGradient TabGradient { get; set; } - - /// - /// Font used in AutoHideStrip elements. - /// - public Font TextFont { get; set; } - - #endregion - } - - /// - /// The skin used to display the document and tool strips and tabs. - /// - [TypeConverter(typeof(DockPaneStripConverter))] - public class DockPaneStripSkin - { - #region Fields - - #endregion - - #region cTor - - public DockPaneStripSkin() - { - DocumentGradient = new DockPaneStripGradient(); - DocumentGradient.DockStripGradient.StartColor = SystemColors.Control; - DocumentGradient.DockStripGradient.EndColor = SystemColors.Control; - DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight; - DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight; - DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight; - DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight; - - ToolWindowGradient = new DockPaneStripToolWindowGradient(); - ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight; - ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight; - - ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control; - ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control; - - ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent; - ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent; - ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark; - - ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption; - ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption; - ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; - ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText; - - ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption; - ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.InactiveCaption; - ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical; - ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.InactiveCaptionText; - - TextFont = SystemFonts.MenuFont; - } - - #endregion - - #region Properties - - /// - /// The skin used to display the Document style DockPane strip and tab. - /// - public DockPaneStripGradient DocumentGradient { get; set; } - - /// - /// The skin used to display the ToolWindow style DockPane strip and tab. - /// - public DockPaneStripToolWindowGradient ToolWindowGradient { get; set; } - - /// - /// Font used in DockPaneStrip elements. - /// - public Font TextFont { get; set; } - - #endregion - } - - /// - /// The skin used to display the DockPane ToolWindow strip and tab. - /// - [TypeConverter(typeof(DockPaneStripGradientConverter))] - public class DockPaneStripToolWindowGradient : DockPaneStripGradient - { - #region Fields - - #endregion - - #region cTor - - public DockPaneStripToolWindowGradient() - { - ActiveCaptionGradient = new TabGradient(); - InactiveCaptionGradient = new TabGradient(); - } - - #endregion - - #region Properties - - /// - /// The skin used to display the active ToolWindow caption. - /// - public TabGradient ActiveCaptionGradient { get; set; } - - /// - /// The skin used to display the inactive ToolWindow caption. - /// - public TabGradient InactiveCaptionGradient { get; set; } - - #endregion - } - - /// - /// The skin used to display the DockPane strip and tab. - /// - [TypeConverter(typeof(DockPaneStripGradientConverter))] - public class DockPaneStripGradient - { - #region Fields - - #endregion - - #region cTor - - public DockPaneStripGradient() - { - DockStripGradient = new DockPanelGradient(); - ActiveTabGradient = new TabGradient(); - InactiveTabGradient = new TabGradient(); - } - - #endregion - - #region Properties - - /// - /// The gradient color skin for the DockStrip. - /// - public DockPanelGradient DockStripGradient { get; set; } - - /// - /// The skin used to display the active DockPane tabs. - /// - public TabGradient ActiveTabGradient { get; set; } - - /// - /// The skin used to display the inactive DockPane tabs. - /// - public TabGradient InactiveTabGradient { get; set; } - - #endregion - } - - /// - /// The skin used to display the dock pane tab - /// - [TypeConverter(typeof(DockPaneTabGradientConverter))] - public class TabGradient : DockPanelGradient - { - #region Fields - - #endregion - - #region cTor - - public TabGradient() - { - TextColor = SystemColors.ControlText; - } - - #endregion - - #region Properties - - /// - /// The text color. - /// - [DefaultValue(typeof(SystemColors), "ControlText")] - public Color TextColor { get; set; } - - #endregion - } - - /// - /// The gradient color skin. - /// - [TypeConverter(typeof(DockPanelGradientConverter))] - public class DockPanelGradient - { - #region Fields - - #endregion - - #region cTor - - public DockPanelGradient() - { - StartColor = SystemColors.Control; - EndColor = SystemColors.Control; - LinearGradientMode = LinearGradientMode.Horizontal; - } - - #endregion - - #region Properties - - /// - /// The beginning gradient color. - /// - [DefaultValue(typeof(SystemColors), "Control")] - public Color StartColor { get; set; } - - /// - /// The ending gradient color. - /// - [DefaultValue(typeof(SystemColors), "Control")] - public Color EndColor { get; set; } - - /// - /// The gradient mode to display the colors. - /// - [DefaultValue(LinearGradientMode.Horizontal)] - public LinearGradientMode LinearGradientMode { get; set; } - - #endregion - } - - #endregion - - #region Converters - - public class DockPanelSkinConverter : ExpandableObjectConverter - { - #region Public methods - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(DockPanelSkin)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, - object value, Type destinationType) - { - if (destinationType == typeof(string) && value is DockPanelSkin) - { - return "DockPanelSkin"; - } - return base.ConvertTo(context, culture, value, destinationType); - } - - #endregion - } - - public class DockPanelGradientConverter : ExpandableObjectConverter - { - #region Public methods - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(DockPanelGradient)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, - object value, Type destinationType) - { - if (destinationType == typeof(string) && value is DockPanelGradient) - { - return "DockPanelGradient"; - } - return base.ConvertTo(context, culture, value, destinationType); - } - - #endregion - } - - public class AutoHideStripConverter : ExpandableObjectConverter - { - #region Public methods - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(AutoHideStripSkin)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, - object value, Type destinationType) - { - if (destinationType == typeof(string) && value is AutoHideStripSkin) - { - return "AutoHideStripSkin"; - } - return base.ConvertTo(context, culture, value, destinationType); - } - - #endregion - } - - public class DockPaneStripConverter : ExpandableObjectConverter - { - #region Public methods - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(DockPaneStripSkin)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, - object value, Type destinationType) - { - if (destinationType == typeof(string) && value is DockPaneStripSkin) - { - return "DockPaneStripSkin"; - } - return base.ConvertTo(context, culture, value, destinationType); - } - - #endregion - } - - public class DockPaneStripGradientConverter : ExpandableObjectConverter - { - #region Public methods - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(DockPaneStripGradient)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, - object value, Type destinationType) - { - if (destinationType == typeof(string) && value is DockPaneStripGradient) - { - return "DockPaneStripGradient"; - } - return base.ConvertTo(context, culture, value, destinationType); - } - - #endregion - } - - public class DockPaneTabGradientConverter : ExpandableObjectConverter - { - #region Public methods - - public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) - { - if (destinationType == typeof(TabGradient)) - { - return true; - } - - return base.CanConvertTo(context, destinationType); - } - - public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, - object value, Type destinationType) - { - if (destinationType == typeof(string) && value is TabGradient) - { - return "DockPaneTabGradient"; - } - return base.ConvertTo(context, culture, value, destinationType); - } - - #endregion - } - - #endregion -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockWindow.SplitterControl.cs b/src/WinFormsUI/Docking/DockWindow.SplitterControl.cs deleted file mode 100644 index 5e8f761d..00000000 --- a/src/WinFormsUI/Docking/DockWindow.SplitterControl.cs +++ /dev/null @@ -1,38 +0,0 @@ -using System; -using System.Collections; -using System.ComponentModel; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public partial class DockWindow - { - private class SplitterControl : SplitterBase - { - #region Properties - - protected override int SplitterSize - { - get { return Measures.SplitterSize; } - } - - #endregion - - #region Overrides - - protected override void StartDrag() - { - DockWindow window = Parent as DockWindow; - if (window == null) - { - return; - } - - window.DockPanel.BeginDrag(window, window.RectangleToScreen(Bounds)); - } - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockWindow.cs b/src/WinFormsUI/Docking/DockWindow.cs deleted file mode 100644 index a5133b6f..00000000 --- a/src/WinFormsUI/Docking/DockWindow.cs +++ /dev/null @@ -1,283 +0,0 @@ -using System; -using System.Windows.Forms; -using System.Drawing; -using System.Runtime.InteropServices; -using System.ComponentModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - [ToolboxItem(false)] - public partial class DockWindow : Panel, INestedPanesContainer, ISplitterDragSource - { - #region Fields - - private readonly SplitterControl m_splitter; - - #endregion - - #region cTor - - internal DockWindow(DockPanel dockPanel, DockState dockState) - { - NestedPanes = new NestedPaneCollection(this); - DockPanel = dockPanel; - DockState = dockState; - Visible = false; - - SuspendLayout(); - - if (DockState == DockState.DockLeft || DockState == DockState.DockRight || - DockState == DockState.DockTop || DockState == DockState.DockBottom) - { - m_splitter = new SplitterControl(); - Controls.Add(m_splitter); - } - - if (DockState == DockState.DockLeft) - { - Dock = DockStyle.Left; - m_splitter.Dock = DockStyle.Right; - } - else if (DockState == DockState.DockRight) - { - Dock = DockStyle.Right; - m_splitter.Dock = DockStyle.Left; - } - else if (DockState == DockState.DockTop) - { - Dock = DockStyle.Top; - m_splitter.Dock = DockStyle.Bottom; - } - else if (DockState == DockState.DockBottom) - { - Dock = DockStyle.Bottom; - m_splitter.Dock = DockStyle.Top; - } - else if (DockState == DockState.Document) - { - Dock = DockStyle.Fill; - } - - ResumeLayout(); - } - - #endregion - - #region Properties - - public VisibleNestedPaneCollection VisibleNestedPanes - { - get { return NestedPanes.VisibleNestedPanes; } - } - - public NestedPaneCollection NestedPanes { get; } - - public DockPanel DockPanel { get; } - - public DockState DockState { get; } - - public bool IsFloat - { - get { return DockState == DockState.Float; } - } - - internal DockPane DefaultPane - { - get { return VisibleNestedPanes.Count == 0 ? null : VisibleNestedPanes[0]; } - } - - public virtual Rectangle DisplayingRectangle - { - get - { - Rectangle rect = ClientRectangle; - // if DockWindow is document, exclude the border - if (DockState == DockState.Document) - { - rect.X += 1; - rect.Y += 1; - rect.Width -= 2; - rect.Height -= 2; - } - // exclude the splitter - else if (DockState == DockState.DockLeft) - { - rect.Width -= Measures.SplitterSize; - } - else if (DockState == DockState.DockRight) - { - rect.X += Measures.SplitterSize; - rect.Width -= Measures.SplitterSize; - } - else if (DockState == DockState.DockTop) - { - rect.Height -= Measures.SplitterSize; - } - else if (DockState == DockState.DockBottom) - { - rect.Y += Measures.SplitterSize; - rect.Height -= Measures.SplitterSize; - } - - return rect; - } - } - - #endregion - - #region Overrides - - protected override void OnPaint(PaintEventArgs e) - { - // if DockWindow is document, draw the border - if (DockState == DockState.Document) - { - e.Graphics.DrawRectangle(SystemPens.ControlDark, ClientRectangle.X, ClientRectangle.Y, - ClientRectangle.Width - 1, ClientRectangle.Height - 1); - } - - base.OnPaint(e); - } - - protected override void OnLayout(LayoutEventArgs levent) - { - VisibleNestedPanes.Refresh(); - if (VisibleNestedPanes.Count == 0) - { - if (Visible) - { - Visible = false; - } - } - else if (!Visible) - { - Visible = true; - VisibleNestedPanes.Refresh(); - } - - base.OnLayout(levent); - } - - #endregion - - #region ISplitterDragSource Members - - void ISplitterDragSource.BeginDrag(Rectangle rectSplitter) - { - } - - void ISplitterDragSource.EndDrag() - { - } - - bool ISplitterDragSource.IsVertical - { - get { return DockState == DockState.DockLeft || DockState == DockState.DockRight; } - } - - Rectangle ISplitterDragSource.DragLimitBounds - { - get - { - Rectangle rectLimit = DockPanel.DockArea; - Point location; - if ((Control.ModifierKeys & Keys.Shift) == 0) - { - location = Location; - } - else - { - location = DockPanel.DockArea.Location; - } - - if (((ISplitterDragSource) this).IsVertical) - { - rectLimit.X += MeasurePane.MinSize; - rectLimit.Width -= 2 * MeasurePane.MinSize; - rectLimit.Y = location.Y; - if ((Control.ModifierKeys & Keys.Shift) == 0) - { - rectLimit.Height = Height; - } - } - else - { - rectLimit.Y += MeasurePane.MinSize; - rectLimit.Height -= 2 * MeasurePane.MinSize; - rectLimit.X = location.X; - if ((Control.ModifierKeys & Keys.Shift) == 0) - { - rectLimit.Width = Width; - } - } - - return DockPanel.RectangleToScreen(rectLimit); - } - } - - void ISplitterDragSource.MoveSplitter(int offset) - { - if ((Control.ModifierKeys & Keys.Shift) != 0) - { - SendToBack(); - } - - Rectangle rectDockArea = DockPanel.DockArea; - if (DockState == DockState.DockLeft && rectDockArea.Width > 0) - { - if (DockPanel.DockLeftPortion > 1) - { - DockPanel.DockLeftPortion = Width + offset; - } - else - { - DockPanel.DockLeftPortion += (double) offset / (double) rectDockArea.Width; - } - } - else if (DockState == DockState.DockRight && rectDockArea.Width > 0) - { - if (DockPanel.DockRightPortion > 1) - { - DockPanel.DockRightPortion = Width - offset; - } - else - { - DockPanel.DockRightPortion -= (double) offset / (double) rectDockArea.Width; - } - } - else if (DockState == DockState.DockBottom && rectDockArea.Height > 0) - { - if (DockPanel.DockBottomPortion > 1) - { - DockPanel.DockBottomPortion = Height - offset; - } - else - { - DockPanel.DockBottomPortion -= (double) offset / (double) rectDockArea.Height; - } - } - else if (DockState == DockState.DockTop && rectDockArea.Height > 0) - { - if (DockPanel.DockTopPortion > 1) - { - DockPanel.DockTopPortion = Height + offset; - } - else - { - DockPanel.DockTopPortion += (double) offset / (double) rectDockArea.Height; - } - } - } - - #region IDragSource Members - - Control IDragSource.DragControl - { - get { return this; } - } - - #endregion - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DockWindowCollection.cs b/src/WinFormsUI/Docking/DockWindowCollection.cs deleted file mode 100644 index 0c0af785..00000000 --- a/src/WinFormsUI/Docking/DockWindowCollection.cs +++ /dev/null @@ -1,56 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public class DockWindowCollection : ReadOnlyCollection - { - #region cTor - - internal DockWindowCollection(DockPanel dockPanel) - : base(new List()) - { - Items.Add(new DockWindow(dockPanel, DockState.Document)); - Items.Add(new DockWindow(dockPanel, DockState.DockLeft)); - Items.Add(new DockWindow(dockPanel, DockState.DockRight)); - Items.Add(new DockWindow(dockPanel, DockState.DockTop)); - Items.Add(new DockWindow(dockPanel, DockState.DockBottom)); - } - - #endregion - - #region Properties - - public DockWindow this[DockState dockState] - { - get - { - if (dockState == DockState.Document) - { - return Items[0]; - } - else if (dockState == DockState.DockLeft || dockState == DockState.DockLeftAutoHide) - { - return Items[1]; - } - else if (dockState == DockState.DockRight || dockState == DockState.DockRightAutoHide) - { - return Items[2]; - } - else if (dockState == DockState.DockTop || dockState == DockState.DockTopAutoHide) - { - return Items[3]; - } - else if (dockState == DockState.DockBottom || dockState == DockState.DockBottomAutoHide) - { - return Items[4]; - } - - throw new ArgumentOutOfRangeException(); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DragForm.cs b/src/WinFormsUI/Docking/DragForm.cs deleted file mode 100644 index f250e21c..00000000 --- a/src/WinFormsUI/Docking/DragForm.cs +++ /dev/null @@ -1,84 +0,0 @@ -using System; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - // Inspired by Chris Sano's article: - // http://msdn.microsoft.com/smartclient/default.aspx?pull=/library/en-us/dnwinforms/html/colorpicker.asp - // In Sano's article, the DragForm needs to meet the following criteria: - // (1) it was not to show up in the task bar; - // ShowInTaskBar = false - // (2) it needed to be the top-most window; - // TopMost = true (not necessary here) - // (3) its icon could not show up in the ALT+TAB window if the user pressed ALT+TAB during a drag-and-drop; - // FormBorderStyle = FormBorderStyle.None; - // Create with WS_EX_TOOLWINDOW window style. - // Compares with the solution in the artile by setting FormBorderStyle as FixedToolWindow, - // and then clip the window caption and border, this way is much simplier. - // (4) it was not to steal focus from the application when displayed. - // User Win32 ShowWindow API with SW_SHOWNOACTIVATE - // In addition, this form should only for display and therefore should act as transparent, otherwise - // WindowFromPoint will return this form, instead of the control beneath. Need BOTH of the following to - // achieve this (don't know why, spent hours to try it out :( ): - // 1. Enabled = false; - // 2. WM_NCHITTEST returns HTTRANSPARENT - internal class DragForm : Form - { - #region cTor - - public DragForm() - { - FormBorderStyle = FormBorderStyle.None; - ShowInTaskbar = false; - SetStyle(ControlStyles.Selectable, false); - Enabled = false; - } - - #endregion - - #region Properties - - protected override CreateParams CreateParams - { - get - { - CreateParams createParams = base.CreateParams; - createParams.ExStyle |= (int) Win32.WindowExStyles.WS_EX_TOOLWINDOW; - return createParams; - } - } - - #endregion - - #region Public methods - - public virtual void Show(bool bActivate) - { - if (bActivate) - { - Show(); - } - else - { - NativeMethods.ShowWindow(Handle, (int) Win32.ShowWindowStyles.SW_SHOWNOACTIVATE); - } - } - - #endregion - - #region Overrides - - protected override void WndProc(ref Message m) - { - if (m.Msg == (int) Win32.Msgs.WM_NCHITTEST) - { - m.Result = (IntPtr) Win32.HitTest.HTTRANSPARENT; - return; - } - - base.WndProc(ref m); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/DummyControl.cs b/src/WinFormsUI/Docking/DummyControl.cs deleted file mode 100644 index 7933d0ca..00000000 --- a/src/WinFormsUI/Docking/DummyControl.cs +++ /dev/null @@ -1,17 +0,0 @@ -using System; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal class DummyControl : Control - { - #region cTor - - public DummyControl() - { - SetStyle(ControlStyles.Selectable, false); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Enums.cs b/src/WinFormsUI/Docking/Enums.cs deleted file mode 100644 index 4a748031..00000000 --- a/src/WinFormsUI/Docking/Enums.cs +++ /dev/null @@ -1,60 +0,0 @@ -using System; -using System.ComponentModel; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - [Flags] - [Serializable] - [Editor(typeof(DockAreasEditor), typeof(System.Drawing.Design.UITypeEditor))] - public enum DockAreas - { - Float = 1, - DockLeft = 2, - DockRight = 4, - DockTop = 8, - DockBottom = 16, - Document = 32 - } - - public enum DockState - { - Unknown = 0, - Float = 1, - DockTopAutoHide = 2, - DockLeftAutoHide = 3, - DockBottomAutoHide = 4, - DockRightAutoHide = 5, - Document = 6, - DockTop = 7, - DockLeft = 8, - DockBottom = 9, - DockRight = 10, - Hidden = 11 - } - - public enum DockAlignment - { - Left, - Right, - Top, - Bottom - } - - public enum DocumentStyle - { - DockingMdi, - DockingWindow, - DockingSdi, - SystemMdi, - } - - /// - /// The location to draw the DockPaneStrip for Document style windows. - /// - public enum DocumentTabStripLocation - { - Top, - Bottom - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/FloatWindow.cs b/src/WinFormsUI/Docking/FloatWindow.cs deleted file mode 100644 index e341137a..00000000 --- a/src/WinFormsUI/Docking/FloatWindow.cs +++ /dev/null @@ -1,551 +0,0 @@ -using System; -using System.Diagnostics.CodeAnalysis; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public class FloatWindow : Form, INestedPanesContainer, IDockDragSource - { - #region Fields - - internal const int WM_CHECKDISPOSE = (int) (Win32.Msgs.WM_USER + 1); - - #endregion - - #region cTor - - internal protected FloatWindow(DockPanel dockPanel, DockPane pane) - { - InternalConstruct(dockPanel, pane, false, Rectangle.Empty); - } - - internal protected FloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds) - { - InternalConstruct(dockPanel, pane, true, bounds); - } - - #endregion - - #region Properties - - public bool AllowEndUserDocking { get; set; } = true; - - public NestedPaneCollection NestedPanes { get; private set; } - - public VisibleNestedPaneCollection VisibleNestedPanes - { - get { return NestedPanes.VisibleNestedPanes; } - } - - public DockPanel DockPanel { get; private set; } - - public DockState DockState - { - get { return DockState.Float; } - } - - public bool IsFloat - { - get { return DockState == DockState.Float; } - } - - public virtual Rectangle DisplayingRectangle - { - get { return ClientRectangle; } - } - - #endregion - - #region Internals - - internal bool IsDockStateValid(DockState dockState) - { - foreach (DockPane pane in NestedPanes) - foreach (IDockContent content in pane.Contents) - { - if (!DockHelper.IsDockStateValid(dockState, content.DockHandler.DockAreas)) - { - return false; - } - } - - return true; - } - - - [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = - "System.Windows.Forms.Control.set_Text(System.String)")] - internal void SetText() - { - DockPane theOnlyPane = VisibleNestedPanes.Count == 1 ? VisibleNestedPanes[0] : null; - - if (theOnlyPane == null) - { - Text = " "; // use " " instead of string.Empty because the whole title bar will disappear when ControlBox is set to false. - } - else if (theOnlyPane.ActiveContent == null) - { - Text = " "; - } - else - { - Text = theOnlyPane.ActiveContent.DockHandler.TabText; - } - } - - internal void RefreshChanges() - { - if (IsDisposed) - { - return; - } - - if (VisibleNestedPanes.Count == 0) - { - ControlBox = true; - return; - } - - for (int i = VisibleNestedPanes.Count - 1; i >= 0; i--) - { - DockContentCollection contents = VisibleNestedPanes[i].Contents; - for (int j = contents.Count - 1; j >= 0; j--) - { - IDockContent content = contents[j]; - if (content.DockHandler.DockState != DockState.Float) - { - continue; - } - - if (content.DockHandler.CloseButton && content.DockHandler.CloseButtonVisible) - { - ControlBox = true; - return; - } - } - } - //Only if there is a ControlBox do we turn it off - //old code caused a flash of the window. - if (ControlBox) - { - ControlBox = false; - } - } - - internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) - { - if (VisibleNestedPanes.Count == 1) - { - DockPane pane = VisibleNestedPanes[0]; - if (!dragSource.CanDockTo(pane)) - { - return; - } - - Point ptMouse = Control.MousePosition; - uint lParam = Win32Helper.MakeLong(ptMouse.X, ptMouse.Y); - if (NativeMethods.SendMessage(Handle, (int) Win32.Msgs.WM_NCHITTEST, 0, lParam) == - (uint) Win32.HitTest.HTCAPTION) - { - dockOutline.Show(VisibleNestedPanes[0], -1); - } - } - } - - #endregion - - #region Overrides - - protected override void Dispose(bool disposing) - { - if (disposing) - { - if (DockPanel != null) - { - DockPanel.RemoveFloatWindow(this); - } - DockPanel = null; - } - base.Dispose(disposing); - } - - protected override void OnActivated(EventArgs e) - { - DockPanel.FloatWindows.BringWindowToFront(this); - base.OnActivated(e); - // Propagate the Activated event to the visible panes content objects - foreach (DockPane pane in VisibleNestedPanes) - foreach (IDockContent content in pane.Contents) - { - content.OnActivated(e); - } - } - - protected override void OnDeactivate(EventArgs e) - { - base.OnDeactivate(e); - // Propagate the Deactivate event to the visible panes content objects - foreach (DockPane pane in VisibleNestedPanes) - foreach (IDockContent content in pane.Contents) - { - content.OnDeactivate(e); - } - } - - protected override void OnLayout(LayoutEventArgs levent) - { - VisibleNestedPanes.Refresh(); - RefreshChanges(); - Visible = VisibleNestedPanes.Count > 0; - SetText(); - - base.OnLayout(levent); - } - - protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) - { - Rectangle rectWorkArea = SystemInformation.VirtualScreen; - - if (y + height > rectWorkArea.Bottom) - { - y -= y + height - rectWorkArea.Bottom; - } - - if (y < rectWorkArea.Top) - { - y += rectWorkArea.Top - y; - } - - base.SetBoundsCore(x, y, width, height, specified); - } - - protected override void WndProc(ref Message m) - { - if (m.Msg == (int) Win32.Msgs.WM_NCLBUTTONDOWN) - { - if (IsDisposed) - { - return; - } - - uint result = NativeMethods.SendMessage(this.Handle, (int) Win32.Msgs.WM_NCHITTEST, 0, (uint) m.LParam); - if (result == 2 && DockPanel.AllowEndUserDocking && this.AllowEndUserDocking) // HITTEST_CAPTION - { - Activate(); - DockPanel.BeginDrag(this); - } - else - { - base.WndProc(ref m); - } - - return; - } - else if (m.Msg == (int) Win32.Msgs.WM_NCRBUTTONDOWN) - { - uint result = NativeMethods.SendMessage(this.Handle, (int) Win32.Msgs.WM_NCHITTEST, 0, (uint) m.LParam); - if (result == 2) // HITTEST_CAPTION - { - DockPane theOnlyPane = VisibleNestedPanes.Count == 1 ? VisibleNestedPanes[0] : null; - if (theOnlyPane != null && theOnlyPane.ActiveContent != null) - { - theOnlyPane.ShowTabPageContextMenu(this, PointToClient(Control.MousePosition)); - return; - } - } - - base.WndProc(ref m); - return; - } - else if (m.Msg == (int) Win32.Msgs.WM_CLOSE) - { - if (NestedPanes.Count == 0) - { - base.WndProc(ref m); - return; - } - - for (int i = NestedPanes.Count - 1; i >= 0; i--) - { - DockContentCollection contents = NestedPanes[i].Contents; - for (int j = contents.Count - 1; j >= 0; j--) - { - IDockContent content = contents[j]; - if (content.DockHandler.DockState != DockState.Float) - { - continue; - } - - if (!content.DockHandler.CloseButton) - { - continue; - } - - if (content.DockHandler.HideOnClose) - { - content.DockHandler.Hide(); - } - else - { - content.DockHandler.Close(); - } - } - } - - return; - } - else if (m.Msg == (int) Win32.Msgs.WM_NCLBUTTONDBLCLK) - { - uint result = NativeMethods.SendMessage(this.Handle, (int) Win32.Msgs.WM_NCHITTEST, 0, (uint) m.LParam); - if (result != 2) // HITTEST_CAPTION - { - base.WndProc(ref m); - return; - } - - DockPanel.SuspendLayout(true); - - // Restore to panel - foreach (DockPane pane in NestedPanes) - { - if (pane.DockState != DockState.Float) - { - continue; - } - pane.RestoreToPanel(); - } - - - DockPanel.ResumeLayout(true, true); - return; - } - else if (m.Msg == WM_CHECKDISPOSE) - { - if (NestedPanes.Count == 0) - { - Dispose(); - } - - return; - } - - base.WndProc(ref m); - } - - #endregion - - #region Private Methods - - private void InternalConstruct(DockPanel dockPanel, DockPane pane, bool boundsSpecified, Rectangle bounds) - { - if (dockPanel == null) - { - throw new ArgumentNullException(Strings.FloatWindow_Constructor_NullDockPanel); - } - - NestedPanes = new NestedPaneCollection(this); - - FormBorderStyle = FormBorderStyle.SizableToolWindow; - ShowInTaskbar = false; - if (dockPanel.RightToLeft != RightToLeft) - { - RightToLeft = dockPanel.RightToLeft; - } - if (RightToLeftLayout != dockPanel.RightToLeftLayout) - { - RightToLeftLayout = dockPanel.RightToLeftLayout; - } - - SuspendLayout(); - if (boundsSpecified) - { - Bounds = bounds; - StartPosition = FormStartPosition.Manual; - } - else - { - StartPosition = FormStartPosition.WindowsDefaultLocation; - Size = dockPanel.DefaultFloatWindowSize; - } - - DockPanel = dockPanel; - Owner = DockPanel.FindForm(); - DockPanel.AddFloatWindow(this); - if (pane != null) - { - pane.FloatWindow = this; - } - - ResumeLayout(); - } - - #endregion - - #region IDockDragSource Members - - #region IDragSource Members - - Control IDragSource.DragControl - { - get { return this; } - } - - #endregion - - bool IDockDragSource.IsDockStateValid(DockState dockState) - { - return IsDockStateValid(dockState); - } - - bool IDockDragSource.CanDockTo(DockPane pane) - { - if (!IsDockStateValid(pane.DockState)) - { - return false; - } - - if (pane.FloatWindow == this) - { - return false; - } - - return true; - } - - Rectangle IDockDragSource.BeginDrag(Point ptMouse) - { - return Bounds; - } - - public void FloatAt(Rectangle floatWindowBounds) - { - Bounds = floatWindowBounds; - } - - public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) - { - if (dockStyle == DockStyle.Fill) - { - for (int i = NestedPanes.Count - 1; i >= 0; i--) - { - DockPane paneFrom = NestedPanes[i]; - for (int j = paneFrom.Contents.Count - 1; j >= 0; j--) - { - IDockContent c = paneFrom.Contents[j]; - c.DockHandler.Pane = pane; - if (contentIndex != -1) - { - pane.SetContentIndex(c, contentIndex); - } - c.DockHandler.Activate(); - } - } - } - else - { - DockAlignment alignment = DockAlignment.Left; - if (dockStyle == DockStyle.Left) - { - alignment = DockAlignment.Left; - } - else if (dockStyle == DockStyle.Right) - { - alignment = DockAlignment.Right; - } - else if (dockStyle == DockStyle.Top) - { - alignment = DockAlignment.Top; - } - else if (dockStyle == DockStyle.Bottom) - { - alignment = DockAlignment.Bottom; - } - - MergeNestedPanes(VisibleNestedPanes, pane.NestedPanesContainer.NestedPanes, pane, alignment, 0.5); - } - } - - public void DockTo(DockPanel panel, DockStyle dockStyle) - { - if (panel != DockPanel) - { - throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); - } - - NestedPaneCollection nestedPanesTo = null; - - if (dockStyle == DockStyle.Top) - { - nestedPanesTo = DockPanel.DockWindows[DockState.DockTop].NestedPanes; - } - else if (dockStyle == DockStyle.Bottom) - { - nestedPanesTo = DockPanel.DockWindows[DockState.DockBottom].NestedPanes; - } - else if (dockStyle == DockStyle.Left) - { - nestedPanesTo = DockPanel.DockWindows[DockState.DockLeft].NestedPanes; - } - else if (dockStyle == DockStyle.Right) - { - nestedPanesTo = DockPanel.DockWindows[DockState.DockRight].NestedPanes; - } - else if (dockStyle == DockStyle.Fill) - { - nestedPanesTo = DockPanel.DockWindows[DockState.Document].NestedPanes; - } - - DockPane prevPane = null; - for (int i = nestedPanesTo.Count - 1; i >= 0; i--) - { - if (nestedPanesTo[i] != VisibleNestedPanes[0]) - { - prevPane = nestedPanesTo[i]; - } - } - MergeNestedPanes(VisibleNestedPanes, nestedPanesTo, prevPane, DockAlignment.Left, 0.5); - } - - private static void MergeNestedPanes(VisibleNestedPaneCollection nestedPanesFrom, - NestedPaneCollection nestedPanesTo, DockPane prevPane, DockAlignment alignment, double proportion) - { - if (nestedPanesFrom.Count == 0) - { - return; - } - - int count = nestedPanesFrom.Count; - DockPane[] panes = new DockPane[count]; - DockPane[] prevPanes = new DockPane[count]; - DockAlignment[] alignments = new DockAlignment[count]; - double[] proportions = new double[count]; - - for (int i = 0; i < count; i++) - { - panes[i] = nestedPanesFrom[i]; - prevPanes[i] = nestedPanesFrom[i].NestedDockingStatus.PreviousPane; - alignments[i] = nestedPanesFrom[i].NestedDockingStatus.Alignment; - proportions[i] = nestedPanesFrom[i].NestedDockingStatus.Proportion; - } - - DockPane pane = panes[0].DockTo(nestedPanesTo.Container, prevPane, alignment, proportion); - panes[0].DockState = nestedPanesTo.DockState; - - for (int i = 1; i < count; i++) - { - for (int j = i; j < count; j++) - { - if (prevPanes[j] == panes[i - 1]) - { - prevPanes[j] = pane; - } - } - pane = panes[i].DockTo(nestedPanesTo.Container, prevPanes[i], alignments[i], proportions[i]); - panes[i].DockState = nestedPanesTo.DockState; - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/FloatWindowCollection.cs b/src/WinFormsUI/Docking/FloatWindowCollection.cs deleted file mode 100644 index fa5434b5..00000000 --- a/src/WinFormsUI/Docking/FloatWindowCollection.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public class FloatWindowCollection : ReadOnlyCollection - { - #region cTor - - internal FloatWindowCollection() - : base(new List()) - { - } - - #endregion - - #region Internals - - internal int Add(FloatWindow fw) - { - if (Items.Contains(fw)) - { - return Items.IndexOf(fw); - } - - Items.Add(fw); - return Count - 1; - } - - internal void Dispose() - { - for (int i = Count - 1; i >= 0; i--) - { - this[i].Close(); - } - } - - internal void Remove(FloatWindow fw) - { - Items.Remove(fw); - } - - internal void BringWindowToFront(FloatWindow fw) - { - Items.Remove(fw); - Items.Add(fw); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Helpers/DockHelper.cs b/src/WinFormsUI/Docking/Helpers/DockHelper.cs deleted file mode 100644 index 1d7c5112..00000000 --- a/src/WinFormsUI/Docking/Helpers/DockHelper.cs +++ /dev/null @@ -1,153 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal static class DockHelper - { - #region Public methods - - public static bool IsDockStateAutoHide(DockState dockState) - { - if (dockState == DockState.DockLeftAutoHide || - dockState == DockState.DockRightAutoHide || - dockState == DockState.DockTopAutoHide || - dockState == DockState.DockBottomAutoHide) - { - return true; - } - else - { - return false; - } - } - - public static bool IsDockStateValid(DockState dockState, DockAreas dockableAreas) - { - if ((dockableAreas & DockAreas.Float) == 0 && - dockState == DockState.Float) - { - return false; - } - else if ((dockableAreas & DockAreas.Document) == 0 && - dockState == DockState.Document) - { - return false; - } - else if ((dockableAreas & DockAreas.DockLeft) == 0 && - (dockState == DockState.DockLeft || dockState == DockState.DockLeftAutoHide)) - { - return false; - } - else if ((dockableAreas & DockAreas.DockRight) == 0 && - (dockState == DockState.DockRight || dockState == DockState.DockRightAutoHide)) - { - return false; - } - else if ((dockableAreas & DockAreas.DockTop) == 0 && - (dockState == DockState.DockTop || dockState == DockState.DockTopAutoHide)) - { - return false; - } - else if ((dockableAreas & DockAreas.DockBottom) == 0 && - (dockState == DockState.DockBottom || dockState == DockState.DockBottomAutoHide)) - { - return false; - } - else - { - return true; - } - } - - public static bool IsDockWindowState(DockState state) - { - if (state == DockState.DockTop || state == DockState.DockBottom || state == DockState.DockLeft || - state == DockState.DockRight || state == DockState.Document) - { - return true; - } - else - { - return false; - } - } - - public static DockState ToggleAutoHideState(DockState state) - { - if (state == DockState.DockLeft) - { - return DockState.DockLeftAutoHide; - } - else if (state == DockState.DockRight) - { - return DockState.DockRightAutoHide; - } - else if (state == DockState.DockTop) - { - return DockState.DockTopAutoHide; - } - else if (state == DockState.DockBottom) - { - return DockState.DockBottomAutoHide; - } - else if (state == DockState.DockLeftAutoHide) - { - return DockState.DockLeft; - } - else if (state == DockState.DockRightAutoHide) - { - return DockState.DockRight; - } - else if (state == DockState.DockTopAutoHide) - { - return DockState.DockTop; - } - else if (state == DockState.DockBottomAutoHide) - { - return DockState.DockBottom; - } - else - { - return state; - } - } - - public static DockPane PaneAtPoint(Point pt, DockPanel dockPanel) - { - for (Control control = Win32Helper.ControlAtPoint(pt); control != null; control = control.Parent) - { - IDockContent content = control as IDockContent; - if (content != null && content.DockHandler.DockPanel == dockPanel) - { - return content.DockHandler.Pane; - } - - DockPane pane = control as DockPane; - if (pane != null && pane.DockPanel == dockPanel) - { - return pane; - } - } - - return null; - } - - public static FloatWindow FloatWindowAtPoint(Point pt, DockPanel dockPanel) - { - for (Control control = Win32Helper.ControlAtPoint(pt); control != null; control = control.Parent) - { - FloatWindow floatWindow = control as FloatWindow; - if (floatWindow != null && floatWindow.DockPanel == dockPanel) - { - return floatWindow; - } - } - - return null; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Helpers/DrawHelper.cs b/src/WinFormsUI/Docking/Helpers/DrawHelper.cs deleted file mode 100644 index 742697bb..00000000 --- a/src/WinFormsUI/Docking/Helpers/DrawHelper.cs +++ /dev/null @@ -1,112 +0,0 @@ -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Drawing.Imaging; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal static class DrawHelper - { - #region Public methods - - public static Point RtlTransform(Control control, Point point) - { - if (control.RightToLeft != RightToLeft.Yes) - { - return point; - } - else - { - return new Point(control.Right - point.X, point.Y); - } - } - - public static Rectangle RtlTransform(Control control, Rectangle rectangle) - { - if (control.RightToLeft != RightToLeft.Yes) - { - return rectangle; - } - else - { - return new Rectangle(control.ClientRectangle.Right - rectangle.Right, rectangle.Y, rectangle.Width, - rectangle.Height); - } - } - - public static GraphicsPath GetRoundedCornerTab(GraphicsPath graphicsPath, Rectangle rect, bool upCorner) - { - if (graphicsPath == null) - { - graphicsPath = new GraphicsPath(); - } - else - { - graphicsPath.Reset(); - } - - int curveSize = 6; - if (upCorner) - { - graphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Top + curveSize / 2); - graphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); - graphicsPath.AddLine(rect.Left + curveSize / 2, rect.Top, rect.Right - curveSize / 2, rect.Top); - graphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90); - graphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom); - } - else - { - graphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Bottom - curveSize / 2); - graphicsPath.AddArc( - new Rectangle(rect.Right - curveSize, rect.Bottom - curveSize, curveSize, curveSize), 0, 90); - graphicsPath.AddLine(rect.Right - curveSize / 2, rect.Bottom, rect.Left + curveSize / 2, rect.Bottom); - graphicsPath.AddArc(new Rectangle(rect.Left, rect.Bottom - curveSize, curveSize, curveSize), 90, 90); - graphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top); - } - - return graphicsPath; - } - - public static GraphicsPath CalculateGraphicsPathFromBitmap(Bitmap bitmap) - { - return CalculateGraphicsPathFromBitmap(bitmap, Color.Empty); - } - - // From http://edu.cnzz.cn/show_3281.html - public static GraphicsPath CalculateGraphicsPathFromBitmap(Bitmap bitmap, Color colorTransparent) - { - GraphicsPath graphicsPath = new GraphicsPath(); - if (colorTransparent == Color.Empty) - { - colorTransparent = bitmap.GetPixel(0, 0); - } - - for (int row = 0; row < bitmap.Height; row++) - { - int colOpaquePixel = 0; - for (int col = 0; col < bitmap.Width; col++) - { - if (bitmap.GetPixel(col, row) != colorTransparent) - { - colOpaquePixel = col; - int colNext = col; - for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++) - { - if (bitmap.GetPixel(colNext, row) == colorTransparent) - { - break; - } - } - - graphicsPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1)); - col = colNext; - } - } - } - return graphicsPath; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Helpers/ResourceHelper.cs b/src/WinFormsUI/Docking/Helpers/ResourceHelper.cs deleted file mode 100644 index 2e1759ca..00000000 --- a/src/WinFormsUI/Docking/Helpers/ResourceHelper.cs +++ /dev/null @@ -1,43 +0,0 @@ -using System; -using System.Drawing; -using System.Reflection; -using System.Resources; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal static class ResourceHelper - { - #region Fields - - private static ResourceManager _resourceManager = null; - - #endregion - - #region Properties - - private static ResourceManager ResourceManager - { - get - { - if (_resourceManager == null) - { - _resourceManager = new ResourceManager("WeifenLuo.WinFormsUI.Docking.Strings", - typeof(ResourceHelper).Assembly); - } - return _resourceManager; - } - } - - #endregion - - #region Public methods - - public static string GetString(string name) - { - return ResourceManager.GetString(name); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Helpers/Win32Helper.cs b/src/WinFormsUI/Docking/Helpers/Win32Helper.cs deleted file mode 100644 index f2cb2bcb..00000000 --- a/src/WinFormsUI/Docking/Helpers/Win32Helper.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal static class Win32Helper - { - #region Public methods - - public static Control ControlAtPoint(Point pt) - { - return Control.FromChildHandle(NativeMethods.WindowFromPoint(pt)); - } - - public static uint MakeLong(int low, int high) - { - return (uint) ((high << 16) + low); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/InertButtonBase.cs b/src/WinFormsUI/Docking/InertButtonBase.cs deleted file mode 100644 index f7891057..00000000 --- a/src/WinFormsUI/Docking/InertButtonBase.cs +++ /dev/null @@ -1,145 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Windows.Forms; -using System.Drawing; -using System.Drawing.Imaging; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal abstract class InertButtonBase : Control - { - #region Fields - - private bool m_isMouseOver = false; - - #endregion - - #region cTor - - protected InertButtonBase() - { - SetStyle(ControlStyles.SupportsTransparentBackColor, true); - BackColor = Color.Transparent; - } - - #endregion - - #region Properties - - public abstract Bitmap Image { get; } - - protected bool IsMouseOver - { - get { return m_isMouseOver; } - private set - { - if (m_isMouseOver == value) - { - return; - } - - m_isMouseOver = value; - Invalidate(); - } - } - - protected override Size DefaultSize - { - get { return Resources.DockPane_Close.Size; } - } - - #endregion - - #region Public methods - - public void RefreshChanges() - { - if (IsDisposed) - { - return; - } - - bool mouseOver = ClientRectangle.Contains(PointToClient(Control.MousePosition)); - if (mouseOver != IsMouseOver) - { - IsMouseOver = mouseOver; - } - - OnRefreshChanges(); - } - - #endregion - - #region Overrides - - protected override void OnMouseMove(MouseEventArgs e) - { - base.OnMouseMove(e); - bool over = ClientRectangle.Contains(e.X, e.Y); - if (IsMouseOver != over) - { - IsMouseOver = over; - } - } - - protected override void OnMouseEnter(EventArgs e) - { - base.OnMouseEnter(e); - if (!IsMouseOver) - { - IsMouseOver = true; - } - } - - protected override void OnMouseLeave(EventArgs e) - { - base.OnMouseLeave(e); - if (IsMouseOver) - { - IsMouseOver = false; - } - } - - protected override void OnPaint(PaintEventArgs e) - { - if (IsMouseOver && Enabled) - { - using (Pen pen = new Pen(ForeColor)) - { - e.Graphics.DrawRectangle(pen, Rectangle.Inflate(ClientRectangle, -1, -1)); - } - } - - using (ImageAttributes imageAttributes = new ImageAttributes()) - { - ColorMap[] colorMap = new ColorMap[2]; - colorMap[0] = new ColorMap(); - colorMap[0].OldColor = Color.FromArgb(0, 0, 0); - colorMap[0].NewColor = ForeColor; - colorMap[1] = new ColorMap(); - colorMap[1].OldColor = Image.GetPixel(0, 0); - colorMap[1].NewColor = Color.Transparent; - - imageAttributes.SetRemapTable(colorMap); - - e.Graphics.DrawImage( - Image, - new Rectangle(0, 0, Image.Width, Image.Height), - 0, 0, - Image.Width, - Image.Height, - GraphicsUnit.Pixel, - imageAttributes); - } - - base.OnPaint(e); - } - - #endregion - - protected virtual void OnRefreshChanges() - { - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Interfaces.cs b/src/WinFormsUI/Docking/Interfaces.cs deleted file mode 100644 index 6654370f..00000000 --- a/src/WinFormsUI/Docking/Interfaces.cs +++ /dev/null @@ -1,76 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public interface IDockContent - { - #region Properties - - DockContentHandler DockHandler { get; } - - #endregion - - #region Public methods - - void OnActivated(EventArgs e); - void OnDeactivate(EventArgs e); - - #endregion - } - - public interface INestedPanesContainer - { - #region Properties - - DockState DockState { get; } - Rectangle DisplayingRectangle { get; } - NestedPaneCollection NestedPanes { get; } - VisibleNestedPaneCollection VisibleNestedPanes { get; } - bool IsFloat { get; } - - #endregion - } - - internal interface IDragSource - { - #region Properties - - Control DragControl { get; } - - #endregion - } - - internal interface IDockDragSource : IDragSource - { - #region Public methods - - Rectangle BeginDrag(Point ptMouse); - bool IsDockStateValid(DockState dockState); - bool CanDockTo(DockPane pane); - void FloatAt(Rectangle floatWindowBounds); - void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex); - void DockTo(DockPanel panel, DockStyle dockStyle); - - #endregion - } - - internal interface ISplitterDragSource : IDragSource - { - #region Properties - - bool IsVertical { get; } - Rectangle DragLimitBounds { get; } - - #endregion - - #region Public methods - - void BeginDrag(Rectangle rectSplitter); - void EndDrag(); - void MoveSplitter(int offset); - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Localization.cs b/src/WinFormsUI/Docking/Localization.cs deleted file mode 100644 index ddb98192..00000000 --- a/src/WinFormsUI/Docking/Localization.cs +++ /dev/null @@ -1,68 +0,0 @@ -using System; -using System.ComponentModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - [AttributeUsage(AttributeTargets.All)] - internal sealed class LocalizedDescriptionAttribute : DescriptionAttribute - { - #region Fields - - private bool m_initialized = false; - - #endregion - - #region cTor - - public LocalizedDescriptionAttribute(string key) : base(key) - { - } - - #endregion - - #region Properties - - public override string Description - { - get - { - if (!m_initialized) - { - string key = base.Description; - DescriptionValue = ResourceHelper.GetString(key); - if (DescriptionValue == null) - { - DescriptionValue = string.Empty; - } - - m_initialized = true; - } - - return DescriptionValue; - } - } - - #endregion - } - - [AttributeUsage(AttributeTargets.All)] - internal sealed class LocalizedCategoryAttribute : CategoryAttribute - { - #region cTor - - public LocalizedCategoryAttribute(string key) : base(key) - { - } - - #endregion - - #region Overrides - - protected override string GetLocalizedString(string key) - { - return ResourceHelper.GetString(key); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Measures.cs b/src/WinFormsUI/Docking/Measures.cs deleted file mode 100644 index a5607852..00000000 --- a/src/WinFormsUI/Docking/Measures.cs +++ /dev/null @@ -1,22 +0,0 @@ -using System; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal static class Measures - { - #region Fields - - public const int SplitterSize = 4; - - #endregion - } - - internal static class MeasurePane - { - #region Fields - - public const int MinSize = 24; - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/NestedDockingStatus.cs b/src/WinFormsUI/Docking/NestedDockingStatus.cs deleted file mode 100644 index c65a5f1c..00000000 --- a/src/WinFormsUI/Docking/NestedDockingStatus.cs +++ /dev/null @@ -1,78 +0,0 @@ -using System; -using System.Drawing; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public sealed class NestedDockingStatus - { - #region Fields - - #endregion - - #region cTor - - internal NestedDockingStatus(DockPane pane) - { - DockPane = pane; - } - - #endregion - - #region Properties - - public DockPane DockPane { get; } = null; - - public NestedPaneCollection NestedPanes { get; private set; } = null; - - public DockPane PreviousPane { get; private set; } = null; - - public DockAlignment Alignment { get; private set; } = DockAlignment.Left; - - public double Proportion { get; private set; } = 0.5; - - public bool IsDisplaying { get; private set; } = false; - - public DockPane DisplayingPreviousPane { get; private set; } = null; - - public DockAlignment DisplayingAlignment { get; private set; } = DockAlignment.Left; - - public double DisplayingProportion { get; private set; } = 0.5; - - public Rectangle LogicalBounds { get; private set; } = Rectangle.Empty; - - public Rectangle PaneBounds { get; private set; } = Rectangle.Empty; - - public Rectangle SplitterBounds { get; private set; } = Rectangle.Empty; - - #endregion - - #region Internals - - internal void SetStatus(NestedPaneCollection nestedPanes, DockPane previousPane, DockAlignment alignment, - double proportion) - { - NestedPanes = nestedPanes; - PreviousPane = previousPane; - Alignment = alignment; - Proportion = proportion; - } - - internal void SetDisplayingStatus(bool isDisplaying, DockPane displayingPreviousPane, - DockAlignment displayingAlignment, double displayingProportion) - { - IsDisplaying = isDisplaying; - DisplayingPreviousPane = displayingPreviousPane; - DisplayingAlignment = displayingAlignment; - DisplayingProportion = displayingProportion; - } - - internal void SetDisplayingBounds(Rectangle logicalBounds, Rectangle paneBounds, Rectangle splitterBounds) - { - LogicalBounds = logicalBounds; - PaneBounds = paneBounds; - SplitterBounds = splitterBounds; - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/NestedPaneCollection.cs b/src/WinFormsUI/Docking/NestedPaneCollection.cs deleted file mode 100644 index 61c6eff9..00000000 --- a/src/WinFormsUI/Docking/NestedPaneCollection.cs +++ /dev/null @@ -1,212 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Drawing; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public sealed class NestedPaneCollection : ReadOnlyCollection - { - #region Fields - - #endregion - - #region cTor - - internal NestedPaneCollection(INestedPanesContainer container) - : base(new List()) - { - Container = container; - VisibleNestedPanes = new VisibleNestedPaneCollection(this); - } - - #endregion - - #region Properties - - public INestedPanesContainer Container { get; } - - public VisibleNestedPaneCollection VisibleNestedPanes { get; } - - public DockState DockState - { - get { return Container.DockState; } - } - - public bool IsFloat - { - get { return DockState == DockState.Float; } - } - - #endregion - - #region Public methods - - public DockPane GetDefaultPreviousPane(DockPane pane) - { - for (int i = Count - 1; i >= 0; i--) - { - if (this[i] != pane) - { - return this[i]; - } - } - - return null; - } - - #endregion - - #region Internals - - internal void Add(DockPane pane) - { - if (pane == null) - { - return; - } - - NestedPaneCollection oldNestedPanes = - pane.NestedPanesContainer == null ? null : pane.NestedPanesContainer.NestedPanes; - if (oldNestedPanes != null) - { - oldNestedPanes.InternalRemove(pane); - } - Items.Add(pane); - if (oldNestedPanes != null) - { - oldNestedPanes.CheckFloatWindowDispose(); - } - } - - /// - /// Switches a pane with its first child in the pane hierarchy. (The actual hiding happens elsewhere.) - /// - /// Pane to switch - internal void SwitchPaneWithFirstChild(DockPane pane) - { - if (!Contains(pane)) - { - return; - } - - NestedDockingStatus statusPane = pane.NestedDockingStatus; - DockPane lastNestedPane = null; - for (int i = Count - 1; i > IndexOf(pane); i--) - { - if (this[i].NestedDockingStatus.PreviousPane == pane) - { - lastNestedPane = this[i]; - break; - } - } - - if (lastNestedPane != null) - { - int indexLastNestedPane = IndexOf(lastNestedPane); - Items[IndexOf(pane)] = lastNestedPane; - Items[indexLastNestedPane] = pane; - NestedDockingStatus lastNestedDock = lastNestedPane.NestedDockingStatus; - - DockAlignment newAlignment; - if (lastNestedDock.Alignment == DockAlignment.Left) - { - newAlignment = DockAlignment.Right; - } - else if (lastNestedDock.Alignment == DockAlignment.Right) - { - newAlignment = DockAlignment.Left; - } - else if (lastNestedDock.Alignment == DockAlignment.Top) - { - newAlignment = DockAlignment.Bottom; - } - else - { - newAlignment = DockAlignment.Top; - } - double newProportion = 1 - lastNestedDock.Proportion; - - lastNestedDock.SetStatus(this, statusPane.PreviousPane, statusPane.Alignment, statusPane.Proportion); - for (int i = indexLastNestedPane - 1; i > IndexOf(lastNestedPane); i--) - { - NestedDockingStatus status = this[i].NestedDockingStatus; - if (status.PreviousPane == pane) - { - status.SetStatus(this, lastNestedPane, status.Alignment, status.Proportion); - } - } - - statusPane.SetStatus(this, lastNestedPane, newAlignment, newProportion); - } - } - - internal void Remove(DockPane pane) - { - InternalRemove(pane); - CheckFloatWindowDispose(); - } - - #endregion - - #region Private Methods - - private void CheckFloatWindowDispose() - { - if (Count == 0 && Container.DockState == DockState.Float) - { - FloatWindow floatWindow = (FloatWindow) Container; - if (!floatWindow.Disposing && !floatWindow.IsDisposed) - { - NativeMethods.PostMessage(((FloatWindow) Container).Handle, FloatWindow.WM_CHECKDISPOSE, 0, 0); - } - } - } - - private void InternalRemove(DockPane pane) - { - if (!Contains(pane)) - { - return; - } - - NestedDockingStatus statusPane = pane.NestedDockingStatus; - DockPane lastNestedPane = null; - for (int i = Count - 1; i > IndexOf(pane); i--) - { - if (this[i].NestedDockingStatus.PreviousPane == pane) - { - lastNestedPane = this[i]; - break; - } - } - - if (lastNestedPane != null) - { - int indexLastNestedPane = IndexOf(lastNestedPane); - Items.Remove(lastNestedPane); - Items[IndexOf(pane)] = lastNestedPane; - NestedDockingStatus lastNestedDock = lastNestedPane.NestedDockingStatus; - lastNestedDock.SetStatus(this, statusPane.PreviousPane, statusPane.Alignment, statusPane.Proportion); - for (int i = indexLastNestedPane - 1; i > IndexOf(lastNestedPane); i--) - { - NestedDockingStatus status = this[i].NestedDockingStatus; - if (status.PreviousPane == pane) - { - status.SetStatus(this, lastNestedPane, status.Alignment, status.Proportion); - } - } - } - else - { - Items.Remove(pane); - } - - statusPane.SetStatus(null, null, DockAlignment.Left, 0.5); - statusPane.SetDisplayingStatus(false, null, DockAlignment.Left, 0.5); - statusPane.SetDisplayingBounds(Rectangle.Empty, Rectangle.Empty, Rectangle.Empty); - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Resources.Designer.cs b/src/WinFormsUI/Docking/Resources.Designer.cs deleted file mode 100644 index 38344cce..00000000 --- a/src/WinFormsUI/Docking/Resources.Designer.cs +++ /dev/null @@ -1,293 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace WeifenLuo.WinFormsUI.Docking { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Resources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Resources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WeifenLuo.WinFormsUI.Docking.Resources", typeof(Resources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond_Bottom { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond_Bottom", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond_Fill { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond_Fill", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond_HotSpot { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond_HotSpot", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond_HotSpotIndex { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond_HotSpotIndex", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond_Left { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond_Left", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond_Right { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond_Right", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PaneDiamond_Top { - get { - object obj = ResourceManager.GetObject("DockIndicator_PaneDiamond_Top", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelBottom { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelBottom", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelBottom_Active { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelBottom_Active", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelFill { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelFill", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelFill_Active { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelFill_Active", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelLeft { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelLeft", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelLeft_Active { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelLeft_Active", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelRight { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelRight", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelRight_Active { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelRight_Active", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelTop { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelTop", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockIndicator_PanelTop_Active { - get { - object obj = ResourceManager.GetObject("DockIndicator_PanelTop_Active", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockPane_AutoHide { - get { - object obj = ResourceManager.GetObject("DockPane_AutoHide", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockPane_Close { - get { - object obj = ResourceManager.GetObject("DockPane_Close", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockPane_Dock { - get { - object obj = ResourceManager.GetObject("DockPane_Dock", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockPane_Option { - get { - object obj = ResourceManager.GetObject("DockPane_Option", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - - /// - /// Looks up a localized resource of type System.Drawing.Bitmap. - /// - internal static System.Drawing.Bitmap DockPane_OptionOverflow { - get { - object obj = ResourceManager.GetObject("DockPane_OptionOverflow", resourceCulture); - return ((System.Drawing.Bitmap)(obj)); - } - } - } -} diff --git a/src/WinFormsUI/Docking/Resources.resx b/src/WinFormsUI/Docking/Resources.resx deleted file mode 100644 index 3032913d..00000000 --- a/src/WinFormsUI/Docking/Resources.resx +++ /dev/null @@ -1,190 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - - Resources\DockIndicator_PaneDiamond.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PaneDiamond_Bottom.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\Dockindicator_PaneDiamond_Fill.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PaneDiamond_Hotspot.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PaneDiamond_HotspotIndex.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PaneDiamond_Left.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PaneDiamond_Right.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PaneDiamond_Top.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelBottom.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelBottom_Active.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelFill.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelFill_Active.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelLeft.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelLeft_Active.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelRight.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelRight_Active.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelTop.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockIndicator_PanelTop_Active.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockPane_AutoHide.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockPane_Close.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockPane_Dock.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockPane_Option.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - - Resources\DockPane_OptionOverflow.bmp;System.Drawing.Bitmap, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a - - \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond.bmp deleted file mode 100644 index 70e70e28..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Bottom.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Bottom.bmp deleted file mode 100644 index d95ec697..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Bottom.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Hotspot.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Hotspot.bmp deleted file mode 100644 index e801d382..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Hotspot.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_HotspotIndex.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_HotspotIndex.bmp deleted file mode 100644 index e5ef472c..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_HotspotIndex.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Left.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Left.bmp deleted file mode 100644 index 1fbda61c..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Left.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Right.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Right.bmp deleted file mode 100644 index 1de97a09..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Right.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Top.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Top.bmp deleted file mode 100644 index 95122a0f..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PaneDiamond_Top.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelBottom.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelBottom.bmp deleted file mode 100644 index ad851ea1..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelBottom.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelBottom_Active.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelBottom_Active.bmp deleted file mode 100644 index 212fb0d3..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelBottom_Active.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelFill.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelFill.bmp deleted file mode 100644 index 21a1b274..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelFill.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelFill_Active.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelFill_Active.bmp deleted file mode 100644 index d58b00f9..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelFill_Active.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelLeft.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelLeft.bmp deleted file mode 100644 index 551fd886..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelLeft.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelLeft_Active.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelLeft_Active.bmp deleted file mode 100644 index 5182318e..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelLeft_Active.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelRight.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelRight.bmp deleted file mode 100644 index 003cbb02..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelRight.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelRight_Active.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelRight_Active.bmp deleted file mode 100644 index dad42355..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelRight_Active.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelTop.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelTop.bmp deleted file mode 100644 index f6293fd2..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelTop.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelTop_Active.bmp b/src/WinFormsUI/Docking/Resources/DockIndicator_PanelTop_Active.bmp deleted file mode 100644 index 563549eb..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockIndicator_PanelTop_Active.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockPane_AutoHide.bmp b/src/WinFormsUI/Docking/Resources/DockPane_AutoHide.bmp deleted file mode 100644 index 2f395fc0..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockPane_AutoHide.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockPane_Close.bmp b/src/WinFormsUI/Docking/Resources/DockPane_Close.bmp deleted file mode 100644 index a7748a67..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockPane_Close.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockPane_Dock.bmp b/src/WinFormsUI/Docking/Resources/DockPane_Dock.bmp deleted file mode 100644 index 6a9d145e..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockPane_Dock.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockPane_Option.bmp b/src/WinFormsUI/Docking/Resources/DockPane_Option.bmp deleted file mode 100644 index 0d9927a7..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockPane_Option.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/DockPane_OptionOverflow.bmp b/src/WinFormsUI/Docking/Resources/DockPane_OptionOverflow.bmp deleted file mode 100644 index 02e4bf29..00000000 Binary files a/src/WinFormsUI/Docking/Resources/DockPane_OptionOverflow.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/Resources/Dockindicator_PaneDiamond_Fill.bmp b/src/WinFormsUI/Docking/Resources/Dockindicator_PaneDiamond_Fill.bmp deleted file mode 100644 index cbe0a156..00000000 Binary files a/src/WinFormsUI/Docking/Resources/Dockindicator_PaneDiamond_Fill.bmp and /dev/null differ diff --git a/src/WinFormsUI/Docking/SplitterBase.cs b/src/WinFormsUI/Docking/SplitterBase.cs deleted file mode 100644 index 4897b8f8..00000000 --- a/src/WinFormsUI/Docking/SplitterBase.cs +++ /dev/null @@ -1,98 +0,0 @@ -using System; -using System.Collections; -using System.ComponentModel; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal class SplitterBase : Control - { - #region cTor - - public SplitterBase() - { - SetStyle(ControlStyles.Selectable, false); - } - - #endregion - - #region Properties - - public override DockStyle Dock - { - get { return base.Dock; } - set - { - SuspendLayout(); - base.Dock = value; - - if (Dock == DockStyle.Left || Dock == DockStyle.Right) - { - Width = SplitterSize; - } - else if (Dock == DockStyle.Top || Dock == DockStyle.Bottom) - { - Height = SplitterSize; - } - else - { - Bounds = Rectangle.Empty; - } - - if (Dock == DockStyle.Left || Dock == DockStyle.Right) - { - Cursor = Cursors.VSplit; - } - else if (Dock == DockStyle.Top || Dock == DockStyle.Bottom) - { - Cursor = Cursors.HSplit; - } - else - { - Cursor = Cursors.Default; - } - - ResumeLayout(); - } - } - - protected virtual int SplitterSize - { - get { return 0; } - } - - #endregion - - #region Overrides - - protected override void OnMouseDown(MouseEventArgs e) - { - base.OnMouseDown(e); - - if (e.Button != MouseButtons.Left) - { - return; - } - - StartDrag(); - } - - protected override void WndProc(ref Message m) - { - // eat the WM_MOUSEACTIVATE message - if (m.Msg == (int) Win32.Msgs.WM_MOUSEACTIVATE) - { - return; - } - - base.WndProc(ref m); - } - - #endregion - - protected virtual void StartDrag() - { - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Strings.Designer.cs b/src/WinFormsUI/Docking/Strings.Designer.cs deleted file mode 100644 index 468be951..00000000 --- a/src/WinFormsUI/Docking/Strings.Designer.cs +++ /dev/null @@ -1,774 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace WeifenLuo.WinFormsUI.Docking { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class Strings { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal Strings() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("WeifenLuo.WinFormsUI.Docking.Strings", typeof(Strings).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to Docking. - /// - internal static string Category_Docking { - get { - return ResourceManager.GetString("Category_Docking", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Docking Notification. - /// - internal static string Category_DockingNotification { - get { - return ResourceManager.GetString("Category_DockingNotification", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Property Changed. - /// - internal static string Category_PropertyChanged { - get { - return ResourceManager.GetString("Category_PropertyChanged", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to (Float). - /// - internal static string DockAreaEditor_FloatCheckBoxText { - get { - return ResourceManager.GetString("DockAreaEditor_FloatCheckBoxText", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Determines if end user drag and drop docking is allowed.. - /// - internal static string DockContent_AllowEndUserDocking_Description { - get { - return ResourceManager.GetString("DockContent_AllowEndUserDocking_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The size to display the content in auto hide mode. Value < 1 to specify the size in portion; value >= 1 to specify the size in pixel.. - /// - internal static string DockContent_AutoHidePortion_Description { - get { - return ResourceManager.GetString("DockContent_AutoHidePortion_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Enable/Disable the close button of the content.. - /// - internal static string DockContent_CloseButton_Description { - get { - return ResourceManager.GetString("DockContent_CloseButton_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Shows or hides the close button of the content. This property does not function with System MDI Document Style.. - /// - internal static string DockContent_CloseButtonVisible_Description { - get { - return ResourceManager.GetString("DockContent_CloseButtonVisible_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The form must be of type IDockContent.. - /// - internal static string DockContent_Constructor_InvalidForm { - get { - return ResourceManager.GetString("DockContent_Constructor_InvalidForm", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Gets or sets a value indicating in which area of the DockPanel the content allowed to show.. - /// - internal static string DockContent_DockAreas_Description { - get { - return ResourceManager.GetString("DockContent_DockAreas_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Occurs when the value of DockState property changed.. - /// - internal static string DockContent_DockStateChanged_Description { - get { - return ResourceManager.GetString("DockContent_DockStateChanged_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Indicates the content will be hidden instead of being closed.. - /// - internal static string DockContent_HideOnClose_Description { - get { - return ResourceManager.GetString("DockContent_HideOnClose_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The desired docking state when first showing.. - /// - internal static string DockContent_ShowHint_Description { - get { - return ResourceManager.GetString("DockContent_ShowHint_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Context menu displayed for the dock pane tab strip.. - /// - internal static string DockContent_TabPageContextMenu_Description { - get { - return ResourceManager.GetString("DockContent_TabPageContextMenu_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The tab text displayed in the dock pane. If not set, the Text property will be used.. - /// - internal static string DockContent_TabText_Description { - get { - return ResourceManager.GetString("DockContent_TabText_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The text displayed when mouse hovers over the tab.. - /// - internal static string DockContent_ToolTipText_Description { - get { - return ResourceManager.GetString("DockContent_ToolTipText_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The provided value is out of range.. - /// - internal static string DockContentHandler_AutoHidePortion_OutOfRange { - get { - return ResourceManager.GetString("DockContentHandler_AutoHidePortion_OutOfRange", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Value: The value of DockAreas conflicts with current DockState.. - /// - internal static string DockContentHandler_DockAreas_InvalidValue { - get { - return ResourceManager.GetString("DockContentHandler_DockAreas_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The pane is invalid. Check the IsFloat and DockPanel properties of this dock pane.. - /// - internal static string DockContentHandler_DockPane_InvalidValue { - get { - return ResourceManager.GetString("DockContentHandler_DockPane_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The pane is invalid. Check the IsFloat and DockPanel properties of this dock pane.. - /// - internal static string DockContentHandler_FloatPane_InvalidValue { - get { - return ResourceManager.GetString("DockContentHandler_FloatPane_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value, conflicts with DockableAreas property.. - /// - internal static string DockContentHandler_IsFloat_InvalidValue { - get { - return ResourceManager.GetString("DockContentHandler_IsFloat_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The dock state is invalid.. - /// - internal static string DockContentHandler_SetDockState_InvalidState { - get { - return ResourceManager.GetString("DockContentHandler_SetDockState_InvalidState", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The dock panel is null.. - /// - internal static string DockContentHandler_SetDockState_NullPanel { - get { - return ResourceManager.GetString("DockContentHandler_SetDockState_NullPanel", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid beforeContent, it must be contained by the pane.. - /// - internal static string DockContentHandler_Show_InvalidBeforeContent { - get { - return ResourceManager.GetString("DockContentHandler_Show_InvalidBeforeContent", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid DockState: Content can not be showed as "Unknown" or "Hidden".. - /// - internal static string DockContentHandler_Show_InvalidDockState { - get { - return ResourceManager.GetString("DockContentHandler_Show_InvalidDockState", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The previous pane is invalid. It can not be null, and its docking state must not be auto-hide.. - /// - internal static string DockContentHandler_Show_InvalidPrevPane { - get { - return ResourceManager.GetString("DockContentHandler_Show_InvalidPrevPane", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DockPanel can not be null.. - /// - internal static string DockContentHandler_Show_NullDockPanel { - get { - return ResourceManager.GetString("DockContentHandler_Show_NullDockPanel", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The Pane can not be null.. - /// - internal static string DockContentHandler_Show_NullPane { - get { - return ResourceManager.GetString("DockContentHandler_Show_NullPane", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value, check DockableAreas property.. - /// - internal static string DockContentHandler_ShowHint_InvalidValue { - get { - return ResourceManager.GetString("DockContentHandler_ShowHint_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Context menu displayed for the dock pane tab strip.. - /// - internal static string DockHandler_TabPageContextMenuStrip_Description { - get { - return ResourceManager.GetString("DockHandler_TabPageContextMenuStrip_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Press SHIFT for docking to full side.. - /// - internal static string DockIndicator_ToolTipText { - get { - return ResourceManager.GetString("DockIndicator_ToolTipText", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Content: ActiveContent must be one of the visible contents, or null if there is no visible content.. - /// - internal static string DockPane_ActiveContent_InvalidValue { - get { - return ResourceManager.GetString("DockPane_ActiveContent_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid argument: Content can not be "null".. - /// - internal static string DockPane_Constructor_NullContent { - get { - return ResourceManager.GetString("DockPane_Constructor_NullContent", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid argument: The content's DockPanel can not be "null".. - /// - internal static string DockPane_Constructor_NullDockPanel { - get { - return ResourceManager.GetString("DockPane_Constructor_NullDockPanel", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The specified container conflicts with the IsFloat property.. - /// - internal static string DockPane_DockTo_InvalidContainer { - get { - return ResourceManager.GetString("DockPane_DockTo_InvalidContainer", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The previous pane does not exist in the nested docking pane collection.. - /// - internal static string DockPane_DockTo_NoPrevPane { - get { - return ResourceManager.GetString("DockPane_DockTo_NoPrevPane", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The container can not be null.. - /// - internal static string DockPane_DockTo_NullContainer { - get { - return ResourceManager.GetString("DockPane_DockTo_NullContainer", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The previous pane can not be null when the nested docking pane collection is not empty.. - /// - internal static string DockPane_DockTo_NullPrevPane { - get { - return ResourceManager.GetString("DockPane_DockTo_NullPrevPane", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The previous pane can not be itself.. - /// - internal static string DockPane_DockTo_SelfPrevPane { - get { - return ResourceManager.GetString("DockPane_DockTo_SelfPrevPane", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to FloatWindow property can not be set to "null" when DockState is DockState.Float.. - /// - internal static string DockPane_FloatWindow_InvalidValue { - get { - return ResourceManager.GetString("DockPane_FloatWindow_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Content: Content not within the collection.. - /// - internal static string DockPane_SetContentIndex_InvalidContent { - get { - return ResourceManager.GetString("DockPane_SetContentIndex_InvalidContent", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Index: The index is out of range.. - /// - internal static string DockPane_SetContentIndex_InvalidIndex { - get { - return ResourceManager.GetString("DockPane_SetContentIndex_InvalidIndex", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The state for the dock pane is invalid.. - /// - internal static string DockPane_SetDockState_InvalidState { - get { - return ResourceManager.GetString("DockPane_SetDockState_InvalidState", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Auto Hide. - /// - internal static string DockPaneCaption_ToolTipAutoHide { - get { - return ResourceManager.GetString("DockPaneCaption_ToolTipAutoHide", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close. - /// - internal static string DockPaneCaption_ToolTipClose { - get { - return ResourceManager.GetString("DockPaneCaption_ToolTipClose", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Options. - /// - internal static string DockPaneCaption_ToolTipOptions { - get { - return ResourceManager.GetString("DockPaneCaption_ToolTipOptions", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Content: The content must be auto-hide state and associates with this DockPanel.. - /// - internal static string DockPanel_ActiveAutoHideContent_InvalidValue { - get { - return ResourceManager.GetString("DockPanel_ActiveAutoHideContent_InvalidValue", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Occurs when the value of ActiveContentProperty changed.. - /// - internal static string DockPanel_ActiveContentChanged_Description { - get { - return ResourceManager.GetString("DockPanel_ActiveContentChanged_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Occurs when the value of ActiveDocument property changed.. - /// - internal static string DockPanel_ActiveDocumentChanged_Description { - get { - return ResourceManager.GetString("DockPanel_ActiveDocumentChanged_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Occurs when the value of ActivePane property changed.. - /// - internal static string DockPanel_ActivePaneChanged_Description { - get { - return ResourceManager.GetString("DockPanel_ActivePaneChanged_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Determines if the drag and drop docking is allowed.. - /// - internal static string DockPanel_AllowEndUserDocking_Description { - get { - return ResourceManager.GetString("DockPanel_AllowEndUserDocking_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Determines if the drag and drop nested docking is allowed.. - /// - internal static string DockPanel_AllowEndUserNestedDocking_Description { - get { - return ResourceManager.GetString("DockPanel_AllowEndUserNestedDocking_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Occurs when a content added to the DockPanel.. - /// - internal static string DockPanel_ContentAdded_Description { - get { - return ResourceManager.GetString("DockPanel_ContentAdded_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Occurs when a content removed from the DockPanel.. - /// - internal static string DockPanel_ContentRemoved_Description { - get { - return ResourceManager.GetString("DockPanel_ContentRemoved_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The default size of float window.. - /// - internal static string DockPanel_DefaultFloatWindowSize_Description { - get { - return ResourceManager.GetString("DockPanel_DefaultFloatWindowSize_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Provides Visual Studio .Net style docking.. - /// - internal static string DockPanel_Description { - get { - return ResourceManager.GetString("DockPanel_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Size of the bottom docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels.. - /// - internal static string DockPanel_DockBottomPortion_Description { - get { - return ResourceManager.GetString("DockPanel_DockBottomPortion_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Size of the left docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels.. - /// - internal static string DockPanel_DockLeftPortion_Description { - get { - return ResourceManager.GetString("DockPanel_DockLeftPortion_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The visual skin to use when displaying the docked windows.. - /// - internal static string DockPanel_DockPanelSkin { - get { - return ResourceManager.GetString("DockPanel_DockPanelSkin", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Size of the right docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels.. - /// - internal static string DockPanel_DockRightPortion_Description { - get { - return ResourceManager.GetString("DockPanel_DockRightPortion_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Size of the top docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels.. - /// - internal static string DockPanel_DockTopPortion_Description { - get { - return ResourceManager.GetString("DockPanel_DockTopPortion_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The style of the document window.. - /// - internal static string DockPanel_DocumentStyle_Description { - get { - return ResourceManager.GetString("DockPanel_DocumentStyle_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Determines where the tab strip for Document style content is drawn.. - /// - internal static string DockPanel_DocumentTabStripLocation { - get { - return ResourceManager.GetString("DockPanel_DocumentTabStripLocation", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The DockPanel has already been initialized.. - /// - internal static string DockPanel_LoadFromXml_AlreadyInitialized { - get { - return ResourceManager.GetString("DockPanel_LoadFromXml_AlreadyInitialized", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The configuration file's version is invalid.. - /// - internal static string DockPanel_LoadFromXml_InvalidFormatVersion { - get { - return ResourceManager.GetString("DockPanel_LoadFromXml_InvalidFormatVersion", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to The XML file format is invalid.. - /// - internal static string DockPanel_LoadFromXml_InvalidXmlFormat { - get { - return ResourceManager.GetString("DockPanel_LoadFromXml_InvalidXmlFormat", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid parent form. When using DockingMdi or SystemMdi document style, the DockPanel control must be the child control of the main MDI container form.. - /// - internal static string DockPanel_ParentForm_Invalid { - get { - return ResourceManager.GetString("DockPanel_ParentForm_Invalid", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to DockPanel configuration file. Author: Weifen Luo, all rights reserved.. - /// - internal static string DockPanel_Persistor_XmlFileComment1 { - get { - return ResourceManager.GetString("DockPanel_Persistor_XmlFileComment1", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to !!! AUTOMATICALLY GENERATED FILE. DO NOT MODIFY !!!. - /// - internal static string DockPanel_Persistor_XmlFileComment2 { - get { - return ResourceManager.GetString("DockPanel_Persistor_XmlFileComment2", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Indicates whether the control layout is right-to-left when the RightToLeft property is set to Yes.. - /// - internal static string DockPanel_RightToLeftLayout_Description { - get { - return ResourceManager.GetString("DockPanel_RightToLeftLayout_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Index: The index is out of range.. - /// - internal static string DockPanel_SetPaneIndex_InvalidIndex { - get { - return ResourceManager.GetString("DockPanel_SetPaneIndex_InvalidIndex", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Pane: DockPane not within the collection.. - /// - internal static string DockPanel_SetPaneIndex_InvalidPane { - get { - return ResourceManager.GetString("DockPanel_SetPaneIndex_InvalidPane", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Determines if the document icon will be displayed in the tab strip.. - /// - internal static string DockPanel_ShowDocumentIcon_Description { - get { - return ResourceManager.GetString("DockPanel_ShowDocumentIcon_Description", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Close. - /// - internal static string DockPaneStrip_ToolTipClose { - get { - return ResourceManager.GetString("DockPaneStrip_ToolTipClose", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Window List. - /// - internal static string DockPaneStrip_ToolTipWindowList { - get { - return ResourceManager.GetString("DockPaneStrip_ToolTipWindowList", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid argument: DockPanel can not be "null".. - /// - internal static string FloatWindow_Constructor_NullDockPanel { - get { - return ResourceManager.GetString("FloatWindow_Constructor_NullDockPanel", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Index: The index is out of range.. - /// - internal static string FloatWindow_SetPaneIndex_InvalidIndex { - get { - return ResourceManager.GetString("FloatWindow_SetPaneIndex_InvalidIndex", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Pane: DockPane not within the collection.. - /// - internal static string FloatWindow_SetPaneIndex_InvalidPane { - get { - return ResourceManager.GetString("FloatWindow_SetPaneIndex_InvalidPane", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid DockPanel.. - /// - internal static string IDockDragSource_DockTo_InvalidPanel { - get { - return ResourceManager.GetString("IDockDragSource_DockTo_InvalidPanel", resourceCulture); - } - } - } -} diff --git a/src/WinFormsUI/Docking/Strings.resx b/src/WinFormsUI/Docking/Strings.resx deleted file mode 100644 index d5ff49d5..00000000 --- a/src/WinFormsUI/Docking/Strings.resx +++ /dev/null @@ -1,357 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Docking - - - Docking Notification - - - Property Changed - - - (Float) - - - Determines if end user drag and drop docking is allowed. - - - The size to display the content in auto hide mode. Value < 1 to specify the size in portion; value >= 1 to specify the size in pixel. - - - Enable/Disable the close button of the content. - - - The form must be of type IDockContent. - - - Gets or sets a value indicating in which area of the DockPanel the content allowed to show. - - - Occurs when the value of DockState property changed. - - - Indicates the content will be hidden instead of being closed. - - - The desired docking state when first showing. - - - Context menu displayed for the dock pane tab strip. - - - The tab text displayed in the dock pane. If not set, the Text property will be used. - - - The text displayed when mouse hovers over the tab. - - - The provided value is out of range. - - - Invalid Value: The value of DockAreas conflicts with current DockState. - - - The pane is invalid. Check the IsFloat and DockPanel properties of this dock pane. - - - The pane is invalid. Check the IsFloat and DockPanel properties of this dock pane. - - - Invalid value, conflicts with DockableAreas property. - - - The dock state is invalid. - - - The dock panel is null. - - - Invalid beforeContent, it must be contained by the pane. - - - Invalid DockState: Content can not be showed as "Unknown" or "Hidden". - - - The previous pane is invalid. It can not be null, and its docking state must not be auto-hide. - - - DockPanel can not be null. - - - The Pane can not be null. - - - Invalid value, check DockableAreas property. - - - Context menu displayed for the dock pane tab strip. - - - Press SHIFT for docking to full side. - - - Invalid Content: ActiveContent must be one of the visible contents, or null if there is no visible content. - - - Invalid argument: Content can not be "null". - - - Invalid argument: The content's DockPanel can not be "null". - - - The specified container conflicts with the IsFloat property. - - - The previous pane does not exist in the nested docking pane collection. - - - The container can not be null. - - - The previous pane can not be null when the nested docking pane collection is not empty. - - - The previous pane can not be itself. - - - FloatWindow property can not be set to "null" when DockState is DockState.Float. - - - Invalid Content: Content not within the collection. - - - Invalid Index: The index is out of range. - - - The state for the dock pane is invalid. - - - Auto Hide - - - Close - - - Options - - - Invalid Content: The content must be auto-hide state and associates with this DockPanel. - - - Occurs when the value of ActiveContentProperty changed. - - - Occurs when the value of ActiveDocument property changed. - - - Occurs when the value of ActivePane property changed. - - - Determines if the drag and drop docking is allowed. - - - Determines if the drag and drop nested docking is allowed. - - - Occurs when a content added to the DockPanel. - - - Occurs when a content removed from the DockPanel. - - - The default size of float window. - - - Provides Visual Studio .Net style docking. - - - Size of the bottom docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels. - - - Size of the left docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels. - - - Size of the right docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels. - - - Size of the top docking window. Value < 1 to specify the size in portion; value > 1 to specify the size in pixels. - - - The style of the document window. - - - The DockPanel has already been initialized. - - - The configuration file's version is invalid. - - - The XML file format is invalid. - - - Invalid parent form. When using DockingMdi or SystemMdi document style, the DockPanel control must be the child control of the main MDI container form. - - - DockPanel configuration file. Author: Weifen Luo, all rights reserved. - - - !!! AUTOMATICALLY GENERATED FILE. DO NOT MODIFY !!! - - - Indicates whether the control layout is right-to-left when the RightToLeft property is set to Yes. - - - Invalid Index: The index is out of range. - - - Invalid Pane: DockPane not within the collection. - - - Determines if the document icon will be displayed in the tab strip. - - - Close - - - Window List - - - Invalid argument: DockPanel can not be "null". - - - Invalid Index: The index is out of range. - - - Invalid Pane: DockPane not within the collection. - - - Invalid DockPanel. - - - Shows or hides the close button of the content. This property does not function with System MDI Document Style. - - - The visual skin to use when displaying the docked windows. - - - Determines where the tab strip for Document style content is drawn. - - \ No newline at end of file diff --git a/src/WinFormsUI/Docking/VS2005AutoHideStrip.cs b/src/WinFormsUI/Docking/VS2005AutoHideStrip.cs deleted file mode 100644 index 8f2f992d..00000000 --- a/src/WinFormsUI/Docking/VS2005AutoHideStrip.cs +++ /dev/null @@ -1,604 +0,0 @@ -using System; -using System.Drawing; -using System.Windows.Forms; -using System.Drawing.Drawing2D; -using System.ComponentModel; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal class VS2005AutoHideStrip : AutoHideStripBase - { - #region Fields - - private const int _ImageHeight = 16; - private const int _ImageWidth = 16; - private const int _ImageGapTop = 2; - private const int _ImageGapLeft = 4; - private const int _ImageGapRight = 2; - private const int _ImageGapBottom = 2; - private const int _TextGapLeft = 0; - private const int _TextGapRight = 0; - private const int _TabGapTop = 3; - private const int _TabGapLeft = 4; - private const int _TabGapBetween = 10; - - private static StringFormat _stringFormatTabHorizontal; - - private static StringFormat _stringFormatTabVertical; - - private static DockState[] _dockStates; - - private static GraphicsPath _graphicsPath; - - #endregion - - #region cTor - - public VS2005AutoHideStrip(DockPanel panel) - : base(panel) - { - SetStyle(ControlStyles.ResizeRedraw | - ControlStyles.UserPaint | - ControlStyles.AllPaintingInWmPaint | - ControlStyles.OptimizedDoubleBuffer, true); - BackColor = SystemColors.ControlLight; - } - - #endregion - - #region Properties - - public Font TextFont - { - get { return DockPanel.Skin.AutoHideStripSkin.TextFont; } - } - - private StringFormat StringFormatTabHorizontal - { - get - { - if (_stringFormatTabHorizontal == null) - { - _stringFormatTabHorizontal = new StringFormat(); - _stringFormatTabHorizontal.Alignment = StringAlignment.Near; - _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; - _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; - _stringFormatTabHorizontal.Trimming = StringTrimming.None; - } - - if (RightToLeft == RightToLeft.Yes) - { - _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - } - else - { - _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; - } - - return _stringFormatTabHorizontal; - } - } - - private StringFormat StringFormatTabVertical - { - get - { - if (_stringFormatTabVertical == null) - { - _stringFormatTabVertical = new StringFormat(); - _stringFormatTabVertical.Alignment = StringAlignment.Near; - _stringFormatTabVertical.LineAlignment = StringAlignment.Center; - _stringFormatTabVertical.FormatFlags = - StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; - _stringFormatTabVertical.Trimming = StringTrimming.None; - } - if (RightToLeft == RightToLeft.Yes) - { - _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; - } - else - { - _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; - } - - return _stringFormatTabVertical; - } - } - - private static int ImageHeight - { - get { return _ImageHeight; } - } - - private static int ImageWidth - { - get { return _ImageWidth; } - } - - private static int ImageGapTop - { - get { return _ImageGapTop; } - } - - private static int ImageGapLeft - { - get { return _ImageGapLeft; } - } - - private static int ImageGapRight - { - get { return _ImageGapRight; } - } - - private static int ImageGapBottom - { - get { return _ImageGapBottom; } - } - - private static int TextGapLeft - { - get { return _TextGapLeft; } - } - - private static int TextGapRight - { - get { return _TextGapRight; } - } - - private static int TabGapTop - { - get { return _TabGapTop; } - } - - private static int TabGapLeft - { - get { return _TabGapLeft; } - } - - private static int TabGapBetween - { - get { return _TabGapBetween; } - } - - private static Pen PenTabBorder - { - get { return SystemPens.GrayText; } - } - - private static Matrix MatrixIdentity { get; } = new Matrix(); - - private static DockState[] DockStates - { - get - { - if (_dockStates == null) - { - _dockStates = new DockState[4]; - _dockStates[0] = DockState.DockLeftAutoHide; - _dockStates[1] = DockState.DockRightAutoHide; - _dockStates[2] = DockState.DockTopAutoHide; - _dockStates[3] = DockState.DockBottomAutoHide; - } - return _dockStates; - } - } - - internal static GraphicsPath GraphicsPath - { - get - { - if (_graphicsPath == null) - { - _graphicsPath = new GraphicsPath(); - } - - return _graphicsPath; - } - } - - #endregion - - #region Overrides - - protected override void OnPaint(PaintEventArgs e) - { - Graphics g = e.Graphics; - - Color startColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.StartColor; - Color endColor = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.EndColor; - LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.DockStripGradient.LinearGradientMode; - using (LinearGradientBrush brush = - new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) - { - g.FillRectangle(brush, ClientRectangle); - } - - DrawTabStrip(g); - } - - protected override void OnLayout(LayoutEventArgs levent) - { - CalculateTabs(); - base.OnLayout(levent); - } - - protected override IDockContent HitTest(Point ptMouse) - { - foreach (DockState state in DockStates) - { - Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); - if (!rectTabStrip.Contains(ptMouse)) - { - continue; - } - - foreach (Pane pane in GetPanes(state)) - { - foreach (TabVS2005 tab in pane.AutoHideTabs) - { - GraphicsPath path = GetTabOutline(tab, true, true); - if (path.IsVisible(ptMouse)) - { - return tab.Content; - } - } - } - } - - return null; - } - - protected internal override int MeasureHeight() - { - return Math.Max(ImageGapBottom + - ImageGapTop + ImageHeight, - TextFont.Height) + TabGapTop; - } - - protected override void OnRefreshChanges() - { - CalculateTabs(); - Invalidate(); - } - - protected override AutoHideStripBase.Tab CreateTab(IDockContent content) - { - return new TabVS2005(content); - } - - #endregion - - #region Private Methods - - private void DrawTabStrip(Graphics g) - { - DrawTabStrip(g, DockState.DockTopAutoHide); - DrawTabStrip(g, DockState.DockBottomAutoHide); - DrawTabStrip(g, DockState.DockLeftAutoHide); - DrawTabStrip(g, DockState.DockRightAutoHide); - } - - private void DrawTabStrip(Graphics g, DockState dockState) - { - Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); - - if (rectTabStrip.IsEmpty) - { - return; - } - - Matrix matrixIdentity = g.Transform; - if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) - { - Matrix matrixRotated = new Matrix(); - matrixRotated.RotateAt(90, new PointF((float) rectTabStrip.X + (float) rectTabStrip.Height / 2, - (float) rectTabStrip.Y + (float) rectTabStrip.Height / 2)); - g.Transform = matrixRotated; - } - - foreach (Pane pane in GetPanes(dockState)) - { - foreach (TabVS2005 tab in pane.AutoHideTabs) - { - DrawTab(g, tab); - } - } - g.Transform = matrixIdentity; - } - - private void CalculateTabs() - { - CalculateTabs(DockState.DockTopAutoHide); - CalculateTabs(DockState.DockBottomAutoHide); - CalculateTabs(DockState.DockLeftAutoHide); - CalculateTabs(DockState.DockRightAutoHide); - } - - private void CalculateTabs(DockState dockState) - { - Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); - - int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; - int imageWidth = ImageWidth; - if (imageHeight > ImageHeight) - { - imageWidth = ImageWidth * (imageHeight / ImageHeight); - } - - int x = TabGapLeft + rectTabStrip.X; - foreach (Pane pane in GetPanes(dockState)) - { - foreach (TabVS2005 tab in pane.AutoHideTabs) - { - int width = imageWidth + ImageGapLeft + ImageGapRight + - TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + - TextGapLeft + TextGapRight; - tab.TabX = x; - tab.TabWidth = width; - x += width; - } - - x += TabGapBetween; - } - } - - private Rectangle RtlTransform(Rectangle rect, DockState dockState) - { - Rectangle rectTransformed; - if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) - { - rectTransformed = rect; - } - else - { - rectTransformed = DrawHelper.RtlTransform(this, rect); - } - - return rectTransformed; - } - - private GraphicsPath GetTabOutline(TabVS2005 tab, bool transformed, bool rtlTransform) - { - DockState dockState = tab.Content.DockHandler.DockState; - Rectangle rectTab = GetTabRectangle(tab, transformed); - if (rtlTransform) - { - rectTab = RtlTransform(rectTab, dockState); - } - bool upTab = dockState == DockState.DockLeftAutoHide || dockState == DockState.DockBottomAutoHide; - DrawHelper.GetRoundedCornerTab(GraphicsPath, rectTab, upTab); - - return GraphicsPath; - } - - private void DrawTab(Graphics g, TabVS2005 tab) - { - Rectangle rectTabOrigin = GetTabRectangle(tab); - if (rectTabOrigin.IsEmpty) - { - return; - } - - DockState dockState = tab.Content.DockHandler.DockState; - IDockContent content = tab.Content; - - GraphicsPath path = GetTabOutline(tab, false, true); - - Color startColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.StartColor; - Color endColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.EndColor; - LinearGradientMode gradientMode = DockPanel.Skin.AutoHideStripSkin.TabGradient.LinearGradientMode; - g.FillPath(new LinearGradientBrush(rectTabOrigin, startColor, endColor, gradientMode), path); - g.DrawPath(PenTabBorder, path); - - // Set no rotate for drawing icon and text - Matrix matrixRotate = g.Transform; - g.Transform = MatrixIdentity; - - // Draw the icon - Rectangle rectImage = rectTabOrigin; - rectImage.X += ImageGapLeft; - rectImage.Y += ImageGapTop; - int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; - int imageWidth = ImageWidth; - if (imageHeight > ImageHeight) - { - imageWidth = ImageWidth * (imageHeight / ImageHeight); - } - rectImage.Height = imageHeight; - rectImage.Width = imageWidth; - rectImage = GetTransformedRectangle(dockState, rectImage); - - if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) - { - // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right. - Rectangle rectTransform = RtlTransform(rectImage, dockState); - Point[] rotationPoints = - { - new Point(rectTransform.X + rectTransform.Width, rectTransform.Y), - new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), - new Point(rectTransform.X, rectTransform.Y) - }; - - using (Icon rotatedIcon = new Icon(((Form) content).Icon, 16, 16)) - { - g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); - } - } - else - { - // Draw the icon normally without any rotation. - g.DrawIcon(((Form) content).Icon, RtlTransform(rectImage, dockState)); - } - - // Draw the text - Rectangle rectText = rectTabOrigin; - rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; - rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; - rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); - - Color textColor = DockPanel.Skin.AutoHideStripSkin.TabGradient.TextColor; - - if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) - { - g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, - StringFormatTabVertical); - } - else - { - g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, - StringFormatTabHorizontal); - } - - // Set rotate back - g.Transform = matrixRotate; - } - - private Rectangle GetLogicalTabStripRectangle(DockState dockState) - { - return GetLogicalTabStripRectangle(dockState, false); - } - - private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) - { - if (!DockHelper.IsDockStateAutoHide(dockState)) - { - return Rectangle.Empty; - } - - int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; - int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; - int topPanes = GetPanes(DockState.DockTopAutoHide).Count; - int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; - - int x, y, width, height; - - height = MeasureHeight(); - if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) - { - x = 0; - y = topPanes == 0 ? 0 : height; - width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); - } - else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) - { - x = Width - height; - if (leftPanes != 0 && x < height) - { - x = height; - } - y = topPanes == 0 ? 0 : height; - width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); - } - else if (dockState == DockState.DockTopAutoHide && topPanes > 0) - { - x = leftPanes == 0 ? 0 : height; - y = 0; - width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); - } - else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) - { - x = leftPanes == 0 ? 0 : height; - y = Height - height; - if (topPanes != 0 && y < height) - { - y = height; - } - width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); - } - else - { - return Rectangle.Empty; - } - - if (!transformed) - { - return new Rectangle(x, y, width, height); - } - else - { - return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); - } - } - - private Rectangle GetTabRectangle(TabVS2005 tab) - { - return GetTabRectangle(tab, false); - } - - private Rectangle GetTabRectangle(TabVS2005 tab, bool transformed) - { - DockState dockState = tab.Content.DockHandler.DockState; - Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); - - if (rectTabStrip.IsEmpty) - { - return Rectangle.Empty; - } - - int x = tab.TabX; - int y = rectTabStrip.Y + - (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide - ? 0 - : TabGapTop); - int width = tab.TabWidth; - int height = rectTabStrip.Height - TabGapTop; - - if (!transformed) - { - return new Rectangle(x, y, width, height); - } - else - { - return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); - } - } - - private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) - { - if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) - { - return rect; - } - - PointF[] pts = new PointF[1]; - // the center of the rectangle - pts[0].X = (float) rect.X + (float) rect.Width / 2; - pts[0].Y = (float) rect.Y + (float) rect.Height / 2; - Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); - Matrix matrix = new Matrix(); - matrix.RotateAt(90, new PointF((float) rectTabStrip.X + (float) rectTabStrip.Height / 2, - (float) rectTabStrip.Y + (float) rectTabStrip.Height / 2)); - matrix.TransformPoints(pts); - - return new Rectangle((int) (pts[0].X - (float) rect.Height / 2 + .5F), - (int) (pts[0].Y - (float) rect.Width / 2 + .5F), - rect.Height, rect.Width); - } - - #endregion - - private class TabVS2005 : Tab - { - #region Fields - - #endregion - - #region cTor - - internal TabVS2005(IDockContent content) - : base(content) - { - } - - #endregion - - #region Properties - - public int TabX { get; set; } = 0; - - public int TabWidth { get; set; } = 0; - - #endregion - } - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/VS2005DockPaneCaption.cs b/src/WinFormsUI/Docking/VS2005DockPaneCaption.cs deleted file mode 100644 index 04c283c4..00000000 --- a/src/WinFormsUI/Docking/VS2005DockPaneCaption.cs +++ /dev/null @@ -1,582 +0,0 @@ -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Windows.Forms; -using System.ComponentModel; -using System.Windows.Forms.VisualStyles; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal class VS2005DockPaneCaption : DockPaneCaptionBase - { - #region Fields - - private static Bitmap _imageButtonClose; - - private static Bitmap _imageButtonAutoHide; - - private static Bitmap _imageButtonDock; - - private static Bitmap _imageButtonOptions; - - private static string _toolTipClose; - - private static string _toolTipOptions; - - private static string _toolTipAutoHide; - - private static Blend _activeBackColorGradientBlend; - - private static readonly TextFormatFlags _textFormat = - TextFormatFlags.SingleLine | - TextFormatFlags.EndEllipsis | - TextFormatFlags.VerticalCenter; - - private InertButton m_buttonAutoHide; - - private InertButton m_buttonClose; - - private InertButton m_buttonOptions; - - private readonly ToolTip m_toolTip; - - #endregion - - #region cTor - - public VS2005DockPaneCaption(DockPane pane) : base(pane) - { - SuspendLayout(); - - Components = new Container(); - m_toolTip = new ToolTip(Components); - - ResumeLayout(); - } - - #endregion - - #region Properties - - private static Bitmap ImageButtonClose - { - get - { - if (_imageButtonClose == null) - { - _imageButtonClose = Resources.DockPane_Close; - } - - return _imageButtonClose; - } - } - - private InertButton ButtonClose - { - get - { - if (m_buttonClose == null) - { - m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose); - m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); - m_buttonClose.Click += new EventHandler(Close_Click); - Controls.Add(m_buttonClose); - } - - return m_buttonClose; - } - } - - private static Bitmap ImageButtonAutoHide - { - get - { - if (_imageButtonAutoHide == null) - { - _imageButtonAutoHide = Resources.DockPane_AutoHide; - } - - return _imageButtonAutoHide; - } - } - - private static Bitmap ImageButtonDock - { - get - { - if (_imageButtonDock == null) - { - _imageButtonDock = Resources.DockPane_Dock; - } - - return _imageButtonDock; - } - } - - private InertButton ButtonAutoHide - { - get - { - if (m_buttonAutoHide == null) - { - m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide); - m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide); - m_buttonAutoHide.Click += new EventHandler(AutoHide_Click); - Controls.Add(m_buttonAutoHide); - } - - return m_buttonAutoHide; - } - } - - private static Bitmap ImageButtonOptions - { - get - { - if (_imageButtonOptions == null) - { - _imageButtonOptions = Resources.DockPane_Option; - } - - return _imageButtonOptions; - } - } - - private InertButton ButtonOptions - { - get - { - if (m_buttonOptions == null) - { - m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions); - m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions); - m_buttonOptions.Click += new EventHandler(Options_Click); - Controls.Add(m_buttonOptions); - } - return m_buttonOptions; - } - } - - private IContainer Components { get; } - - private static int TextGapTop - { - get { return _TextGapTop; } - } - - public Font TextFont - { - get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } - } - - private static int TextGapBottom - { - get { return _TextGapBottom; } - } - - private static int TextGapLeft - { - get { return _TextGapLeft; } - } - - private static int TextGapRight - { - get { return _TextGapRight; } - } - - private static int ButtonGapTop - { - get { return _ButtonGapTop; } - } - - private static int ButtonGapBottom - { - get { return _ButtonGapBottom; } - } - - private static int ButtonGapLeft - { - get { return _ButtonGapLeft; } - } - - private static int ButtonGapRight - { - get { return _ButtonGapRight; } - } - - private static int ButtonGapBetween - { - get { return _ButtonGapBetween; } - } - - private static string ToolTipClose - { - get - { - if (_toolTipClose == null) - { - _toolTipClose = Strings.DockPaneCaption_ToolTipClose; - } - return _toolTipClose; - } - } - - private static string ToolTipOptions - { - get - { - if (_toolTipOptions == null) - { - _toolTipOptions = Strings.DockPaneCaption_ToolTipOptions; - } - - return _toolTipOptions; - } - } - - private static string ToolTipAutoHide - { - get - { - if (_toolTipAutoHide == null) - { - _toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide; - } - return _toolTipAutoHide; - } - } - - private static Blend ActiveBackColorGradientBlend - { - get - { - if (_activeBackColorGradientBlend == null) - { - Blend blend = new Blend(2); - - blend.Factors = new float[] {0.5F, 1.0F}; - blend.Positions = new float[] {0.0F, 1.0F}; - _activeBackColorGradientBlend = blend; - } - - return _activeBackColorGradientBlend; - } - } - - private Color TextColor - { - get - { - if (DockPane.IsActivated) - { - return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; - } - else - { - return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient - .TextColor; - } - } - } - - private TextFormatFlags TextFormat - { - get - { - if (RightToLeft == RightToLeft.No) - { - return _textFormat; - } - else - { - return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; - } - } - } - - private bool CloseButtonEnabled - { - get { return DockPane.ActiveContent != null ? DockPane.ActiveContent.DockHandler.CloseButton : false; } - } - - /// - /// Determines whether the close button is visible on the content - /// - private bool CloseButtonVisible - { - get - { - return DockPane.ActiveContent != null ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; - } - } - - private bool ShouldShowAutoHideButton - { - get { return !DockPane.IsFloat; } - } - - #endregion - - #region Overrides - - protected override void Dispose(bool disposing) - { - if (disposing) - { - Components.Dispose(); - } - base.Dispose(disposing); - } - - protected internal override int MeasureHeight() - { - int height = TextFont.Height + TextGapTop + TextGapBottom; - - if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom) - { - height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom; - } - - return height; - } - - protected override void OnPaint(PaintEventArgs e) - { - base.OnPaint(e); - DrawCaption(e.Graphics); - } - - protected override void OnLayout(LayoutEventArgs levent) - { - SetButtonsPosition(); - base.OnLayout(levent); - } - - protected override void OnRefreshChanges() - { - SetButtons(); - Invalidate(); - } - - protected override void OnRightToLeftChanged(EventArgs e) - { - base.OnRightToLeftChanged(e); - PerformLayout(); - } - - #endregion - - #region Private Methods - - private void DrawCaption(Graphics g) - { - if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) - { - return; - } - - if (DockPane.IsActivated) - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient - .EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient - .ActiveCaptionGradient.LinearGradientMode; - using (LinearGradientBrush brush = - new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) - { - brush.Blend = ActiveBackColorGradientBlend; - g.FillRectangle(brush, ClientRectangle); - } - } - else - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient - .EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient - .InactiveCaptionGradient.LinearGradientMode; - using (LinearGradientBrush brush = - new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) - { - g.FillRectangle(brush, ClientRectangle); - } - } - - Rectangle rectCaption = ClientRectangle; - - Rectangle rectCaptionText = rectCaption; - rectCaptionText.X += TextGapLeft; - rectCaptionText.Width -= TextGapLeft + TextGapRight; - rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; - if (ShouldShowAutoHideButton) - { - rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; - } - if (HasTabPageContextMenu) - { - rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; - } - rectCaptionText.Y += TextGapTop; - rectCaptionText.Height -= TextGapTop + TextGapBottom; - - Color colorText; - if (DockPane.IsActivated) - { - colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient - .TextColor; - } - else - { - colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient - .TextColor; - } - - TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), - colorText, TextFormat); - } - - private void SetButtons() - { - ButtonClose.Enabled = CloseButtonEnabled; - ButtonClose.Visible = CloseButtonVisible; - ButtonAutoHide.Visible = ShouldShowAutoHideButton; - ButtonOptions.Visible = HasTabPageContextMenu; - ButtonClose.RefreshChanges(); - ButtonAutoHide.RefreshChanges(); - ButtonOptions.RefreshChanges(); - - SetButtonsPosition(); - } - - private void SetButtonsPosition() - { - // set the size and location for close and auto-hide buttons - Rectangle rectCaption = ClientRectangle; - int buttonWidth = ButtonClose.Image.Width; - int buttonHeight = ButtonClose.Image.Height; - int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; - if (buttonHeight < height) - { - buttonWidth = buttonWidth * (height / buttonHeight); - buttonHeight = height; - } - Size buttonSize = new Size(buttonWidth, buttonHeight); - int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; - int y = rectCaption.Y + ButtonGapTop; - Point point = new Point(x, y); - ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); - - // If the close button is not visible draw the auto hide button overtop. - // Otherwise it is drawn to the left of the close button. - if (CloseButtonVisible) - { - point.Offset(-(buttonWidth + ButtonGapBetween), 0); - } - - ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); - if (ShouldShowAutoHideButton) - { - point.Offset(-(buttonWidth + ButtonGapBetween), 0); - } - ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); - } - - #endregion - - #region Events handler - - private void Close_Click(object sender, EventArgs e) - { - DockPane.CloseActiveContent(); - } - - private void AutoHide_Click(object sender, EventArgs e) - { - DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); - if (DockHelper.IsDockStateAutoHide(DockPane.DockState)) - { - DockPane.DockPanel.ActiveAutoHideContent = null; - DockPane.NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(DockPane); - } - } - - private void Options_Click(object sender, EventArgs e) - { - ShowTabPageContextMenu(PointToClient(Control.MousePosition)); - } - - #endregion - - private sealed class InertButton : InertButtonBase - { - #region Fields - - private readonly Bitmap m_image; - private readonly Bitmap m_imageAutoHide; - - #endregion - - #region cTor - - public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide) - : base() - { - DockPaneCaption = dockPaneCaption; - m_image = image; - m_imageAutoHide = imageAutoHide; - RefreshChanges(); - } - - #endregion - - #region Properties - - private VS2005DockPaneCaption DockPaneCaption { get; } - - public bool IsAutoHide - { - get { return DockPaneCaption.DockPane.IsAutoHide; } - } - - public override Bitmap Image - { - get { return IsAutoHide ? m_imageAutoHide : m_image; } - } - - #endregion - - #region Overrides - - protected override void OnRefreshChanges() - { - if (DockPaneCaption.DockPane.DockPanel != null) - { - if (DockPaneCaption.TextColor != ForeColor) - { - ForeColor = DockPaneCaption.TextColor; - Invalidate(); - } - } - } - - #endregion - } - - #region consts - - private const int _TextGapTop = 2; - private const int _TextGapBottom = 0; - private const int _TextGapLeft = 3; - private const int _TextGapRight = 3; - private const int _ButtonGapTop = 2; - private const int _ButtonGapBottom = 1; - private const int _ButtonGapBetween = 1; - private const int _ButtonGapLeft = 1; - private const int _ButtonGapRight = 2; - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/VS2005DockPaneStrip.cs b/src/WinFormsUI/Docking/VS2005DockPaneStrip.cs deleted file mode 100644 index 27885e55..00000000 --- a/src/WinFormsUI/Docking/VS2005DockPaneStrip.cs +++ /dev/null @@ -1,1707 +0,0 @@ -using System; -using System.Drawing; -using System.Drawing.Drawing2D; -using System.Windows.Forms; -using System.ComponentModel; -using System.Collections; -using System.Collections.Generic; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal class VS2005DockPaneStrip : DockPaneStripBase - { - #region cTor - - public VS2005DockPaneStrip(DockPane pane) - : base(pane) - { - SetStyle(ControlStyles.ResizeRedraw | - ControlStyles.UserPaint | - ControlStyles.AllPaintingInWmPaint | - ControlStyles.OptimizedDoubleBuffer, true); - - SuspendLayout(); - - Components = new Container(); - m_toolTip = new ToolTip(Components); - SelectMenu = new ContextMenuStrip(Components); - - ResumeLayout(); - } - - #endregion - - #region Properties - - private Rectangle TabStripRectangle - { - get - { - if (Appearance == DockPane.AppearanceStyle.Document) - { - return TabStripRectangle_Document; - } - else - { - return TabStripRectangle_ToolWindow; - } - } - } - - private Rectangle TabStripRectangle_ToolWindow - { - get - { - Rectangle rect = ClientRectangle; - return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, - rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); - } - } - - private Rectangle TabStripRectangle_Document - { - get - { - Rectangle rect = ClientRectangle; - return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, - rect.Height - DocumentStripGapTop - ToolWindowStripGapBottom); - } - } - - private Rectangle TabsRectangle - { - get - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - return TabStripRectangle; - } - - Rectangle rectWindow = TabStripRectangle; - int x = rectWindow.X; - int y = rectWindow.Y; - int width = rectWindow.Width; - int height = rectWindow.Height; - - x += DocumentTabGapLeft; - width -= DocumentTabGapLeft + - DocumentTabGapRight + - DocumentButtonGapRight + - ButtonClose.Width + - ButtonWindowList.Width + - 2 * DocumentButtonGapBetween; - - return new Rectangle(x, y, width, height); - } - } - - private ContextMenuStrip SelectMenu { get; } - - private static Bitmap ImageButtonClose - { - get - { - if (m_imageButtonClose == null) - { - m_imageButtonClose = Resources.DockPane_Close; - } - - return m_imageButtonClose; - } - } - - private InertButton ButtonClose - { - get - { - if (m_buttonClose == null) - { - m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); - m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); - m_buttonClose.Click += new EventHandler(Close_Click); - Controls.Add(m_buttonClose); - } - - return m_buttonClose; - } - } - - private static Bitmap ImageButtonWindowList - { - get - { - if (m_imageButtonWindowList == null) - { - m_imageButtonWindowList = Resources.DockPane_Option; - } - - return m_imageButtonWindowList; - } - } - - private static Bitmap ImageButtonWindowListOverflow - { - get - { - if (m_imageButtonWindowListOverflow == null) - { - m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; - } - - return m_imageButtonWindowListOverflow; - } - } - - private InertButton ButtonWindowList - { - get - { - if (m_buttonWindowList == null) - { - m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); - m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); - m_buttonWindowList.Click += new EventHandler(WindowList_Click); - Controls.Add(m_buttonWindowList); - } - - return m_buttonWindowList; - } - } - - private static GraphicsPath GraphicsPath - { - get { return VS2005AutoHideStrip.GraphicsPath; } - } - - private IContainer Components { get; } - - public Font TextFont - { - get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } - } - - private Font BoldFont - { - get - { - if (IsDisposed) - { - return null; - } - - if (m_boldFont == null) - { - m_font = TextFont; - m_boldFont = new Font(TextFont, FontStyle.Bold); - } - else if (m_font != TextFont) - { - m_boldFont.Dispose(); - m_font = TextFont; - m_boldFont = new Font(TextFont, FontStyle.Bold); - } - - return m_boldFont; - } - } - - private int StartDisplayingTab - { - get { return m_startDisplayingTab; } - set - { - m_startDisplayingTab = value; - Invalidate(); - } - } - - private int EndDisplayingTab { get; set; } = 0; - - private int FirstDisplayingTab { get; set; } = 0; - - private bool DocumentTabsOverflow - { - set - { - if (m_documentTabsOverflow == value) - { - return; - } - - m_documentTabsOverflow = value; - if (value) - { - ButtonWindowList.ImageCategory = 1; - } - else - { - ButtonWindowList.ImageCategory = 0; - } - } - } - - private static int ToolWindowStripGapTop - { - get { return _ToolWindowStripGapTop; } - } - - private static int ToolWindowStripGapBottom - { - get { return _ToolWindowStripGapBottom; } - } - - private static int ToolWindowStripGapLeft - { - get { return _ToolWindowStripGapLeft; } - } - - private static int ToolWindowStripGapRight - { - get { return _ToolWindowStripGapRight; } - } - - private static int ToolWindowImageHeight - { - get { return _ToolWindowImageHeight; } - } - - private static int ToolWindowImageWidth - { - get { return _ToolWindowImageWidth; } - } - - private static int ToolWindowImageGapTop - { - get { return _ToolWindowImageGapTop; } - } - - private static int ToolWindowImageGapBottom - { - get { return _ToolWindowImageGapBottom; } - } - - private static int ToolWindowImageGapLeft - { - get { return _ToolWindowImageGapLeft; } - } - - private static int ToolWindowImageGapRight - { - get { return _ToolWindowImageGapRight; } - } - - private static int ToolWindowTextGapRight - { - get { return _ToolWindowTextGapRight; } - } - - private static int ToolWindowTabSeperatorGapTop - { - get { return _ToolWindowTabSeperatorGapTop; } - } - - private static int ToolWindowTabSeperatorGapBottom - { - get { return _ToolWindowTabSeperatorGapBottom; } - } - - private static string ToolTipClose - { - get - { - if (m_toolTipClose == null) - { - m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; - } - return m_toolTipClose; - } - } - - private static string ToolTipSelect - { - get - { - if (m_toolTipSelect == null) - { - m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; - } - return m_toolTipSelect; - } - } - - private TextFormatFlags ToolWindowTextFormat - { - get - { - TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | - TextFormatFlags.HorizontalCenter | - TextFormatFlags.SingleLine | - TextFormatFlags.VerticalCenter; - if (RightToLeft == RightToLeft.Yes) - { - return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; - } - else - { - return textFormat; - } - } - } - - private static int DocumentStripGapTop - { - get { return _DocumentStripGapTop; } - } - - private static int DocumentStripGapBottom - { - get { return _DocumentStripGapBottom; } - } - - private TextFormatFlags DocumentTextFormat - { - get - { - TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | - TextFormatFlags.SingleLine | - TextFormatFlags.VerticalCenter | - TextFormatFlags.HorizontalCenter; - if (RightToLeft == RightToLeft.Yes) - { - return textFormat | TextFormatFlags.RightToLeft; - } - else - { - return textFormat; - } - } - } - - private static int DocumentTabMaxWidth - { - get { return _DocumentTabMaxWidth; } - } - - private static int DocumentButtonGapTop - { - get { return _DocumentButtonGapTop; } - } - - private static int DocumentButtonGapBottom - { - get { return _DocumentButtonGapBottom; } - } - - private static int DocumentButtonGapBetween - { - get { return _DocumentButtonGapBetween; } - } - - private static int DocumentButtonGapRight - { - get { return _DocumentButtonGapRight; } - } - - private static int DocumentTabGapTop - { - get { return _DocumentTabGapTop; } - } - - private static int DocumentTabGapLeft - { - get { return _DocumentTabGapLeft; } - } - - private static int DocumentTabGapRight - { - get { return _DocumentTabGapRight; } - } - - private static int DocumentIconGapBottom - { - get { return _DocumentIconGapBottom; } - } - - private static int DocumentIconGapLeft - { - get { return _DocumentIconGapLeft; } - } - - private static int DocumentIconGapRight - { - get { return _DocumentIconGapRight; } - } - - private static int DocumentIconWidth - { - get { return _DocumentIconWidth; } - } - - private static int DocumentIconHeight - { - get { return _DocumentIconHeight; } - } - - private static int DocumentTextGapRight - { - get { return _DocumentTextGapRight; } - } - - private static Pen PenToolWindowTabBorder - { - get { return SystemPens.GrayText; } - } - - private static Pen PenDocumentTabActiveBorder - { - get { return SystemPens.ControlDarkDark; } - } - - private static Pen PenDocumentTabInactiveBorder - { - get { return SystemPens.GrayText; } - } - - #endregion - - #region Overrides - - protected internal override DockPaneStripBase.Tab CreateTab(IDockContent content) - { - return new TabVS2005(content); - } - - protected override void Dispose(bool disposing) - { - if (disposing) - { - Components.Dispose(); - if (m_boldFont != null) - { - m_boldFont.Dispose(); - m_boldFont = null; - } - } - base.Dispose(disposing); - } - - protected internal override int MeasureHeight() - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - return MeasureHeight_ToolWindow(); - } - else - { - return MeasureHeight_Document(); - } - } - - protected override void OnPaint(PaintEventArgs e) - { - Rectangle rect = TabsRectangle; - - if (Appearance == DockPane.AppearanceStyle.Document) - { - rect.X -= DocumentTabGapLeft; - - // Add these values back in so that the DockStrip color is drawn - // beneath the close button and window list button. - rect.Width += DocumentTabGapLeft + - DocumentTabGapRight + - DocumentButtonGapRight + - ButtonClose.Width + - ButtonWindowList.Width; - - // It is possible depending on the DockPanel DocumentStyle to have - // a Document without a DockStrip. - if (rect.Width > 0 && rect.Height > 0) - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient - .EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient - .DockStripGradient.LinearGradientMode; - using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode) - ) - { - e.Graphics.FillRectangle(brush, rect); - } - } - } - else - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient - .EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient - .DockStripGradient.LinearGradientMode; - using (LinearGradientBrush brush = new LinearGradientBrush(rect, startColor, endColor, gradientMode)) - { - e.Graphics.FillRectangle(brush, rect); - } - } - base.OnPaint(e); - CalculateTabs(); - if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) - { - if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) - { - CalculateTabs(); - } - } - - DrawTabStrip(e.Graphics); - } - - protected override void OnRefreshChanges() - { - SetInertButtons(); - Invalidate(); - } - - protected internal override GraphicsPath GetOutline(int index) - { - if (Appearance == DockPane.AppearanceStyle.Document) - { - return GetOutline_Document(index); - } - else - { - return GetOutline_ToolWindow(index); - } - } - - protected internal override void EnsureTabVisible(IDockContent content) - { - if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) - { - return; - } - - CalculateTabs(); - EnsureDocumentTabVisible(content, true); - } - - protected override void OnLayout(LayoutEventArgs levent) - { - if (Appearance == DockPane.AppearanceStyle.Document) - { - LayoutButtons(); - OnRefreshChanges(); - } - - base.OnLayout(levent); - } - - protected internal override int HitTest(Point ptMouse) - { - if (!TabsRectangle.Contains(ptMouse)) - { - return -1; - } - - foreach (Tab tab in Tabs) - { - GraphicsPath path = GetTabOutline(tab, true, false); - if (path.IsVisible(ptMouse)) - { - return Tabs.IndexOf(tab); - } - } - return -1; - } - - protected override void OnMouseHover(EventArgs e) - { - int index = HitTest(PointToClient(Control.MousePosition)); - string toolTip = string.Empty; - - base.OnMouseHover(e); - - if (index != -1) - { - TabVS2005 tab = Tabs[index] as TabVS2005; - if (!string.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) - { - toolTip = tab.Content.DockHandler.ToolTipText; - } - else if (tab.MaxWidth > tab.TabWidth) - { - toolTip = tab.Content.DockHandler.TabText; - } - } - - if (m_toolTip.GetToolTip(this) != toolTip) - { - m_toolTip.Active = false; - m_toolTip.SetToolTip(this, toolTip); - m_toolTip.Active = true; - } - - // requires further tracking of mouse hover behavior, - ResetMouseEventArgs(); - } - - protected override void OnRightToLeftChanged(EventArgs e) - { - base.OnRightToLeftChanged(e); - PerformLayout(); - } - - #endregion - - #region Private Methods - - private int MeasureHeight_ToolWindow() - { - if (DockPane.IsAutoHide || Tabs.Count <= 1) - { - return 0; - } - - int height = Math.Max(TextFont.Height, - ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) - + ToolWindowStripGapTop + ToolWindowStripGapBottom; - - return height; - } - - private int MeasureHeight_Document() - { - int height = Math.Max(TextFont.Height + DocumentTabGapTop, - ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) - + DocumentStripGapBottom + DocumentStripGapTop; - - return height; - } - - private GraphicsPath GetOutline_Document(int index) - { - Rectangle rectTab = GetTabRectangle(index); - rectTab.X -= rectTab.Height / 2; - rectTab.Intersect(TabsRectangle); - rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); - Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); - - GraphicsPath path = new GraphicsPath(); - GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); - path.AddPath(pathTab, true); - - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); - path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); - path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); - path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); - path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); - } - else - { - path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); - path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); - path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); - path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); - path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); - } - return path; - } - - private GraphicsPath GetOutline_ToolWindow(int index) - { - Rectangle rectTab = GetTabRectangle(index); - rectTab.Intersect(TabsRectangle); - rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); - Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); - - GraphicsPath path = new GraphicsPath(); - GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); - path.AddPath(pathTab, true); - path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); - path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); - path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); - path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); - path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); - return path; - } - - private void CalculateTabs() - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - CalculateTabs_ToolWindow(); - } - else - { - CalculateTabs_Document(); - } - } - - private void CalculateTabs_ToolWindow() - { - if (Tabs.Count <= 1 || DockPane.IsAutoHide) - { - return; - } - - Rectangle rectTabStrip = TabStripRectangle; - - // Calculate tab widths - int countTabs = Tabs.Count; - foreach (TabVS2005 tab in Tabs) - { - tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); - tab.Flag = false; - } - - // Set tab whose max width less than average width - bool anyWidthWithinAverage = true; - int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; - int totalAllocatedWidth = 0; - int averageWidth = totalWidth / countTabs; - int remainedTabs = countTabs; - for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0;) - { - anyWidthWithinAverage = false; - foreach (TabVS2005 tab in Tabs) - { - if (tab.Flag) - { - continue; - } - - if (tab.MaxWidth <= averageWidth) - { - tab.Flag = true; - tab.TabWidth = tab.MaxWidth; - totalAllocatedWidth += tab.TabWidth; - anyWidthWithinAverage = true; - remainedTabs--; - } - } - if (remainedTabs != 0) - { - averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; - } - } - - // If any tab width not set yet, set it to the average width - if (remainedTabs > 0) - { - int roundUpWidth = totalWidth - totalAllocatedWidth - averageWidth * remainedTabs; - foreach (TabVS2005 tab in Tabs) - { - if (tab.Flag) - { - continue; - } - - tab.Flag = true; - if (roundUpWidth > 0) - { - tab.TabWidth = averageWidth + 1; - roundUpWidth--; - } - else - { - tab.TabWidth = averageWidth; - } - } - } - - // Set the X position of the tabs - int x = rectTabStrip.X + ToolWindowStripGapLeft; - foreach (TabVS2005 tab in Tabs) - { - tab.TabX = x; - x += tab.TabWidth; - } - } - - private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) - { - bool overflow = false; - - TabVS2005 tab = Tabs[index] as TabVS2005; - tab.MaxWidth = GetMaxTabWidth(index); - int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); - if (x + width < rectTabStrip.Right || index == StartDisplayingTab) - { - tab.TabX = x; - tab.TabWidth = width; - EndDisplayingTab = index; - } - else - { - tab.TabX = 0; - tab.TabWidth = 0; - overflow = true; - } - x += width; - - return overflow; - } - - /// - /// Calculate which tabs are displayed and in what order. - /// - private void CalculateTabs_Document() - { - if (m_startDisplayingTab >= Tabs.Count) - { - m_startDisplayingTab = 0; - } - - Rectangle rectTabStrip = TabsRectangle; - - int x = rectTabStrip.X + rectTabStrip.Height / 2; - bool overflow = false; - - // Originally all new documents that were considered overflow - // (not enough pane strip space to show all tabs) were added to - // the far left (assuming not right to left) and the tabs on the - // right were dropped from view. If StartDisplayingTab is not 0 - // then we are dealing with making sure a specific tab is kept in focus. - if (m_startDisplayingTab > 0) - { - int tempX = x; - TabVS2005 tab = Tabs[m_startDisplayingTab] as TabVS2005; - tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); - - // Add the active tab and tabs to the left - for (int i = StartDisplayingTab; i >= 0; i--) - { - CalculateDocumentTab(rectTabStrip, ref tempX, i); - } - - // Store which tab is the first one displayed so that it - // will be drawn correctly (without part of the tab cut off) - FirstDisplayingTab = EndDisplayingTab; - - tempX = x; // Reset X location because we are starting over - - // Start with the first tab displayed - name is a little misleading. - // Loop through each tab and set its location. If there is not enough - // room for all of them overflow will be returned. - for (int i = EndDisplayingTab; i < Tabs.Count; i++) - { - overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); - } - - // If not all tabs are shown then we have an overflow. - if (FirstDisplayingTab != 0) - { - overflow = true; - } - } - else - { - for (int i = StartDisplayingTab; i < Tabs.Count; i++) - { - overflow = CalculateDocumentTab(rectTabStrip, ref x, i); - } - for (int i = 0; i < StartDisplayingTab; i++) - { - overflow = CalculateDocumentTab(rectTabStrip, ref x, i); - } - - FirstDisplayingTab = StartDisplayingTab; - } - - if (!overflow) - { - m_startDisplayingTab = 0; - FirstDisplayingTab = 0; - x = rectTabStrip.X + rectTabStrip.Height / 2; - foreach (TabVS2005 tab in Tabs) - { - tab.TabX = x; - x += tab.TabWidth; - } - } - DocumentTabsOverflow = overflow; - } - - private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) - { - int index = Tabs.IndexOf(content); - TabVS2005 tab = Tabs[index] as TabVS2005; - if (tab.TabWidth != 0) - { - return false; - } - - StartDisplayingTab = index; - if (repaint) - { - Invalidate(); - } - - return true; - } - - private int GetMaxTabWidth(int index) - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - return GetMaxTabWidth_ToolWindow(index); - } - else - { - return GetMaxTabWidth_Document(index); - } - } - - private int GetMaxTabWidth_ToolWindow(int index) - { - IDockContent content = Tabs[index].Content; - Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); - return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft - + ToolWindowImageGapRight + ToolWindowTextGapRight; - } - - private int GetMaxTabWidth_Document(int index) - { - IDockContent content = Tabs[index].Content; - - int height = GetTabRectangle_Document(index).Height; - - Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, - new Size(DocumentTabMaxWidth, height), DocumentTextFormat); - - if (DockPane.DockPanel.ShowDocumentIcon) - { - return sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + - DocumentTextGapRight; - } - else - { - return sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; - } - } - - private void DrawTabStrip(Graphics g) - { - if (Appearance == DockPane.AppearanceStyle.Document) - { - DrawTabStrip_Document(g); - } - else - { - DrawTabStrip_ToolWindow(g); - } - } - - private void DrawTabStrip_Document(Graphics g) - { - int count = Tabs.Count; - if (count == 0) - { - return; - } - - Rectangle rectTabStrip = TabStripRectangle; - - // Draw the tabs - Rectangle rectTabOnly = TabsRectangle; - Rectangle rectTab = Rectangle.Empty; - TabVS2005 tabActive = null; - g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); - for (int i = 0; i < count; i++) - { - rectTab = GetTabRectangle(i); - if (Tabs[i].Content == DockPane.ActiveContent) - { - tabActive = Tabs[i] as TabVS2005; - continue; - } - if (rectTab.IntersectsWith(rectTabOnly)) - { - DrawTab(g, Tabs[i] as TabVS2005, rectTab); - } - } - - g.SetClip(rectTabStrip); - - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, - rectTabStrip.Right, rectTabStrip.Top + 1); - } - else - { - g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Bottom - 1, - rectTabStrip.Right, rectTabStrip.Bottom - 1); - } - - g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); - if (tabActive != null) - { - rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); - if (rectTab.IntersectsWith(rectTabOnly)) - { - DrawTab(g, tabActive, rectTab); - } - } - } - - private void DrawTabStrip_ToolWindow(Graphics g) - { - Rectangle rectTabStrip = TabStripRectangle; - - g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, - rectTabStrip.Right, rectTabStrip.Top); - - for (int i = 0; i < Tabs.Count; i++) - { - DrawTab(g, Tabs[i] as TabVS2005, GetTabRectangle(i)); - } - } - - private Rectangle GetTabRectangle(int index) - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - return GetTabRectangle_ToolWindow(index); - } - else - { - return GetTabRectangle_Document(index); - } - } - - private Rectangle GetTabRectangle_ToolWindow(int index) - { - Rectangle rectTabStrip = TabStripRectangle; - - TabVS2005 tab = (TabVS2005) Tabs[index]; - return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); - } - - private Rectangle GetTabRectangle_Document(int index) - { - Rectangle rectTabStrip = TabStripRectangle; - TabVS2005 tab = (TabVS2005) Tabs[index]; - - Rectangle rect = new Rectangle(); - rect.X = tab.TabX; - rect.Width = tab.TabWidth; - rect.Height = rectTabStrip.Height - DocumentTabGapTop; - - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - rect.Y = rectTabStrip.Y + DocumentStripGapBottom; - } - else - { - rect.Y = rectTabStrip.Y + DocumentTabGapTop; - } - - return rect; - } - - private void DrawTab(Graphics g, TabVS2005 tab, Rectangle rect) - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - DrawTab_ToolWindow(g, tab, rect); - } - else - { - DrawTab_Document(g, tab, rect); - } - } - - private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); - } - else - { - return GetTabOutline_Document(tab, rtlTransform, toScreen, false); - } - } - - private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) - { - Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); - if (rtlTransform) - { - rect = DrawHelper.RtlTransform(this, rect); - } - if (toScreen) - { - rect = RectangleToScreen(rect); - } - - DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); - return GraphicsPath; - } - - private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) - { - int curveSize = 6; - - GraphicsPath.Reset(); - Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); - if (rtlTransform) - { - rect = DrawHelper.RtlTransform(this, rect); - } - if (toScreen) - { - rect = RectangleToScreen(rect); - } - - // Draws the full angle piece for active content (or first tab) - if (tab.Content == DockPane.ActiveContent || full || Tabs.IndexOf(tab) == FirstDisplayingTab) - { - if (RightToLeft == RightToLeft.Yes) - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. - // It is not needed so it has been commented out. - //GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); - GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Top, - rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); - } - else - { - GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right + rect.Height / 2, rect.Bottom); - GraphicsPath.AddLine(rect.Right + rect.Height / 2, rect.Bottom, - rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); - } - } - else - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - // For some reason the next line draws a line that is not hidden like it is when drawing the tab strip on top. - // It is not needed so it has been commented out. - //GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left - rect.Height / 2, rect.Top); - GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Top, - rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); - } - else - { - GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left - rect.Height / 2, rect.Bottom); - GraphicsPath.AddLine(rect.Left - rect.Height / 2, rect.Bottom, - rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); - } - } - } - // Draws the partial angle for non-active content - else - { - if (RightToLeft == RightToLeft.Yes) - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - GraphicsPath.AddLine(rect.Right, rect.Top, rect.Right, rect.Top + rect.Height / 2); - GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, - rect.Right - rect.Height / 2 + curveSize / 2, rect.Bottom - curveSize / 2); - } - else - { - GraphicsPath.AddLine(rect.Right, rect.Bottom, rect.Right, rect.Bottom - rect.Height / 2); - GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, - rect.Right - rect.Height / 2 + curveSize / 2, rect.Top + curveSize / 2); - } - } - else - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - GraphicsPath.AddLine(rect.Left, rect.Top, rect.Left, rect.Top + rect.Height / 2); - GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, - rect.Left + rect.Height / 2 - curveSize / 2, rect.Bottom - curveSize / 2); - } - else - { - GraphicsPath.AddLine(rect.Left, rect.Bottom, rect.Left, rect.Bottom - rect.Height / 2); - GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, - rect.Left + rect.Height / 2 - curveSize / 2, rect.Top + curveSize / 2); - } - } - } - - if (RightToLeft == RightToLeft.Yes) - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - // Draws the bottom horizontal line (short side) - GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Bottom, - rect.Left + curveSize / 2, rect.Bottom); - - // Drawing the rounded corner is not necessary. The path is automatically connected - //GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); - } - else - { - // Draws the bottom horizontal line (short side) - GraphicsPath.AddLine(rect.Right - rect.Height / 2 - curveSize / 2, rect.Top, - rect.Left + curveSize / 2, rect.Top); - GraphicsPath.AddArc(new Rectangle(rect.Left, rect.Top, curveSize, curveSize), 180, 90); - } - } - else - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - // Draws the bottom horizontal line (short side) - GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Bottom, - rect.Right - curveSize / 2, rect.Bottom); - - // Drawing the rounded corner is not necessary. The path is automatically connected - //GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Bottom, curveSize, curveSize), 90, -90); - } - else - { - // Draws the top horizontal line (short side) - GraphicsPath.AddLine(rect.Left + rect.Height / 2 + curveSize / 2, rect.Top, - rect.Right - curveSize / 2, rect.Top); - - // Draws the rounded corner oppposite the angled side - GraphicsPath.AddArc(new Rectangle(rect.Right - curveSize, rect.Top, curveSize, curveSize), -90, 90); - } - } - - if (Tabs.IndexOf(tab) != EndDisplayingTab && Tabs.IndexOf(tab) != Tabs.Count - 1 && - Tabs[Tabs.IndexOf(tab) + 1].Content == DockPane.ActiveContent && !full) - { - if (RightToLeft == RightToLeft.Yes) - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, - rect.Bottom - rect.Height / 2); - GraphicsPath.AddLine(rect.Left, rect.Bottom - rect.Height / 2, rect.Left + rect.Height / 2, - rect.Top); - } - else - { - GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, - rect.Top + rect.Height / 2); - GraphicsPath.AddLine(rect.Left, rect.Top + rect.Height / 2, rect.Left + rect.Height / 2, - rect.Bottom); - } - } - else - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, - rect.Bottom - rect.Height / 2); - GraphicsPath.AddLine(rect.Right, rect.Bottom - rect.Height / 2, rect.Right - rect.Height / 2, - rect.Top); - } - else - { - GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, - rect.Top + rect.Height / 2); - GraphicsPath.AddLine(rect.Right, rect.Top + rect.Height / 2, rect.Right - rect.Height / 2, - rect.Bottom); - } - } - } - else - { - // Draw the vertical line opposite the angled side - if (RightToLeft == RightToLeft.Yes) - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - GraphicsPath.AddLine(rect.Left, rect.Bottom - curveSize / 2, rect.Left, rect.Top); - } - else - { - GraphicsPath.AddLine(rect.Left, rect.Top + curveSize / 2, rect.Left, rect.Bottom); - } - } - else - { - if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) - { - GraphicsPath.AddLine(rect.Right, rect.Bottom - curveSize / 2, rect.Right, rect.Top); - } - else - { - GraphicsPath.AddLine(rect.Right, rect.Top + curveSize / 2, rect.Right, rect.Bottom); - } - } - } - - return GraphicsPath; - } - - private void DrawTab_ToolWindow(Graphics g, TabVS2005 tab, Rectangle rect) - { - Rectangle rectIcon = new Rectangle( - rect.X + ToolWindowImageGapLeft, - rect.Y + rect.Height - 1 - ToolWindowImageGapBottom - ToolWindowImageHeight, - ToolWindowImageWidth, ToolWindowImageHeight); - Rectangle rectText = rectIcon; - rectText.X += rectIcon.Width + ToolWindowImageGapRight; - rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - - ToolWindowImageGapRight - ToolWindowTextGapRight; - - Rectangle rectTab = DrawHelper.RtlTransform(this, rect); - rectText = DrawHelper.RtlTransform(this, rectText); - rectIcon = DrawHelper.RtlTransform(this, rectIcon); - GraphicsPath path = GetTabOutline(tab, true, false); - if (DockPane.ActiveContent == tab.Content) - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient - .EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient - .ActiveTabGradient.LinearGradientMode; - g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); - g.DrawPath(PenToolWindowTabBorder, path); - - Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient - .TextColor; - TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, - ToolWindowTextFormat); - } - else - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient - .EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient - .InactiveTabGradient.LinearGradientMode; - g.FillPath(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), path); - - if (Tabs.IndexOf(DockPane.ActiveContent) != Tabs.IndexOf(tab) + 1) - { - Point pt1 = new Point(rect.Right, rect.Top + ToolWindowTabSeperatorGapTop); - Point pt2 = new Point(rect.Right, rect.Bottom - ToolWindowTabSeperatorGapBottom); - g.DrawLine(PenToolWindowTabBorder, DrawHelper.RtlTransform(this, pt1), - DrawHelper.RtlTransform(this, pt2)); - } - - Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient - .TextColor; - TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, - ToolWindowTextFormat); - } - - if (rectTab.Contains(rectIcon)) - { - g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); - } - } - - private void DrawTab_Document(Graphics g, TabVS2005 tab, Rectangle rect) - { - if (tab.TabWidth == 0) - { - return; - } - - Rectangle rectIcon = new Rectangle( - rect.X + DocumentIconGapLeft, - rect.Y + rect.Height - 1 - DocumentIconGapBottom - DocumentIconHeight, - DocumentIconWidth, DocumentIconHeight); - Rectangle rectText = rectIcon; - if (DockPane.DockPanel.ShowDocumentIcon) - { - rectText.X += rectIcon.Width + DocumentIconGapRight; - rectText.Y = rect.Y; - rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - - DocumentIconGapRight - DocumentTextGapRight; - rectText.Height = rect.Height; - } - else - { - rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight; - } - - Rectangle rectTab = DrawHelper.RtlTransform(this, rect); - Rectangle rectBack = DrawHelper.RtlTransform(this, rect); - rectBack.Width += rect.X; - rectBack.X = 0; - - rectText = DrawHelper.RtlTransform(this, rectText); - rectIcon = DrawHelper.RtlTransform(this, rectIcon); - GraphicsPath path = GetTabOutline(tab, true, false); - if (DockPane.ActiveContent == tab.Content) - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient - .ActiveTabGradient.LinearGradientMode; - g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); - g.DrawPath(PenDocumentTabActiveBorder, path); - - Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient - .TextColor; - if (DockPane.IsActiveDocumentPane) - { - TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, BoldFont, rectText, textColor, - DocumentTextFormat); - } - else - { - TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, - DocumentTextFormat); - } - } - else - { - Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient - .StartColor; - Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient - .EndColor; - LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient - .InactiveTabGradient.LinearGradientMode; - g.FillPath(new LinearGradientBrush(rectBack, startColor, endColor, gradientMode), path); - g.DrawPath(PenDocumentTabInactiveBorder, path); - - Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient - .TextColor; - TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, - DocumentTextFormat); - } - - if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) - { - g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); - } - } - - private void SetInertButtons() - { - if (Appearance == DockPane.AppearanceStyle.ToolWindow) - { - if (m_buttonClose != null) - { - m_buttonClose.Left = -m_buttonClose.Width; - } - - if (m_buttonWindowList != null) - { - m_buttonWindowList.Left = -m_buttonWindowList.Width; - } - } - else - { - ButtonClose.Enabled = DockPane.ActiveContent == null - ? true - : DockPane.ActiveContent.DockHandler.CloseButton; - m_closeButtonVisible = DockPane.ActiveContent == null - ? true - : DockPane.ActiveContent.DockHandler.CloseButtonVisible; - ButtonClose.Visible = m_closeButtonVisible; - ButtonClose.RefreshChanges(); - ButtonWindowList.RefreshChanges(); - } - } - - private void LayoutButtons() - { - Rectangle rectTabStrip = TabStripRectangle; - - // Set position and size of the buttons - int buttonWidth = ButtonClose.Image.Width; - int buttonHeight = ButtonClose.Image.Height; - int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; - if (buttonHeight < height) - { - buttonWidth = buttonWidth * (height / buttonHeight); - buttonHeight = height; - } - Size buttonSize = new Size(buttonWidth, buttonHeight); - - int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - - DocumentButtonGapRight - buttonWidth; - int y = rectTabStrip.Y + DocumentButtonGapTop; - Point point = new Point(x, y); - ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); - - // If the close button is not visible draw the window list button overtop. - // Otherwise it is drawn to the left of the close button. - if (m_closeButtonVisible) - { - point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); - } - - ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); - } - - #endregion - - #region Events handler - - private void WindowList_Click(object sender, EventArgs e) - { - int x = 0; - int y = ButtonWindowList.Location.Y + ButtonWindowList.Height; - - SelectMenu.Items.Clear(); - foreach (TabVS2005 tab in Tabs) - { - IDockContent content = tab.Content; - ToolStripItem item = - SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); - item.Tag = tab.Content; - item.Click += new EventHandler(ContextMenuItem_Click); - } - SelectMenu.Show(ButtonWindowList, x, y); - } - - private void ContextMenuItem_Click(object sender, EventArgs e) - { - ToolStripMenuItem item = sender as ToolStripMenuItem; - if (item != null) - { - IDockContent content = (IDockContent) item.Tag; - DockPane.ActiveContent = content; - } - } - - private void Close_Click(object sender, EventArgs e) - { - DockPane.CloseActiveContent(); - } - - #endregion - - private class TabVS2005 : Tab - { - #region Fields - - #endregion - - #region cTor - - public TabVS2005(IDockContent content) - : base(content) - { - } - - #endregion - - #region Properties - - public int TabX { get; set; } - - public int TabWidth { get; set; } - - public int MaxWidth { get; set; } - - protected internal bool Flag { get; set; } - - #endregion - } - - private sealed class InertButton : InertButtonBase - { - #region Fields - - private readonly Bitmap m_image0; - private readonly Bitmap m_image1; - - private int m_imageCategory = 0; - - #endregion - - #region cTor - - public InertButton(Bitmap image0, Bitmap image1) - : base() - { - m_image0 = image0; - m_image1 = image1; - } - - #endregion - - #region Properties - - public int ImageCategory - { - get { return m_imageCategory; } - set - { - if (m_imageCategory == value) - { - return; - } - - m_imageCategory = value; - Invalidate(); - } - } - - public override Bitmap Image - { - get { return ImageCategory == 0 ? m_image0 : m_image1; } - } - - #endregion - } - - #region Constants - - private const int _ToolWindowStripGapTop = 0; - private const int _ToolWindowStripGapBottom = 1; - private const int _ToolWindowStripGapLeft = 0; - private const int _ToolWindowStripGapRight = 0; - private const int _ToolWindowImageHeight = 16; - private const int _ToolWindowImageWidth = 16; - private const int _ToolWindowImageGapTop = 3; - private const int _ToolWindowImageGapBottom = 1; - private const int _ToolWindowImageGapLeft = 2; - private const int _ToolWindowImageGapRight = 0; - private const int _ToolWindowTextGapRight = 3; - private const int _ToolWindowTabSeperatorGapTop = 3; - private const int _ToolWindowTabSeperatorGapBottom = 3; - - private const int _DocumentStripGapTop = 0; - private const int _DocumentStripGapBottom = 1; - private const int _DocumentTabMaxWidth = 200; - private const int _DocumentButtonGapTop = 4; - private const int _DocumentButtonGapBottom = 4; - private const int _DocumentButtonGapBetween = 0; - private const int _DocumentButtonGapRight = 3; - private const int _DocumentTabGapTop = 3; - private const int _DocumentTabGapLeft = 3; - private const int _DocumentTabGapRight = 3; - private const int _DocumentIconGapBottom = 2; - private const int _DocumentIconGapLeft = 8; - private const int _DocumentIconGapRight = 0; - private const int _DocumentIconHeight = 16; - private const int _DocumentIconWidth = 16; - private const int _DocumentTextGapRight = 3; - - #endregion - - #region Members - - private static Bitmap m_imageButtonClose; - private InertButton m_buttonClose; - private static Bitmap m_imageButtonWindowList; - private static Bitmap m_imageButtonWindowListOverflow; - private InertButton m_buttonWindowList; - private readonly ToolTip m_toolTip; - private Font m_font; - private Font m_boldFont; - private int m_startDisplayingTab = 0; - private bool m_documentTabsOverflow = false; - private static string m_toolTipSelect; - private static string m_toolTipClose; - private bool m_closeButtonVisible = false; - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/VisibleNestedPaneCollection.cs b/src/WinFormsUI/Docking/VisibleNestedPaneCollection.cs deleted file mode 100644 index 864915d3..00000000 --- a/src/WinFormsUI/Docking/VisibleNestedPaneCollection.cs +++ /dev/null @@ -1,203 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Drawing; -using System.Windows.Forms; - -namespace WeifenLuo.WinFormsUI.Docking -{ - public sealed class VisibleNestedPaneCollection : ReadOnlyCollection - { - #region Fields - - #endregion - - #region cTor - - internal VisibleNestedPaneCollection(NestedPaneCollection nestedPanes) - : base(new List()) - { - NestedPanes = nestedPanes; - } - - #endregion - - #region Properties - - public NestedPaneCollection NestedPanes { get; } - - public INestedPanesContainer Container - { - get { return NestedPanes.Container; } - } - - public DockState DockState - { - get { return NestedPanes.DockState; } - } - - public bool IsFloat - { - get { return NestedPanes.IsFloat; } - } - - #endregion - - #region Internals - - internal void Refresh() - { - Items.Clear(); - for (int i = 0; i < NestedPanes.Count; i++) - { - DockPane pane = NestedPanes[i]; - NestedDockingStatus status = pane.NestedDockingStatus; - status.SetDisplayingStatus(true, status.PreviousPane, status.Alignment, status.Proportion); - Items.Add(pane); - } - - foreach (DockPane pane in NestedPanes) - { - if (pane.DockState != DockState || pane.IsHidden) - { - pane.Bounds = Rectangle.Empty; - pane.SplitterBounds = Rectangle.Empty; - Remove(pane); - } - } - - CalculateBounds(); - - foreach (DockPane pane in this) - { - NestedDockingStatus status = pane.NestedDockingStatus; - pane.Bounds = status.PaneBounds; - pane.SplitterBounds = status.SplitterBounds; - pane.SplitterAlignment = status.Alignment; - } - } - - #endregion - - #region Private Methods - - private void Remove(DockPane pane) - { - if (!Contains(pane)) - { - return; - } - - NestedDockingStatus statusPane = pane.NestedDockingStatus; - DockPane lastNestedPane = null; - for (int i = Count - 1; i > IndexOf(pane); i--) - { - if (this[i].NestedDockingStatus.PreviousPane == pane) - { - lastNestedPane = this[i]; - break; - } - } - - if (lastNestedPane != null) - { - int indexLastNestedPane = IndexOf(lastNestedPane); - Items.Remove(lastNestedPane); - Items[IndexOf(pane)] = lastNestedPane; - NestedDockingStatus lastNestedDock = lastNestedPane.NestedDockingStatus; - lastNestedDock.SetDisplayingStatus(true, statusPane.DisplayingPreviousPane, - statusPane.DisplayingAlignment, statusPane.DisplayingProportion); - for (int i = indexLastNestedPane - 1; i > IndexOf(lastNestedPane); i--) - { - NestedDockingStatus status = this[i].NestedDockingStatus; - if (status.PreviousPane == pane) - { - status.SetDisplayingStatus(true, lastNestedPane, status.DisplayingAlignment, - status.DisplayingProportion); - } - } - } - else - { - Items.Remove(pane); - } - - statusPane.SetDisplayingStatus(false, null, DockAlignment.Left, 0.5); - } - - private void CalculateBounds() - { - if (Count == 0) - { - return; - } - - this[0].NestedDockingStatus.SetDisplayingBounds(Container.DisplayingRectangle, - Container.DisplayingRectangle, Rectangle.Empty); - - for (int i = 1; i < Count; i++) - { - DockPane pane = this[i]; - NestedDockingStatus status = pane.NestedDockingStatus; - DockPane prevPane = status.DisplayingPreviousPane; - NestedDockingStatus statusPrev = prevPane.NestedDockingStatus; - - Rectangle rect = statusPrev.PaneBounds; - bool bVerticalSplitter = status.DisplayingAlignment == DockAlignment.Left || - status.DisplayingAlignment == DockAlignment.Right; - - Rectangle rectThis = rect; - Rectangle rectPrev = rect; - Rectangle rectSplitter = rect; - if (status.DisplayingAlignment == DockAlignment.Left) - { - rectThis.Width = (int) ((double) rect.Width * status.DisplayingProportion) - - Measures.SplitterSize / 2; - rectSplitter.X = rectThis.X + rectThis.Width; - rectSplitter.Width = Measures.SplitterSize; - rectPrev.X = rectSplitter.X + rectSplitter.Width; - rectPrev.Width = rect.Width - rectThis.Width - rectSplitter.Width; - } - else if (status.DisplayingAlignment == DockAlignment.Right) - { - rectPrev.Width = rect.Width - (int) ((double) rect.Width * status.DisplayingProportion) - - Measures.SplitterSize / 2; - rectSplitter.X = rectPrev.X + rectPrev.Width; - rectSplitter.Width = Measures.SplitterSize; - rectThis.X = rectSplitter.X + rectSplitter.Width; - rectThis.Width = rect.Width - rectPrev.Width - rectSplitter.Width; - } - else if (status.DisplayingAlignment == DockAlignment.Top) - { - rectThis.Height = (int) ((double) rect.Height * status.DisplayingProportion) - - Measures.SplitterSize / 2; - rectSplitter.Y = rectThis.Y + rectThis.Height; - rectSplitter.Height = Measures.SplitterSize; - rectPrev.Y = rectSplitter.Y + rectSplitter.Height; - rectPrev.Height = rect.Height - rectThis.Height - rectSplitter.Height; - } - else if (status.DisplayingAlignment == DockAlignment.Bottom) - { - rectPrev.Height = rect.Height - (int) ((double) rect.Height * status.DisplayingProportion) - - Measures.SplitterSize / 2; - rectSplitter.Y = rectPrev.Y + rectPrev.Height; - rectSplitter.Height = Measures.SplitterSize; - rectThis.Y = rectSplitter.Y + rectSplitter.Height; - rectThis.Height = rect.Height - rectPrev.Height - rectSplitter.Height; - } - else - { - rectThis = Rectangle.Empty; - } - - rectSplitter.Intersect(rect); - rectThis.Intersect(rect); - rectPrev.Intersect(rect); - status.SetDisplayingBounds(rect, rectThis, rectSplitter); - statusPrev.SetDisplayingBounds(statusPrev.LogicalBounds, rectPrev, statusPrev.SplitterBounds); - } - } - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Win32/Enums.cs b/src/WinFormsUI/Docking/Win32/Enums.cs deleted file mode 100644 index bf80c4b4..00000000 --- a/src/WinFormsUI/Docking/Win32/Enums.cs +++ /dev/null @@ -1,369 +0,0 @@ -using System; - -namespace WeifenLuo.WinFormsUI.Docking.Win32 -{ - [Flags] - internal enum FlagsSetWindowPos : uint - { - SWP_NOSIZE = 0x0001, - SWP_NOMOVE = 0x0002, - SWP_NOZORDER = 0x0004, - SWP_NOREDRAW = 0x0008, - SWP_NOACTIVATE = 0x0010, - SWP_FRAMECHANGED = 0x0020, - SWP_SHOWWINDOW = 0x0040, - SWP_HIDEWINDOW = 0x0080, - SWP_NOCOPYBITS = 0x0100, - SWP_NOOWNERZORDER = 0x0200, - SWP_NOSENDCHANGING = 0x0400, - SWP_DRAWFRAME = 0x0020, - SWP_NOREPOSITION = 0x0200, - SWP_DEFERERASE = 0x2000, - SWP_ASYNCWINDOWPOS = 0x4000 - } - - internal enum ShowWindowStyles : short - { - SW_HIDE = 0, - SW_SHOWNORMAL = 1, - SW_NORMAL = 1, - SW_SHOWMINIMIZED = 2, - SW_SHOWMAXIMIZED = 3, - SW_MAXIMIZE = 3, - SW_SHOWNOACTIVATE = 4, - SW_SHOW = 5, - SW_MINIMIZE = 6, - SW_SHOWMINNOACTIVE = 7, - SW_SHOWNA = 8, - SW_RESTORE = 9, - SW_SHOWDEFAULT = 10, - SW_FORCEMINIMIZE = 11, - SW_MAX = 11 - } - - internal enum WindowStyles : uint - { - WS_OVERLAPPED = 0x00000000, - WS_POPUP = 0x80000000, - WS_CHILD = 0x40000000, - WS_MINIMIZE = 0x20000000, - WS_VISIBLE = 0x10000000, - WS_DISABLED = 0x08000000, - WS_CLIPSIBLINGS = 0x04000000, - WS_CLIPCHILDREN = 0x02000000, - WS_MAXIMIZE = 0x01000000, - WS_CAPTION = 0x00C00000, - WS_BORDER = 0x00800000, - WS_DLGFRAME = 0x00400000, - WS_VSCROLL = 0x00200000, - WS_HSCROLL = 0x00100000, - WS_SYSMENU = 0x00080000, - WS_THICKFRAME = 0x00040000, - WS_GROUP = 0x00020000, - WS_TABSTOP = 0x00010000, - WS_MINIMIZEBOX = 0x00020000, - WS_MAXIMIZEBOX = 0x00010000, - WS_TILED = 0x00000000, - WS_ICONIC = 0x20000000, - WS_SIZEBOX = 0x00040000, - WS_POPUPWINDOW = 0x80880000, - WS_OVERLAPPEDWINDOW = 0x00CF0000, - WS_TILEDWINDOW = 0x00CF0000, - WS_CHILDWINDOW = 0x40000000 - } - - internal enum WindowExStyles - { - WS_EX_DLGMODALFRAME = 0x00000001, - WS_EX_NOPARENTNOTIFY = 0x00000004, - WS_EX_TOPMOST = 0x00000008, - WS_EX_ACCEPTFILES = 0x00000010, - WS_EX_TRANSPARENT = 0x00000020, - WS_EX_MDICHILD = 0x00000040, - WS_EX_TOOLWINDOW = 0x00000080, - WS_EX_WINDOWEDGE = 0x00000100, - WS_EX_CLIENTEDGE = 0x00000200, - WS_EX_CONTEXTHELP = 0x00000400, - WS_EX_RIGHT = 0x00001000, - WS_EX_LEFT = 0x00000000, - WS_EX_RTLREADING = 0x00002000, - WS_EX_LTRREADING = 0x00000000, - WS_EX_LEFTSCROLLBAR = 0x00004000, - WS_EX_RIGHTSCROLLBAR = 0x00000000, - WS_EX_CONTROLPARENT = 0x00010000, - WS_EX_STATICEDGE = 0x00020000, - WS_EX_APPWINDOW = 0x00040000, - WS_EX_OVERLAPPEDWINDOW = 0x00000300, - WS_EX_PALETTEWINDOW = 0x00000188, - WS_EX_LAYERED = 0x00080000 - } - - internal enum Msgs - { - WM_NULL = 0x0000, - WM_CREATE = 0x0001, - WM_DESTROY = 0x0002, - WM_MOVE = 0x0003, - WM_SIZE = 0x0005, - WM_ACTIVATE = 0x0006, - WM_SETFOCUS = 0x0007, - WM_KILLFOCUS = 0x0008, - WM_ENABLE = 0x000A, - WM_SETREDRAW = 0x000B, - WM_SETTEXT = 0x000C, - WM_GETTEXT = 0x000D, - WM_GETTEXTLENGTH = 0x000E, - WM_PAINT = 0x000F, - WM_CLOSE = 0x0010, - WM_QUERYENDSESSION = 0x0011, - WM_QUIT = 0x0012, - WM_QUERYOPEN = 0x0013, - WM_ERASEBKGND = 0x0014, - WM_SYSCOLORCHANGE = 0x0015, - WM_ENDSESSION = 0x0016, - WM_SHOWWINDOW = 0x0018, - WM_WININICHANGE = 0x001A, - WM_SETTINGCHANGE = 0x001A, - WM_DEVMODECHANGE = 0x001B, - WM_ACTIVATEAPP = 0x001C, - WM_FONTCHANGE = 0x001D, - WM_TIMECHANGE = 0x001E, - WM_CANCELMODE = 0x001F, - WM_SETCURSOR = 0x0020, - WM_MOUSEACTIVATE = 0x0021, - WM_CHILDACTIVATE = 0x0022, - WM_QUEUESYNC = 0x0023, - WM_GETMINMAXINFO = 0x0024, - WM_PAINTICON = 0x0026, - WM_ICONERASEBKGND = 0x0027, - WM_NEXTDLGCTL = 0x0028, - WM_SPOOLERSTATUS = 0x002A, - WM_DRAWITEM = 0x002B, - WM_MEASUREITEM = 0x002C, - WM_DELETEITEM = 0x002D, - WM_VKEYTOITEM = 0x002E, - WM_CHARTOITEM = 0x002F, - WM_SETFONT = 0x0030, - WM_GETFONT = 0x0031, - WM_SETHOTKEY = 0x0032, - WM_GETHOTKEY = 0x0033, - WM_QUERYDRAGICON = 0x0037, - WM_COMPAREITEM = 0x0039, - WM_GETOBJECT = 0x003D, - WM_COMPACTING = 0x0041, - WM_COMMNOTIFY = 0x0044, - WM_WINDOWPOSCHANGING = 0x0046, - WM_WINDOWPOSCHANGED = 0x0047, - WM_POWER = 0x0048, - WM_COPYDATA = 0x004A, - WM_CANCELJOURNAL = 0x004B, - WM_NOTIFY = 0x004E, - WM_INPUTLANGCHANGEREQUEST = 0x0050, - WM_INPUTLANGCHANGE = 0x0051, - WM_TCARD = 0x0052, - WM_HELP = 0x0053, - WM_USERCHANGED = 0x0054, - WM_NOTIFYFORMAT = 0x0055, - WM_CONTEXTMENU = 0x007B, - WM_STYLECHANGING = 0x007C, - WM_STYLECHANGED = 0x007D, - WM_DISPLAYCHANGE = 0x007E, - WM_GETICON = 0x007F, - WM_SETICON = 0x0080, - WM_NCCREATE = 0x0081, - WM_NCDESTROY = 0x0082, - WM_NCCALCSIZE = 0x0083, - WM_NCHITTEST = 0x0084, - WM_NCPAINT = 0x0085, - WM_NCACTIVATE = 0x0086, - WM_GETDLGCODE = 0x0087, - WM_SYNCPAINT = 0x0088, - WM_NCMOUSEMOVE = 0x00A0, - WM_NCLBUTTONDOWN = 0x00A1, - WM_NCLBUTTONUP = 0x00A2, - WM_NCLBUTTONDBLCLK = 0x00A3, - WM_NCRBUTTONDOWN = 0x00A4, - WM_NCRBUTTONUP = 0x00A5, - WM_NCRBUTTONDBLCLK = 0x00A6, - WM_NCMBUTTONDOWN = 0x00A7, - WM_NCMBUTTONUP = 0x00A8, - WM_NCMBUTTONDBLCLK = 0x00A9, - WM_KEYDOWN = 0x0100, - WM_KEYUP = 0x0101, - WM_CHAR = 0x0102, - WM_DEADCHAR = 0x0103, - WM_SYSKEYDOWN = 0x0104, - WM_SYSKEYUP = 0x0105, - WM_SYSCHAR = 0x0106, - WM_SYSDEADCHAR = 0x0107, - WM_KEYLAST = 0x0108, - WM_IME_STARTCOMPOSITION = 0x010D, - WM_IME_ENDCOMPOSITION = 0x010E, - WM_IME_COMPOSITION = 0x010F, - WM_IME_KEYLAST = 0x010F, - WM_INITDIALOG = 0x0110, - WM_COMMAND = 0x0111, - WM_SYSCOMMAND = 0x0112, - WM_TIMER = 0x0113, - WM_HSCROLL = 0x0114, - WM_VSCROLL = 0x0115, - WM_INITMENU = 0x0116, - WM_INITMENUPOPUP = 0x0117, - WM_MENUSELECT = 0x011F, - WM_MENUCHAR = 0x0120, - WM_ENTERIDLE = 0x0121, - WM_MENURBUTTONUP = 0x0122, - WM_MENUDRAG = 0x0123, - WM_MENUGETOBJECT = 0x0124, - WM_UNINITMENUPOPUP = 0x0125, - WM_MENUCOMMAND = 0x0126, - WM_CTLCOLORMSGBOX = 0x0132, - WM_CTLCOLOREDIT = 0x0133, - WM_CTLCOLORLISTBOX = 0x0134, - WM_CTLCOLORBTN = 0x0135, - WM_CTLCOLORDLG = 0x0136, - WM_CTLCOLORSCROLLBAR = 0x0137, - WM_CTLCOLORSTATIC = 0x0138, - WM_MOUSEMOVE = 0x0200, - WM_LBUTTONDOWN = 0x0201, - WM_LBUTTONUP = 0x0202, - WM_LBUTTONDBLCLK = 0x0203, - WM_RBUTTONDOWN = 0x0204, - WM_RBUTTONUP = 0x0205, - WM_RBUTTONDBLCLK = 0x0206, - WM_MBUTTONDOWN = 0x0207, - WM_MBUTTONUP = 0x0208, - WM_MBUTTONDBLCLK = 0x0209, - WM_MOUSEWHEEL = 0x020A, - WM_PARENTNOTIFY = 0x0210, - WM_ENTERMENULOOP = 0x0211, - WM_EXITMENULOOP = 0x0212, - WM_NEXTMENU = 0x0213, - WM_SIZING = 0x0214, - WM_CAPTURECHANGED = 0x0215, - WM_MOVING = 0x0216, - WM_DEVICECHANGE = 0x0219, - WM_MDICREATE = 0x0220, - WM_MDIDESTROY = 0x0221, - WM_MDIACTIVATE = 0x0222, - WM_MDIRESTORE = 0x0223, - WM_MDINEXT = 0x0224, - WM_MDIMAXIMIZE = 0x0225, - WM_MDITILE = 0x0226, - WM_MDICASCADE = 0x0227, - WM_MDIICONARRANGE = 0x0228, - WM_MDIGETACTIVE = 0x0229, - WM_MDISETMENU = 0x0230, - WM_ENTERSIZEMOVE = 0x0231, - WM_EXITSIZEMOVE = 0x0232, - WM_DROPFILES = 0x0233, - WM_MDIREFRESHMENU = 0x0234, - WM_IME_SETCONTEXT = 0x0281, - WM_IME_NOTIFY = 0x0282, - WM_IME_CONTROL = 0x0283, - WM_IME_COMPOSITIONFULL = 0x0284, - WM_IME_SELECT = 0x0285, - WM_IME_CHAR = 0x0286, - WM_IME_REQUEST = 0x0288, - WM_IME_KEYDOWN = 0x0290, - WM_IME_KEYUP = 0x0291, - WM_MOUSEHOVER = 0x02A1, - WM_MOUSELEAVE = 0x02A3, - WM_CUT = 0x0300, - WM_COPY = 0x0301, - WM_PASTE = 0x0302, - WM_CLEAR = 0x0303, - WM_UNDO = 0x0304, - WM_RENDERFORMAT = 0x0305, - WM_RENDERALLFORMATS = 0x0306, - WM_DESTROYCLIPBOARD = 0x0307, - WM_DRAWCLIPBOARD = 0x0308, - WM_PAINTCLIPBOARD = 0x0309, - WM_VSCROLLCLIPBOARD = 0x030A, - WM_SIZECLIPBOARD = 0x030B, - WM_ASKCBFORMATNAME = 0x030C, - WM_CHANGECBCHAIN = 0x030D, - WM_HSCROLLCLIPBOARD = 0x030E, - WM_QUERYNEWPALETTE = 0x030F, - WM_PALETTEISCHANGING = 0x0310, - WM_PALETTECHANGED = 0x0311, - WM_HOTKEY = 0x0312, - WM_PRINT = 0x0317, - WM_PRINTCLIENT = 0x0318, - WM_HANDHELDFIRST = 0x0358, - WM_HANDHELDLAST = 0x035F, - WM_AFXFIRST = 0x0360, - WM_AFXLAST = 0x037F, - WM_PENWINFIRST = 0x0380, - WM_PENWINLAST = 0x038F, - WM_APP = 0x8000, - WM_USER = 0x0400 - } - - internal enum HitTest - { - HTERROR = -2, - HTTRANSPARENT = -1, - HTNOWHERE = 0, - HTCLIENT = 1, - HTCAPTION = 2, - HTSYSMENU = 3, - HTGROWBOX = 4, - HTSIZE = 4, - HTMENU = 5, - HTHSCROLL = 6, - HTVSCROLL = 7, - HTMINBUTTON = 8, - HTMAXBUTTON = 9, - HTLEFT = 10, - HTRIGHT = 11, - HTTOP = 12, - HTTOPLEFT = 13, - HTTOPRIGHT = 14, - HTBOTTOM = 15, - HTBOTTOMLEFT = 16, - HTBOTTOMRIGHT = 17, - HTBORDER = 18, - HTREDUCE = 8, - HTZOOM = 9, - HTSIZEFIRST = 10, - HTSIZELAST = 17, - HTOBJECT = 19, - HTCLOSE = 20, - HTHELP = 21 - } - - internal enum ScrollBars : uint - { - SB_HORZ = 0, - SB_VERT = 1, - SB_CTL = 2, - SB_BOTH = 3 - } - - internal enum GetWindowLongIndex : int - { - GWL_STYLE = -16, - GWL_EXSTYLE = -20 - } - - // Hook Types - internal enum HookType : int - { - WH_JOURNALRECORD = 0, - WH_JOURNALPLAYBACK = 1, - WH_KEYBOARD = 2, - WH_GETMESSAGE = 3, - WH_CALLWNDPROC = 4, - WH_CBT = 5, - WH_SYSMSGFILTER = 6, - WH_MOUSE = 7, - WH_HARDWARE = 8, - WH_DEBUG = 9, - WH_SHELL = 10, - WH_FOREGROUNDIDLE = 11, - WH_CALLWNDPROCRET = 12, - WH_KEYBOARD_LL = 13, - WH_MOUSE_LL = 14 - } -} \ No newline at end of file diff --git a/src/WinFormsUI/Docking/Win32/NativeMethods.cs b/src/WinFormsUI/Docking/Win32/NativeMethods.cs deleted file mode 100644 index a4c85b62..00000000 --- a/src/WinFormsUI/Docking/Win32/NativeMethods.cs +++ /dev/null @@ -1,74 +0,0 @@ -using System; -using System.Drawing; -using System.Runtime.InteropServices; -using System.Diagnostics.CodeAnalysis; -using WeifenLuo.WinFormsUI.Docking.Win32; - -namespace WeifenLuo.WinFormsUI.Docking -{ - internal static class NativeMethods - { - #region Delegates - - public delegate IntPtr HookProc(int code, IntPtr wParam, IntPtr lParam); - - #endregion - - #region Public methods - - [DllImport("User32.dll", CharSet = CharSet.Auto)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool DragDetect(IntPtr hWnd, Point pt); - - [DllImport("User32.dll", CharSet = CharSet.Auto)] - public static extern IntPtr GetFocus(); - - [DllImport("User32.dll", CharSet = CharSet.Auto)] - public static extern IntPtr SetFocus(IntPtr hWnd); - - [DllImport("User32.dll", CharSet = CharSet.Auto)] - [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool PostMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam); - - [DllImport("User32.dll", CharSet = CharSet.Auto)] - public static extern uint SendMessage(IntPtr hWnd, int Msg, uint wParam, uint lParam); - - [DllImport("User32.dll", CharSet = CharSet.Auto)] - public static extern int ShowWindow(IntPtr hWnd, short cmdShow); - - [DllImport("User32.dll", CharSet = CharSet.Auto)] - public static extern int SetWindowPos(IntPtr hWnd, IntPtr hWndAfter, int X, int Y, int Width, int Height, - FlagsSetWindowPos flags); - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - public static extern int GetWindowLong(IntPtr hWnd, int Index); - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - public static extern int SetWindowLong(IntPtr hWnd, int Index, int Value); - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - public static extern int ShowScrollBar(IntPtr hWnd, int wBar, int bShow); - - [DllImport("user32.dll", CharSet = CharSet.Auto)] - //********************************* - // FxCop bug, suppress the message - //********************************* - [SuppressMessage("Microsoft.Portability", "CA1901:PInvokeDeclarationsShouldBePortable", MessageId = "0")] - public static extern IntPtr WindowFromPoint(Point point); - - [DllImport("Kernel32.dll", CharSet = CharSet.Auto)] - public static extern int GetCurrentThreadId(); - - [DllImport("user32.dll")] - public static extern IntPtr - SetWindowsHookEx(Win32.HookType code, HookProc func, IntPtr hInstance, int threadID); - - [DllImport("user32.dll")] - public static extern int UnhookWindowsHookEx(IntPtr hhook); - - [DllImport("user32.dll")] - public static extern IntPtr CallNextHookEx(IntPtr hhook, int code, IntPtr wParam, IntPtr lParam); - - #endregion - } -} \ No newline at end of file diff --git a/src/WinFormsUI/WinFormsUI.csproj b/src/WinFormsUI/WinFormsUI.csproj deleted file mode 100644 index 664ada6d..00000000 --- a/src/WinFormsUI/WinFormsUI.csproj +++ /dev/null @@ -1,113 +0,0 @@ - - - net8.0-windows - true - Library - WeifenLuo.WinFormsUI - WeifenLuo.WinFormsUI.Docking - true - ..\Solution Items\Key.snk - SAK - SAK - false - SAK - SAK - publish\ - true - Disk - false - Foreground - 7 - Days - false - false - true - 0 - 1.0.0.%2a - false - false - true - false - true - true - false - $(SolutionDir)..\bin\$(Configuration) - CA1416; - - - False - - - True - - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - UserControl - - - Component - - - Component - - - Component - - - UserControl - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - Component - - - - - Key.snk - - - - - - diff --git a/src/WinFormsUI/WinFormsUI.csproj.vspscc b/src/WinFormsUI/WinFormsUI.csproj.vspscc deleted file mode 100644 index feffdeca..00000000 --- a/src/WinFormsUI/WinFormsUI.csproj.vspscc +++ /dev/null @@ -1,10 +0,0 @@ -"" -{ -"FILE_VERSION" = "9237" -"ENLISTMENT_CHOICE" = "NEVER" -"PROJECT_FILE_RELATIVE_PATH" = "" -"NUMBER_OF_EXCLUDED_FILES" = "0" -"ORIGINAL_PROJECT_FILE_PATH" = "" -"NUMBER_OF_NESTED_PROJECTS" = "0" -"SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" -} diff --git a/src/WinFormsUI/license.txt b/src/WinFormsUI/license.txt deleted file mode 100644 index 290b9a43..00000000 --- a/src/WinFormsUI/license.txt +++ /dev/null @@ -1,9 +0,0 @@ -The MIT License - -Copyright (c) 2007 Weifen Luo (email: weifenluo@yahoo.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/usedPackages.json b/src/usedPackages.json new file mode 100644 index 00000000..0b48bbde Binary files /dev/null and b/src/usedPackages.json differ