<commit_before>﻿using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Highlighting;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using RehostedWorkflowDesigner.Helpers;
using System;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.View;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace RehostedWorkflowDesigner.CSharpExpressionEditor
{
    public class RoslynExpressionEditorInstance : TextEditor, IExpressionEditorInstance
    {
        private CompletionWindow completionWindow;
        private string variableDeclarations;

        public RoslynExpressionEditorInstance()
        {
            this.TextArea.TextEntering += TextArea_TextEntering;
            this.TextArea.TextEntered += TextArea_TextEntered;
            this.TextArea.LostKeyboardFocus += TextArea_LostFocus; // Need to detach events.

            this.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
            this.FontFamily = new System.Windows.Media.FontFamily("Consolas");
            this.FontSize = 12;
        }

        public RoslynExpressionEditorInstance(Size initialSize) : this()
        {
            this.Width = initialSize.Width;
            this.Height = initialSize.Height;
        }

        public void UpdateInstance(List<ModelItem> variables, string text)
        {
            this.Text = text;
            if (variables != null)
                try
                {
                    if (variables.Count > 0) {
                        var variablesSerialized = variables.Select(v =>
                        {
                           return (v.GetCurrentValue() is System.Activities.Variable c) ? (c.Type.FullName + " " + c.Name + ";\n") : "";
                        }).ToArray();
                        this.variableDeclarations = string.Join("", variablesSerialized);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
        }

        private void TextArea_TextEntered(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                try
                {
                    string startString = RoslynExpressionEditorService.Instance.UsingNamespaces 
                        + "using System; using System.Collections.Generic; using System.Text; namespace SomeNamespace { public class NotAProgram { private void SomeMethod() { "
                        + variableDeclarations + "var blah = ";
                    string endString = " ; } } }";
                    string codeString = startString + this.Text.Substring(0, this.CaretOffset) + endString;

                    var tree = CSharpSyntaxTree.ParseText(codeString);

                    var root = (CompilationUnitSyntax)tree.GetRoot();

                    var compilation = CSharpCompilation.Create("CustomIntellisense")
                                               .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                                               .AddSyntaxTrees(tree);

                    var model = compilation.GetSemanticModel(tree);

                    var exprString = root.FindToken(codeString.LastIndexOf('.') - 1).Parent;

                    var literalInfo = model.GetTypeInfo(exprString);

                    var stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type;
                    IList<ISymbol> symbols = new List<ISymbol>() { };
                    foreach (var s in (from method in stringTypeSymbol.GetMembers() where method.DeclaredAccessibility == Accessibility.Public select method).Distinct())
                        symbols.Add(s);

                    if (symbols != null && symbols.Count > 0)
                    {
                        completionWindow = new CompletionWindow(this.TextArea);
                        IList<ICompletionData> data = completionWindow.CompletionList.CompletionData;
                        data.Clear();
                        var distinctSymbols = from s in symbols group s by s.Name into g select new { Name = g.Key, Symbols = g };
                        foreach (var g in distinctSymbols.OrderBy(s => s.Name))
                        {
                            data.Add(new QueryCompletionData(g.Name, g.Symbols.ToArray()));
                        }

                        completionWindow.Show();
                        completionWindow.Closed += delegate
                        {
                            completionWindow = null;
                        };
                    }
                }
                catch (Exception ex) {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        private void TextArea_TextEntering(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && completionWindow != null)
            {
                if (!char.IsLetterOrDigit(e.Text[0]))
                {
                    // Whenever a non-letter is typed while the completion window is open,
                    // insert the currently selected element.
                    completionWindow.CompletionList.RequestInsertion(e);
                }
            }
            // Do not set e.Handled=true.<commit_msg>commit code of cloudhack in issue #7<commit_after>﻿using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.AvalonEdit.Highlighting;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using RehostedWorkflowDesigner.Helpers;
using System;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.View;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace RehostedWorkflowDesigner.CSharpExpressionEditor
{
    public class RoslynExpressionEditorInstance : TextEditor, IExpressionEditorInstance
    {
        private CompletionWindow completionWindow;
        private string variableDeclarations;

        public RoslynExpressionEditorInstance()
        {
            this.TextArea.TextEntering += TextArea_TextEntering;
            this.TextArea.TextEntered += TextArea_TextEntered;
            this.TextArea.LostKeyboardFocus += TextArea_LostFocus; // Need to detach events.

            this.SyntaxHighlighting = HighlightingManager.Instance.GetDefinition("C#");
            this.FontFamily = new System.Windows.Media.FontFamily("Consolas");
            this.FontSize = 12;
        }

        public RoslynExpressionEditorInstance(Size initialSize) : this()
        {
            this.Width = initialSize.Width;
            this.Height = initialSize.Height;
        }

        public void UpdateInstance(List<ModelItem> variables, string text)
        {
            this.Text = text;
            if (variables != null)
                try
                {
                    if (variables.Count > 0)
                    {
                        this.variableDeclarations = string.Join("", variables.Select(v =>
                        {
                            var c = v.GetCurrentValue() as System.Activities.Variable;
                            if (c != null)
                                return c.Type.FullName + " " + c.Name + ";\n";
                            var d = v.GetCurrentValue() as System.Activities.DelegateArgument;
                            if (d != null)
                                return d.Type.FullName + " " + d.Name + ";\n";
                            return null;
                        }).ToArray());
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
        }

        private void TextArea_TextEntered(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (e.Text == ".")
            {
                try
                {
                    string startString = RoslynExpressionEditorService.Instance.UsingNamespaces
                        + "using System; using System.Collections.Generic; using System.Text; namespace SomeNamespace { public class NotAProgram { private void SomeMethod() { "
                        + variableDeclarations + "var blah = ";
                    string endString = " ; } } }";
                    string codeString = startString + this.Text.Substring(0, this.CaretOffset) + endString;

                    var tree = CSharpSyntaxTree.ParseText(codeString);

                    var root = (CompilationUnitSyntax)tree.GetRoot();

                    var compilation = CSharpCompilation.Create("CustomIntellisense")
                                               .AddReferences(MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                                               .AddSyntaxTrees(tree);

                    var model = compilation.GetSemanticModel(tree);

                    var exprString = root.FindToken(codeString.LastIndexOf('.') - 1).Parent;

                    var literalInfo = model.GetTypeInfo(exprString);

                    var stringTypeSymbol = (INamedTypeSymbol)literalInfo.Type;
                    IList<ISymbol> symbols = new List<ISymbol>() { };
                    foreach (var s in (from method in stringTypeSymbol.GetMembers() where method.DeclaredAccessibility == Accessibility.Public select method).Distinct())
                        symbols.Add(s);

                    if (symbols != null && symbols.Count > 0)
                    {
                        completionWindow = new CompletionWindow(this.TextArea);
                        IList<ICompletionData> data = completionWindow.CompletionList.CompletionData;
                        data.Clear();
                        var distinctSymbols = from s in symbols group s by s.Name into g select new { Name = g.Key, Symbols = g };
                        foreach (var g in distinctSymbols.OrderBy(s => s.Name))
                        {
                            data.Add(new QueryCompletionData(g.Name, g.Symbols.ToArray()));
                        }

                        completionWindow.Show();
                        completionWindow.Closed += delegate
                        {
                            completionWindow = null;
                        };
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
        }

        private void TextArea_TextEntering(object sender, System.Windows.Input.TextCompositionEventArgs e)
        {
            if (e.Text.Length > 0 && completionWindow != null)
            {
                if (!char.IsLetterOrDigit(e.Text[0]))
                {
                    // Whenever a non-letter is typed while the completion window is open,
                    // insert the currently selected element.
                    completionWindow.CompletionList.RequestInsertion(e);
                }
            }
            // Do not set e.Handled=true.
{'fraction_non_alphanumeric': 0.0832824094281973, 'fraction_numerical': 0.0014840680925360104, 'mean_word_length': 1.5469097376611827, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6616506', 'n_tokens_mistral': 2737, 'n_tokens_neox': 2562, 'n_words': 550}