<commit_before>﻿using Common;
using ICSharpCode.AvalonEdit.AddIn;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.SharpDevelop.Editor;
using Nemerle.Diff;
using Nitra.ViewModels;
using Nitra.ClientServer.Messages;
using Nitra.Visualizer.Properties;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Nitra.Visualizer.Controls;
using Microsoft.VisualBasic.FileIO;
using Nitra.ClientServer.Client;
using Clipboard = System.Windows.Clipboard;
using ContextMenu = System.Windows.Controls.ContextMenu;
using Control = System.Windows.Controls.Control;
using DataFormats = System.Windows.DataFormats;
using File = System.IO.File;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MenuItem = System.Windows.Controls.MenuItem;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using Timer = System.Timers.Timer;
using ToolTip = System.Windows.Controls.ToolTip;

namespace Nitra.Visualizer
{
    using System.Windows.Documents;
    using Interop;
    using System.Windows.Interop;
    using ClientServer.Messages;
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
  {
    bool _initializing = true;
    bool _doTreeOperation;
    bool _doChangeCaretPos;
    readonly Timer _parseTimer;
    readonly Timer _nodeForCaretTimer;
    readonly Dictionary<string, HighlightingColor> _highlightingStyles;
    readonly TextMarkerService _textMarkerService;
    readonly NitraFoldingStrategy _foldingStrategy;
    readonly FoldingManager _foldingManager;
    readonly ToolTip _textBox1Tooltip;
    bool _needUpdateReflection;
    bool _needUpdateHtmlPrettyPrint;
    bool _needUpdateTextPrettyPrint;
    //ParseTree _parseTree;
    readonly Settings _settings;
    WorkspaceVm _workspace;
    SuiteVm _currentSuite;
    ProjectVm _currentProject;
      private SolutionVm _currentSolution;
    TestVm _currentTest;
    readonly PependentPropertyGrid _propertyGrid;
    //readonly MatchBracketsWalker _matchBracketsWalker = new MatchBracketsWalker();
    readonly List<ITextMarker> _matchedBracketsMarkers = new List<ITextMarker>();
    //List<MatchBracketsWalker.MatchBrackets> _matchedBrackets;
    const string ErrorMarkerTag = "Error";

    public MainWindow()
    {
      _settings = Settings.Default;
      _highlightingStyles = new Dictionary<string, HighlightingColor>(StringComparer.OrdinalIgnoreCase);

      ToolTipService.ShowDurationProperty.OverrideMetadata(
        typeof(DependencyObject),
        new FrameworkPropertyMetadata(Int32.MaxValue));

      InitializeComponent();

      _mainRow.Height  = new GridLength(_settings.TabControlHeight);


      _configComboBox.ItemsSource = new[] {"Debug", "Release"};
      var config = _settings.Config;
      _configComboBox.SelectedItem = config == "Release" ? "Release" : "Debug";

      _tabControl.SelectedIndex = _settings.ActiveTabIndex;
      _foldingStrategy          = new NitraFoldingStrategy();
      _textBox1Tooltip          = new ToolTip { PlacementTarget = _text };
      _parseTimer               = new Timer { AutoReset = false, Enabled = false, Interval = 300 };
      _parseTimer.Elapsed       += _parseTimer_Elapsed;
      _nodeForCaretTimer        = new Timer {AutoReset = false, Enabled = false, Interval = 500};
      _nodeForCaretTimer.Elapsed += _nodeForCaretTimer_Elapsed;

      _text.TextArea.Caret.PositionChanged += Caret_PositionChanged;

      _foldingManager    = FoldingManager.Install(_text.TextArea);
      _textMarkerService = new TextMarkerService(_text.Document);

      _text.TextArea.TextView.BackgroundRenderers.Add(_textMarkerService);
      _text.TextArea.TextView.LineTransformers.Add(_textMarkerService);
      _text.Options.ConvertTabsToSpaces = true;
      _text.Options.EnableRectangularSelection = true;
      _text.Options.IndentationSize = 2;
      _testsTreeView.SelectedValuePath = "FullPath";
      _propertyGrid = new PependentPropertyGrid();
      _windowsFormsHost.Child = _propertyGrid;

      if (string.IsNullOrWhiteSpace(_settings.CurrentWorkspace))
        _workspace = null;
      else
        LoadTests();

      _text.Document.Changed += Document_Changed;
      _text.Document.UpdateStarted += DocumentOnUpdateStarted;
      _text.Document.UpdateFinished += DocumentOnUpdateFinished;
    }

    private void DocumentOnUpdateFinished(object sender, EventArgs eventArgs)
    {
      if (_currentTest == null)
        return;

      _currentTest.StartBatchCodeUpdate();
    }

    private void DocumentOnUpdateStarted(object sender, EventArgs eventArgs)
    {
      if (_currentTest == null)
        return;

      _currentTest.FinishBatchCodeUpdate();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
      _initializing = false;

      if ((Keyboard.Modifiers & (ModifierKeys.Shift | ModifierKeys.Control)) != 0)
        return;
      if (_workspace != null)
        SelectTest(_settings.SelectedTestNode);
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
      base.OnSourceInitialized(e);
      this.SetPlacement(_settings.MainWindowPlacement);
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
      _initializing = true;

      _settings.MainWindowPlacement = this.GetPlacement();
      _settings.Config = (string)_configComboBox.SelectedValue;
      _settings.TabControlHeight = _mainRow.Height.Value;
      _settings.LastTextInput = _text.Text;
      _settings.ActiveTabIndex = _tabControl.SelectedIndex;
      _settings.Save();
      
      _currentSuite    = null;
      _currentSolution = null;
      _currentProject  = null;
      _currentTest     = null;

      foreach (var testSuite in _workspace.TestSuites)
        testSuite.Dispose();
    }

    void SetPlacement(string placementXml)
    {
      var helper = new WindowInteropHelper(this);
      var handle = helper.Handle;
      WindowPlacement.SetPlacement(handle, placementXml);
    }

    string GetPlacement()
    {
      var helper = new WindowInteropHelper(this);
      var handle = helper.Handle;
      return WindowPlacement.GetPlacement(handle);
    }

    private void SaveSelectedTestAndTestSuite()
    {
      if (_currentTest != null)
        _settings.SelectedTestNode = _currentTest.FullPath;<commit_msg>Fix NRE.<commit_after>﻿using Common;
using ICSharpCode.AvalonEdit.AddIn;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.SharpDevelop.Editor;
using Nemerle.Diff;
using Nitra.ViewModels;
using Nitra.ClientServer.Messages;
using Nitra.Visualizer.Properties;

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Nitra.Visualizer.Controls;
using Microsoft.VisualBasic.FileIO;
using Nitra.ClientServer.Client;
using Clipboard = System.Windows.Clipboard;
using ContextMenu = System.Windows.Controls.ContextMenu;
using Control = System.Windows.Controls.Control;
using DataFormats = System.Windows.DataFormats;
using File = System.IO.File;
using KeyEventArgs = System.Windows.Input.KeyEventArgs;
using MenuItem = System.Windows.Controls.MenuItem;
using MessageBox = System.Windows.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;
using Timer = System.Timers.Timer;
using ToolTip = System.Windows.Controls.ToolTip;

namespace Nitra.Visualizer
{
    using System.Windows.Documents;
    using Interop;
    using System.Windows.Interop;
    using ClientServer.Messages;
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
  {
    bool _initializing = true;
    bool _doTreeOperation;
    bool _doChangeCaretPos;
    readonly Timer _parseTimer;
    readonly Timer _nodeForCaretTimer;
    readonly Dictionary<string, HighlightingColor> _highlightingStyles;
    readonly TextMarkerService _textMarkerService;
    readonly NitraFoldingStrategy _foldingStrategy;
    readonly FoldingManager _foldingManager;
    readonly ToolTip _textBox1Tooltip;
    bool _needUpdateReflection;
    bool _needUpdateHtmlPrettyPrint;
    bool _needUpdateTextPrettyPrint;
    //ParseTree _parseTree;
    readonly Settings _settings;
    WorkspaceVm _workspace;
    SuiteVm _currentSuite;
    ProjectVm _currentProject;
      private SolutionVm _currentSolution;
    TestVm _currentTest;
    readonly PependentPropertyGrid _propertyGrid;
    //readonly MatchBracketsWalker _matchBracketsWalker = new MatchBracketsWalker();
    readonly List<ITextMarker> _matchedBracketsMarkers = new List<ITextMarker>();
    //List<MatchBracketsWalker.MatchBrackets> _matchedBrackets;
    const string ErrorMarkerTag = "Error";

    public MainWindow()
    {
      _settings = Settings.Default;
      _highlightingStyles = new Dictionary<string, HighlightingColor>(StringComparer.OrdinalIgnoreCase);

      ToolTipService.ShowDurationProperty.OverrideMetadata(
        typeof(DependencyObject),
        new FrameworkPropertyMetadata(Int32.MaxValue));

      InitializeComponent();

      _mainRow.Height  = new GridLength(_settings.TabControlHeight);


      _configComboBox.ItemsSource = new[] {"Debug", "Release"};
      var config = _settings.Config;
      _configComboBox.SelectedItem = config == "Release" ? "Release" : "Debug";

      _tabControl.SelectedIndex = _settings.ActiveTabIndex;
      _foldingStrategy          = new NitraFoldingStrategy();
      _textBox1Tooltip          = new ToolTip { PlacementTarget = _text };
      _parseTimer               = new Timer { AutoReset = false, Enabled = false, Interval = 300 };
      _parseTimer.Elapsed       += _parseTimer_Elapsed;
      _nodeForCaretTimer        = new Timer {AutoReset = false, Enabled = false, Interval = 500};
      _nodeForCaretTimer.Elapsed += _nodeForCaretTimer_Elapsed;

      _text.TextArea.Caret.PositionChanged += Caret_PositionChanged;

      _foldingManager    = FoldingManager.Install(_text.TextArea);
      _textMarkerService = new TextMarkerService(_text.Document);

      _text.TextArea.TextView.BackgroundRenderers.Add(_textMarkerService);
      _text.TextArea.TextView.LineTransformers.Add(_textMarkerService);
      _text.Options.ConvertTabsToSpaces = true;
      _text.Options.EnableRectangularSelection = true;
      _text.Options.IndentationSize = 2;
      _testsTreeView.SelectedValuePath = "FullPath";
      _propertyGrid = new PependentPropertyGrid();
      _windowsFormsHost.Child = _propertyGrid;

      if (string.IsNullOrWhiteSpace(_settings.CurrentWorkspace))
        _workspace = null;
      else
        LoadTests();

      _text.Document.Changed += Document_Changed;
      _text.Document.UpdateStarted += DocumentOnUpdateStarted;
      _text.Document.UpdateFinished += DocumentOnUpdateFinished;
    }

    private void DocumentOnUpdateFinished(object sender, EventArgs eventArgs)
    {
      if (_currentTest == null)
        return;

      _currentTest.StartBatchCodeUpdate();
    }

    private void DocumentOnUpdateStarted(object sender, EventArgs eventArgs)
    {
      if (_currentTest == null)
        return;

      _currentTest.FinishBatchCodeUpdate();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
      _initializing = false;

      if ((Keyboard.Modifiers & (ModifierKeys.Shift | ModifierKeys.Control)) != 0)
        return;
      if (_workspace != null)
        SelectTest(_settings.SelectedTestNode);
    }

    protected override void OnSourceInitialized(EventArgs e)
    {
      base.OnSourceInitialized(e);
      this.SetPlacement(_settings.MainWindowPlacement);
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
      _initializing = true;

      _settings.MainWindowPlacement = this.GetPlacement();
      _settings.Config = (string)_configComboBox.SelectedValue;
      _settings.TabControlHeight = _mainRow.Height.Value;
      _settings.LastTextInput = _text.Text;
      _settings.ActiveTabIndex = _tabControl.SelectedIndex;
      _settings.Save();
      
      _currentSuite    = null;
      _currentSolution = null;
      _currentProject  = null;
      _currentTest     = null;

      if (_workspace != null)
      {
        foreach (var testSuite in _workspace.TestSuites)
          testSuite.Dispose();
      }
    }

    void SetPlacement(string placementXml)
    {
      var helper = new WindowInteropHelper(this);
      var handle = helper.Handle;
      WindowPlacement.SetPlacement(handle, placementXml);
    }

    string GetPlacement()
    {
      var helper = new WindowInteropHelper(this);
      var handle = helper.Handle;
      return WindowPlacement.GetPlacement(handle);
    }

    private void SaveSelectedTestAndTestSuite()
    {
      if (_currentTest != null)
        _settings.SelectedTestNode = _currentTest.FullPath;
{'fraction_non_alphanumeric': 0.08146624550062441, 'fraction_numerical': 0.0017630206420333504, 'mean_word_length': 3.7485176142309036, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '802025', 'n_tokens_mistral': 3886, 'n_tokens_neox': 3772, 'n_words': 771}