public CodeBlock(FsiSession session, IHighlightingDefinition syntaxHighlighting)
 {
     this.Document = new TextDocument("");
     this.session = session;
     this.syntaxHighlighting = syntaxHighlighting;
     this.run = new RelayCommand(OnRun, CanRun);
 }
        public MainWindow()
        {
            // Load our custom highlighting definition
            //IHighlightingDefinition customHighlighting;
            using (Stream s = typeof(MainWindow).Assembly.GetManifestResourceStream("TestWpfC.CustomHighlighting.xshd"))
            {
                if (s == null)
                    throw new InvalidOperationException("Could not find embedded resource");
                using (XmlReader reader = new XmlTextReader(s))
                {
                    customHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.
                        HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }
            // and register it in the HighlightingManager
            HighlightingManager.Instance.RegisterHighlighting("Custom Highlighting", new string[] { ".cool" }, customHighlighting);


            InitializeComponent();


            textEditor.SyntaxHighlighting = customHighlighting;

            HighlightingComboBox_SelectionChanged(null, null);

            //textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
            //textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;

            DispatcherTimer foldingUpdateTimer = new DispatcherTimer();
            foldingUpdateTimer.Interval = TimeSpan.FromSeconds(2);
            foldingUpdateTimer.Tick += foldingUpdateTimer_Tick;
            foldingUpdateTimer.Start();
        }
        public IList<ICompletionData> GetCompletionDatas(IHighlightingDefinition language) {
            if (language == null) return null;
            if (dataDict.ContainsKey(language)) return dataDict[language];
            dataDict.Add(language, new List<ICompletionData>());
            var datas = dataDict[language];
            //以后ecp格式改用自己定义的xml格式
            string path = Path.Combine( _cfgPath,language.Name);

            if (Directory.Exists(path) == false) return datas;

            foreach(string file in Directory.GetFiles(path)) {
                using (StreamReader sr = new StreamReader(file)) {
                    //这里改用xmlSerialize
                    //To Do
                    try {
                        LoadData(datas, sr);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        continue;
                    }
                }
            }
            return datas;
        }
			IHighlightingDefinition GetDefinition()
			{
				Func<IHighlightingDefinition> func;
				lock (lockObj) {
					if (this.definition != null)
						return this.definition;
					func = this.lazyLoadingFunction;
				}
				Exception exception = null;
				IHighlightingDefinition def = null;
				try {
					using (var busyLock = BusyManager.Enter(this)) {
						if (!busyLock.Success)
							throw new InvalidOperationException("Tried to create delay-loaded highlighting definition recursively. Make sure the are no cyclic references between the highlighting definitions.");
						def = func();
					}
					if (def == null)
						throw new InvalidOperationException("Function for delay-loading highlighting definition returned null");
				} catch (Exception ex) {
					exception = ex;
				}
				lock (lockObj) {
					this.lazyLoadingFunction = null;
					if (this.definition == null && this.storedException == null) {
						this.definition = def;
						this.storedException = exception;
					}
					if (this.storedException != null)
						throw new HighlightingDefinitionInvalidException("Error delay-loading highlighting definition", this.storedException);
					return this.definition;
				}
			}
 /// <summary>
 /// Creates a new HighlightingColorizer instance.
 /// </summary>
 /// <param name="ruleSet">The root highlighting rule set.</param>
 public PythonConsoleHighlightingColorizer(IHighlightingDefinition highlightingDefinition, TextDocument document)
     : base(new DocumentHighlighter(document, highlightingDefinition  ))
 {
     if (document == null)
         throw new ArgumentNullException("document");
     this.document = document;
 }
        /// <summary>
        /// Creates a new HighlightingColorizer instance.
        /// </summary>
        /// <param name="definition">The highlighting definition.</param>
        public ThemedHighlightingColorizer(IHighlightingDefinition definition)
            : this()
        {
            if (definition == null)
                throw new ArgumentNullException("definition");

            this.definition = definition;
        }
Beispiel #7
0
 private void LoadHighlightingDefinition()
 {
   var xshdUri = App.GetResourceUri("simai.xshd");
   var rs = Application.GetResourceStream(xshdUri);
   var reader = new System.Xml.XmlTextReader(rs.Stream);
   definition = HighlightingLoader.Load(reader, HighlightingManager.Instance);
   reader.Close();
 }
Beispiel #8
0
		void Decompile(ModuleDef module, BamlDocument document, Language lang,
			ITextOutput output, out IHighlightingDefinition highlight, CancellationToken token) {
			var decompiler = new XamlDecompiler();
			var xaml = decompiler.Decompile(module, document, token);

			output.Write(xaml.ToString(), TextTokenType.Text);
			highlight = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
		}
Beispiel #9
0
		/// <summary>
		/// Converts a readonly TextDocument to a Block and applies the provided highlighting definition.
		/// </summary>
		public static Block ConvertTextDocumentToBlock(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition)
		{
			IHighlighter highlighter;
			if (highlightingDefinition != null)
				highlighter = new DocumentHighlighter(document, highlightingDefinition);
			else
				highlighter = null;
			return ConvertTextDocumentToBlock(document, highlighter);
		}
        /// <summary>
        /// Determine whether or not highlighting can be
        /// suppported by a particular folding strategy.
        /// </summary>
        /// <param name="syntaxHighlighting"></param>
        public void SetFolding(IHighlightingDefinition syntaxHighlighting)
        {
            if (syntaxHighlighting == null)
              {
            this.mFoldingStrategy = null;
              }
              else
              {
            switch (syntaxHighlighting.Name)
            {
              case "XML":
              case "HTML":
            mFoldingStrategy = new XmlFoldingStrategy() { ShowAttributesWhenFolded = true };
            this.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.DefaultIndentationStrategy();
            break;
              case "C#":
            this.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.CSharp.CSharpIndentationStrategy(this.Options);
            mFoldingStrategy = new CSharpBraceFoldingStrategy();
            break;
              case "C++":
              case "PHP":
              case "Java":
            this.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.CSharp.CSharpIndentationStrategy(this.Options);
            mFoldingStrategy = new CSharpBraceFoldingStrategy();
            break;
              case "VBNET":
            this.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.CSharp.CSharpIndentationStrategy(this.Options);
            mFoldingStrategy = new VBNetFoldingStrategy();
            break;
              default:
            this.TextArea.IndentationStrategy = new ICSharpCode.AvalonEdit.Indentation.DefaultIndentationStrategy();
            mFoldingStrategy = null;
            break;
            }

            if (mFoldingStrategy != null)
            {
              if (this.Document != null)
              {
            if (mFoldingManager == null)
              mFoldingManager = FoldingManager.Install(this.TextArea);

            this.mFoldingStrategy.UpdateFoldings(mFoldingManager, this.Document);
              }
              else
            this.mInstallFoldingManager = true;
            }
            else
            {
              if (mFoldingManager != null)
              {
            FoldingManager.Uninstall(mFoldingManager);
            mFoldingManager = null;
              }
            }
              }
        }
 public ScriptEditorViewModel(string name, string content, IHighlightingDefinition highlighting)
 {
     Name = name;
     Content = content;
     CurrentText = new StringText(content);
     Highlighting = highlighting;
     References = new BindableCollection<string>();
     UsingStatements = new BindableCollection<string>();
 }
		/// <summary>
		/// Creates a new DocumentHighlighter instance.
		/// </summary>
		public DocumentHighlighter(ReadOnlyDocument document, IHighlightingDefinition definition)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (definition == null)
				throw new ArgumentNullException("definition");
			this.document = document;
			this.definition = definition;
			InvalidateHighlighting();
		}
Beispiel #13
0
 static CodeEditor()
 {
     using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("JadeControls.EditorControl.cpp_rules.xshd"))
     {
         using (XmlTextReader reader = new XmlTextReader(s))
         {
             highlighDefinition = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader, HighlightingManager.Instance);
         }
     }
 }
		/// <summary>
		/// Creates a new DocumentHighlighter instance.
		/// </summary>
		public DocumentHighlighter(TextDocument document, IHighlightingDefinition definition)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (definition == null)
				throw new ArgumentNullException("definition");
			this.document = document;
			this.definition = definition;
			document.VerifyAccess();
			weakLineTracker = WeakLineTracker.Register(document, this);
			InvalidateHighlighting();
		}
		/// <summary>
		/// Creates a new DocumentHighlighter instance.
		/// </summary>
		public DocumentHighlighter(TextDocument document, IHighlightingDefinition definition)
		{
			if (document == null)
				throw new ArgumentNullException("document");
			if (definition == null)
				throw new ArgumentNullException("definition");
			this.document = document;
			this.definition = definition;
			this.engine = new HighlightingEngine(definition.MainRuleSet);
			document.VerifyAccess();
			weakLineTracker = WeakLineTracker.Register(document, this);
			InvalidateSpanStacks();
		}
 static AmlSimpleEditorHelper()
 {
   using (var stream = System.Reflection.Assembly.GetExecutingAssembly()
     .GetManifestResourceStream("InnovatorAdmin.resources.Aml.xshd"))
   {
     using (var reader = new System.Xml.XmlTextReader(stream))
     {
       _highlighter =
           ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(reader,
           ICSharpCode.AvalonEdit.Highlighting.HighlightingManager.Instance);
     }
   }
 }
 public InnerHighlightingManager()
 {
     if (!Directory.Exists("Resources"))
     {
         Directory.CreateDirectory("Resources");
         File.WriteAllText("Resources\\Java-LightMode.xshd", Resources.Java_LightMode);
         File.WriteAllText("Resources\\Java-DarkMode.xshd", Resources.Java_LightMode);
         File.WriteAllText("Resources\\Python-LightMode.xshd", Resources.Java_LightMode);
         File.WriteAllText("Resources\\Python-DarkMode.xshd", Resources.Java_LightMode);
         File.WriteAllText("Resources\\XML-LightMode.xshd", Resources.Java_LightMode);
         File.WriteAllText("Resources\\XML-DarkMode.xshd", Resources.Java_LightMode);
     }
     //Java highlighting
     _javaLight = HighlightingLoader.Load(new XmlTextReader(File.OpenRead("Resources\\Java-LightMode.xshd")), this);
     _javaDark  = HighlightingLoader.Load(new XmlTextReader(File.OpenRead("Resources\\Java-DarkMode.xshd")), this);
     //Python highlighting
     _pythonLight = HighlightingLoader.Load(new XmlTextReader(File.OpenRead("Resources\\Python-LightMode.xshd")), this);
     _pythonDark  = HighlightingLoader.Load(new XmlTextReader(File.OpenRead("Resources\\Python-DarkMode.xshd")), this);
     //XML highlighting
     _xmlLight = HighlightingLoader.Load(new XmlTextReader(File.OpenRead("Resources\\XML-LightMode.xshd")), this);
     _xmlDark  = HighlightingLoader.Load(new XmlTextReader(File.OpenRead("Resources\\XML-DarkMode.xshd")), this);
 }
Beispiel #18
0
        public override bool View(DecompilerTextView textView)
        {
            IHighlightingDefinition highlighting = null;

            textView.RunWithCancellation(
                token => Task.Factory.StartNew(
                    () => {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                try {
                    if (LoadBaml(output))
                    {
                        highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
                    }
                } catch (Exception ex) {
                    output.Write(ex.ToString());
                }
                return(output);
            }, token))
            .Then(output => textView.ShowNode(output, this, highlighting))
            .HandleExceptions();
            return(true);
        }
Beispiel #19
0
        internal override bool View(DecompilerTextView textView)
        {
            AvalonEditTextOutput    output       = new AvalonEditTextOutput();
            IHighlightingDefinition highlighting = null;

            textView.RunWithCancellation(
                token => Task.Factory.StartNew(
                    () => {
                try {
                    if (LoadBaml(output))
                    {
                        highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
                    }
                } catch (Exception ex) {
                    output.Write(ex.ToString());
                }
                return(output);
            }),
                t => textView.Show(t.Result, highlighting)
                );
            return(true);
        }
        public IList<ICompletionData> GetCompletionDatas(IHighlightingDefinition language) {
            if (language == null) return null;
            if (datas!=null) return datas;

            datas = new List<ICompletionData>();
            //以后ecp格式改用自己定义的xml格式
            string path = _cfgPath;
            using (StreamReader sr = new StreamReader(string.Format(path, language.Name, language.Name))) {
                while (sr.EndOfStream == false) {
                    string line = sr.ReadLine();
                    string[] snappets = line.Split('|');
                    DefaultCompletionData data;
                    if (snappets.Length == 2)
                        data = new DefaultCompletionData() { Text=snappets[0],Description=snappets[1],Content=snappets[0]};
                    else
                        data = new DefaultCompletionData() { Text = snappets[0], Content = snappets[0] };

                    datas.Add(data);
                }
            }
            return datas;
        }
Beispiel #21
0
        /// <summary>
        /// Registers a highlighting definition.
        /// </summary>
        /// <param name="name">The name to register the definition with.</param>
        /// <param name="extensions">The file extensions to register the definition for.</param>
        /// <param name="highlighting">The highlighting definition.</param>
        public void RegisterHighlighting(string name, string[] extensions, IHighlightingDefinition highlighting)
        {
            if (highlighting == null)
            {
                throw new ArgumentNullException("highlighting");
            }

            lock (lockObj) {
                allHighlightings.Add(highlighting);
                if (name != null)
                {
                    highlightingsByName[name] = highlighting;
                }
                if (extensions != null)
                {
                    foreach (string ext in extensions)
                    {
                        highlightingsByExtension[ext] = highlighting;
                    }
                }
            }
        }
Beispiel #22
0
        private IHighlightingDefinition LoadHighlightingDefinition()
        {
            HighlightingManager highlightingManager = HighlightingManager.Instance;

            if (!string.IsNullOrEmpty(CustomSyntaxHighlightingFileName))
            {
                using (var reader = new XmlTextReader(CustomSyntaxHighlightingFileName))
                    _syntaxDefinition = HighlightingLoader.LoadXshd(reader);
            }

            if (_syntaxDefinition != null)
            {
                IHighlightingDefinition highlightingDefinition =
                    HighlightingLoader.Load(_syntaxDefinition, highlightingManager);

                highlightingManager.RegisterHighlighting(_syntaxDefinition.Name,
                                                         _syntaxDefinition.Extensions.ToArray(),
                                                         highlightingDefinition);
            }

            return(highlightingManager.GetDefinition(_name));
        }
Beispiel #23
0
        public override bool View(TabPageModel tabPage)
        {
            AvalonEditTextOutput    output       = new AvalonEditTextOutput();
            IHighlightingDefinition highlighting = null;

            tabPage.ShowTextView(textView => textView.RunWithCancellation(
                                     token => Task.Factory.StartNew(
                                         () => {
                try
                {
                    // cache read XAML because stream will be closed after first read
                    if (xml == null)
                    {
                        using var data = OpenStream();
                        if (data == null)
                        {
                            output.Write("ILSpy: Failed opening resource stream.");
                            output.WriteLine();
                            return(output);
                        }
                        using (var reader = new StreamReader(data))
                        {
                            xml = reader.ReadToEnd();
                        }
                    }
                    output.Write(xml);
                    highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
                }
                catch (Exception ex)
                {
                    output.Write(ex.ToString());
                }
                return(output);
            }, token)
                                     ).Then(t => textView.ShowNode(t, this, highlighting))
                                 .HandleExceptions());
            tabPage.SupportsLanguageSwitching = false;
            return(true);
        }
        public EditorViewModel(IConfiguration configuration)
        {
            this.fontSize = 13.0;
            this.configuration = configuration;
            DispatcherHelper.Initialize();

            this.feedback = "";
            this.run = new RelayCommand(OnRun, CanRun);
            this.addCodeBlock = new RelayCommand(OnAddCodeBlock);

            this.increaseFontSize = new RelayCommand(OnIncreaseFont);
            this.decreaseFontSize = new RelayCommand(OnDecreaseFont);

            var fsiPath = this.configuration.FsiLocation; //@"C:\Program Files (x86)\Microsoft F#\v4.0\fsi.exe";
            this.session = new FsiSession(fsiPath);

            this.Session.Start();
            this.Session.OutputReceived += OnOutputReceived;
            this.Session.ErrorReceived += OnErrorReceived;

            var editorLocation = Assembly.GetExecutingAssembly().Location;
            var editorPath = Path.GetDirectoryName(editorLocation);
            var highlightFileName = "FSharpHighlighting.xshd";
            var highlightFileLocation = Path.Combine(editorPath, highlightFileName);

            using (var stream = File.OpenRead(highlightFileLocation))
            {
                using (var reader = new XmlTextReader(stream))
                {
                    this.syntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }

            this.codeBlocks = new ObservableCollection<CodeBlock>();
            this.CodeBlocks.Add(new CodeBlock(this.Session, this.syntaxHighlighting));

            this.feedbackBlocks = new ObservableCollection<FeedbackBlock>();
        }
Beispiel #25
0
        /// <summary>
        /// 为 <see cref="ICSharpCode.AvalonEdit.TextEditor"/> 实现一个简单的C#自动补全
        /// </summary>
        /// <param name="textEditor">要绑定的 TextEditor 实例</param>
        /// <param name="QuickerVarInfo">Quicker的动作变量信息转换的JArray</param>
        /// <param name="CustomVarTypeDefine">键为变量名,值为其对应的变量类型,用于为一些特殊变量指定类型,比如 _eval 变量的变量类型为 EvalContext</param>
        public CodeCompletion(
            TextEditor textEditor,
            JArray QuickerVarInfo = null,
            Dictionary <string, List <Type> > CustomVarTypeDefine = null)
        {
            if (QuickerVarInfo != null)
            {
                this.quickerVarInfo = QuickerVarInfo;
            }
            if (CustomVarTypeDefine != null)
            {
                this.CustomVarTypeDefine = CustomVarTypeDefine;
            }

            textEditor.TextArea.TextEntered  += TextEnteredHandler;
            textEditor.TextArea.TextEntering += TextEnteringHandler;
            textEditor.KeyDown += OnKeyDown;
            using (StringReader sr = new StringReader(CodeCompletion.rm.GetString("DescriptionHighlight")))
                using (XmlReader xmlReader = XmlReader.Create(sr))
                {
                    DescriptionHighlighting = HighlightingLoader.Load(xmlReader, HighlightingManager.Instance);
                }
        }
Beispiel #26
0
        /// <summary>
        /// Export the current content of the text editor as HTML.
        /// </summary>
        /// <param name="defaultFileName"></param>
        /// <param name="showLineNumbers"></param>
        /// <param name="alternateLineBackground"></param>
        public void ExportToHtml(string defaultFileName       = "",
                                 bool showLineNumbers         = true,
                                 bool alternateLineBackground = true)
        {
            string exportHtmlFileFilter = Util.Local.Strings.STR_ExportHTMLFileFilter;

            // Create and configure SaveFileDialog.
            FileDialog dlg = new SaveFileDialog()
            {
                ValidateNames = true,
                AddExtension  = true,
                Filter        = exportHtmlFileFilter,
                FileName      = defaultFileName
            };

            // Show dialog; return if canceled.
            if (!dlg.ShowDialog(Application.Current.MainWindow).GetValueOrDefault())
            {
                return;
            }

            defaultFileName = dlg.FileName;

            IHighlightingDefinition highlightDefinition = HighlightingDefinition;

            HtmlWriter w = new HtmlWriter()
            {
                ShowLineNumbers         = showLineNumbers,
                AlternateLineBackground = alternateLineBackground
            };

            string html = w.GenerateHtml(Text, highlightDefinition);

            File.WriteAllText(defaultFileName, @"<html><body>" + html + @"</body></html>");

            System.Diagnostics.Process.Start(defaultFileName); // view in browser
        }
Beispiel #27
0
        static DeclarationEditBox()
        {
            Uri uri = new Uri("pack://application:,,,/Lithnet.Acma.Presentation;component/Resources/AcmaDLNoAttributes.xshd", UriKind.Absolute);

            using (Stream s = Application.GetResourceStream(uri).Stream)
            {
                using (XmlTextReader reader = new XmlTextReader(s))
                {
                    acmaDLNoAttributes = HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }

            uri = new Uri("pack://application:,,,/Lithnet.Acma.Presentation;component/Resources/AcmaDL.xshd", UriKind.Absolute);


            using (Stream s = Application.GetResourceStream(uri).Stream)
            {
                using (XmlTextReader reader = new XmlTextReader(s))
                {
                    acmaDLAttributes = HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }

            ActiveConfig.XmlConfigChanged          += ActiveConfig_XmlConfigChanged;
            ActiveConfig.DatabaseConnectionChanged += ActiveConfig_DatabaseConnectionChanged;

            if (ActiveConfig.DB != null)
            {
                ActiveConfig.DB.AttributesBindingList.ListChanged += AttributesBindingList_ListChanged;
                ActiveConfig.DB.ConstantsBindingList.ListChanged  += ConstantsBindingList_ListChanged;
            }

            if (ActiveConfig.XmlConfig != null)
            {
                ActiveConfig.XmlConfig.Transforms.CollectionChanged += Transforms_CollectionChanged;
            }
        }
        /// <summary>
        /// Ensures that the highlighting definition is loaded.
        /// </summary>
        /// <returns>
        /// <see langword="true"/> if the highlighting definition is valid; otherwise,
        /// <see langword="false"/>.
        /// </returns>
        private bool EnsureDefinition()
        {
            if (_isLoading)
            {
                throw new InvalidOperationException("Recursive syntax highlighting definition detected. Make sure that there are no cyclic reference between syntax highlighting definitions.");
            }

            if (_theme != _themeService.Theme)
            {
                // Reload definition.
                _theme      = _themeService.Theme;
                _definition = null;

                try
                {
                    _isLoading = true;

                    // Look for themes in the following order.
                    var keys = new[] { _theme, "Generic", "Default", string.Empty, null };
                    foreach (var key in keys)
                    {
                        _definition = LoadDefinition(key);
                        if (_definition != null)
                        {
                            return(true);
                        }
                    }
                }
                finally
                {
                    _isLoading = false;
                }
            }

            return(_definition != null);
        }
Beispiel #29
0
        public override bool View(TabPageModel tabPage)
        {
            IHighlightingDefinition highlighting = null;

            tabPage.SupportsLanguageSwitching = false;
            tabPage.ShowTextView(textView => textView.RunWithCancellation(
                                     token => Task.Factory.StartNew(
                                         () => {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                try
                {
                    LoadBaml(output, token);
                    highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
                }
                catch (Exception ex)
                {
                    output.Write(ex.ToString());
                }
                return(output);
            }, token))
                                 .Then(output => textView.ShowNode(output, this, highlighting))
                                 .HandleExceptions());
            return(true);
        }
        public AsScriptControl()
        {
            string assemblyName = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase;
            extensionPath_ = System.IO.Path.GetDirectoryName(assemblyName).Replace("file:\\", "").Replace("\\", "/");

            InitializeComponent();
            InitializeScriptEngine();

            textboxOutput.Document.UndoStack.SizeLimit = 0;
            textboxOutput.WordWrap = true;

            VSColorTheme.ThemeChanged += VSColorThemeChanged;

            darkCustomHighlighting_ = LoadHighlighting("mkkim1129.ASmallGoodThing.Resources.PythonDark.xshd");
            lightCustomHighlighting_ = LoadHighlighting("mkkim1129.ASmallGoodThing.Resources.PythonLight.xshd");
            UpdateHeghlighting();

            AddScriptTabFile(null);

            builtInFunctionTable_.Add(".cls", () => textboxOutput.Text = "" );
            builtInFunctionTable_.Add(".restart", () => InitializeScriptEngine() );
            builtInFunctionTable_.Add(".run", () => RunScript() );
            builtInFunctionTable_.Add(".sel", () => RunSelectedText() );
        }
Beispiel #31
0
        public static void Init()
        {
            if (Table == null)
            {
                var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("QueryDesk.Resources.Table_748.png");
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                Table = decoder.Frames[0];
            }

            if (Field == null)
            {
                var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("QueryDesk.Resources.Template_514.png");
                PngBitmapDecoder decoder = new PngBitmapDecoder(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
                Field = decoder.Frames[0];
            }

            if (SQLHighlighter == null)
            {
                var reader = XmlReader.Create(Assembly.GetExecutingAssembly().GetManifestResourceStream("QueryDesk.Resources.SQL.xshd"));
                SQLHighlighter = HighlightingLoader.LoadXshd(reader);

                SQLSyntaxHiglighting = HighlightingLoader.Load(SQLHighlighter, HighlightingManager.Instance);
            }
        }
        public MainWindow()
        {
            // Load our custom highlighting definition
            //IHighlightingDefinition customHighlighting;
            using (Stream s = typeof(MainWindow).Assembly.GetManifestResourceStream("TestWpfC.CustomHighlighting.xshd"))
            {
                if (s == null)
                {
                    throw new InvalidOperationException("Could not find embedded resource");
                }
                using (XmlReader reader = new XmlTextReader(s))
                {
                    customHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.
                                         HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }
            // and register it in the HighlightingManager
            HighlightingManager.Instance.RegisterHighlighting("Custom Highlighting", new string[] { ".cool" }, customHighlighting);


            InitializeComponent();


            textEditor.SyntaxHighlighting = customHighlighting;

            HighlightingComboBox_SelectionChanged(null, null);

            //textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering;
            //textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered;

            DispatcherTimer foldingUpdateTimer = new DispatcherTimer();

            foldingUpdateTimer.Interval = TimeSpan.FromSeconds(2);
            foldingUpdateTimer.Tick    += foldingUpdateTimer_Tick;
            foldingUpdateTimer.Start();
        }
Beispiel #33
0
		void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
		{
			if (colorizer != null) {
				this.TextArea.TextView.LineTransformers.Remove(colorizer);
				colorizer = null;
			}
			if (newValue != null) {
				TextView textView = this.TextArea.TextView;
				colorizer = new HighlightingColorizer(textView, newValue.MainRuleSet);
				textView.LineTransformers.Insert(0, colorizer);
			}
		}
        /// <summary>
        /// This method is executed via <seealso cref="TextEditor"/> class when the Highlighting for
        /// a text display is changed durring the live time of the control.
        /// </summary>
        /// <param name="newValue"></param>
        protected override void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
        {
            base.OnSyntaxHighlightingChanged(newValue);

              if (newValue != null)
            this.SetFolding(newValue);
        }
        /// <summary>
        /// Registers a highlighting definition.
        /// </summary>
        /// <param name="name">The name to register the definition with.</param>
        /// <param name="extensions">The file extensions to register the definition for.</param>
        /// <param name="highlighting">The highlighting definition.</param>
        public void RegisterHighlighting(string name, string[] extensions, IHighlightingDefinition highlighting)
        {
            if (highlighting == null)
                throw new ArgumentNullException("highlighting");

            lock (lockObj) {
                allHighlightings.Add(highlighting);
                if (name != null) {
                    highlightingsByName[name] = highlighting;
                }
                if (extensions != null) {
                    foreach (string ext in extensions) {
                        highlightingsByExtension[ext] = highlighting;
                    }
                }
            }
        }
        /// <summary>
        /// Sets the editor options.
        /// </summary>
        /// <param name="editor">The editor.</param>
        /// <param name="leftSide">if set to <c>true</c> [left side].</param>
        protected virtual void SetEditorOptions(TextEditor editor, bool leftSide)
        {
            var ctx = new ContextMenu
            {
                Items = new List <MenuItem>()
                {
                    new MenuItem()
                    {
                        Header  = ViewModel.EditorCopy,
                        Command = ReactiveCommand.Create(() => editor.Copy()).DisposeWith(Disposables)
                    },
                    new MenuItem()
                    {
                        Header  = ViewModel.EditorCut,
                        Command = ReactiveCommand.Create(() => editor.Cut()).DisposeWith(Disposables)
                    },
                    new MenuItem()
                    {
                        Header  = ViewModel.EditorPaste,
                        Command = ReactiveCommand.Create(() => editor.Paste()).DisposeWith(Disposables)
                    },
                    new MenuItem()
                    {
                        Header  = ViewModel.EditorDelete,
                        Command = ReactiveCommand.Create(() => editor.Delete()).DisposeWith(Disposables)
                    },
                    new MenuItem()
                    {
                        Header  = ViewModel.EditorSelectAll,
                        Command = ReactiveCommand.Create(() => editor.SelectAll()).DisposeWith(Disposables)
                    },
                    new MenuItem()
                    {
                        Header = "-"
                    },
                    new MenuItem()
                    {
                        Header  = ViewModel.EditorUndo,
                        Command = ReactiveCommand.Create(() => editor.Undo()).DisposeWith(Disposables)
                    },
                    new MenuItem()
                    {
                        Header  = ViewModel.EditorRedo,
                        Command = ReactiveCommand.Create(() => editor.Redo()).DisposeWith(Disposables)
                    }
                }
            };

            editor.ContextMenu = ctx;

            editor.Options = new TextEditorOptions()
            {
                ConvertTabsToSpaces = true,
                IndentationSize     = 4
            };
            editor.TextArea.ActiveInputHandler = new Implementation.AvaloniaEdit.TextAreaInputHandler(editor);

            ViewModel.WhenAnyValue(p => p.EditingYaml).Subscribe(s =>
            {
                setEditMode();
            }).DisposeWith(Disposables);
            setEditMode();

            void setEditMode()
            {
                if (ViewModel.EditingYaml)
                {
                    if (yamlHighlightingDefinition == null)
                    {
                        yamlHighlightingDefinition = GetHighlightingDefinition(Constants.Resources.YAML);
                    }
                    editor.SyntaxHighlighting = yamlHighlightingDefinition;
                }
                else
                {
                    if (pdxScriptHighlightingDefinition == null)
                    {
                        pdxScriptHighlightingDefinition = GetHighlightingDefinition(Constants.Resources.PDXScript);
                    }
                    editor.SyntaxHighlighting = pdxScriptHighlightingDefinition;
                }
            }

            bool manualAppend = false;

            editor.TextChanged += (sender, args) =>
            {
                // It's a hack I know see: https://github.com/AvaloniaUI/AvaloniaEdit/issues/99.
                // I'd need to go into the code to fix it and it ain't worth it. There doesn't seem to be any feedback on this issue as well.
                var lines = editor.Text.SplitOnNewLine(false).ToList();
                if (lines.Count > 3)
                {
                    if (manualAppend)
                    {
                        manualAppend = false;
                        return;
                    }
                    var carretOffset = editor.CaretOffset;
                    for (int i = 1; i <= 3; i++)
                    {
                        var last = lines[^ i];
Beispiel #37
0
        //MyCompletionWindow myCompletionWindow;
        public MainWindow()
        {
            Instance = this;
            Environment.SetEnvironmentVariable("NATURLPATH", Path.GetFullPath("resources"));
            MaxHeight = SystemParameters.MaximizedPrimaryScreenHeight;
            //Loading Settings configuration from XML
            UserSettings.LoadUserSettings("resources/settings.xml");
            language         = UserSettings.language;
            _warningSeverity = UserSettings.warningSeverity;
            //Unused warning severity yet.
            InitializeComponent();
            TextEditor textEditor =
                (TextEditor)((Grid)((TabItem)FindName("Tab_id_")).FindName(
                                 "grid_codebox")).Children[0];
            XmlTextReader reader = new XmlTextReader(UserSettings.syntaxFilePath);

            _highlightingDefinition =
                HighlightingLoader.Load(reader, HighlightingManager.Instance);

            textEditor.SyntaxHighlighting = _highlightingDefinition;
            defaultSize = UserSettings.defaultFontSize;
            reader.Close();
            string[] paths =
                File.ReadAllLines("resources/lastfiles.txt");
            tabitem = XamlWriter.Save(FindName("Tab_id_"));
            ((TabablzControl)FindName("TabControl")).Items.RemoveAt(0);

            Process lspServer = new Process
            {
                StartInfo =
                {
                    FileName              = "resources/server.exe",
                    //C:\\Users\\Adrian\\Desktop\\TCP Server\\TCP Server\\bin\\Debug\\netcoreapp3.1\\TCP Server.exe
                    EnvironmentVariables  =
                    {
                        ["NATURLPATH"] =
                            Path.GetFullPath("resources")
                    },
                    CreateNoWindow        = true,
                    RedirectStandardError = true
                },
            };

            //lspServer.OutputDataReceived += (sender, args) => Console.WriteLine("Server log:" + args.Data);
            //lspServer.ErrorDataReceived += (sender, args) => Console.WriteLine("Server log(err):" + args.Data);
            LspSender = new LspHandler(this, lspServer);
            LspSender.InitializeRequest(Process.GetCurrentProcess().Id,
                                        "file://" + Directory.GetCurrentDirectory(),
                                        new ClientCapabilities(
                                            new TextDocumentClientCapabilities(
                                                new CompletionClientCapabilities(),
                                                new DefinitionClientCapabilities(),
                                                new PublishDiagnosticsClientCapabilities())));
            if (paths.Length == 0)
            {
                NewTabItems(++_tabInt, null);
            }
            else
            {
                foreach (string path in paths)
                {
                    NewTabItems(++_tabInt, path);
                }
            }

            _lastFocusedTextEditor =
                (TextEditor)FindName("CodeBox" + _currenttabId);
            InitialiseLanguageComponents(language);
        }
Beispiel #38
0
 public LastOutput(ITextOutput output, IHighlightingDefinition highlighting)
 {
     this.output       = output;
     this.highlighting = highlighting;
 }
Beispiel #39
0
        public QueryDeveloperViewModel(Guid fileId, ExplicitConnection explicitConnection, IExplicitConnectionCache explicitConnectionCache, IHighlightingDefinition sqlHighlightingDefinition, ISnackbarMessageQueue snackbarMessageQueue, IDialogTargetFinder dialogTargetFinder)
        {
            if (explicitConnectionCache == null)
            {
                throw new ArgumentNullException(nameof(explicitConnectionCache));
            }

            FileId                   = fileId;
            _generalSettings         = new GeneralSettings(10);
            _explicitConnection      = explicitConnection;
            _explicitConnectionCache = explicitConnectionCache;

            FetchDocumentCommand    = new Command(o => QueryRunnerViewModel.Run($"SELECT * FROM root r WHERE r.id = '{DocumentId}'"));
            EditConnectionCommand   = new Command(sender => EditConnectionAsync((DependencyObject)sender));
            EditSettingsCommand     = new Command(sender => EditSettingsAsync((DependencyObject)sender));
            QueryRunnerViewModel    = new QueryRunnerViewModel(fileId, sqlHighlightingDefinition, () => _explicitConnection, () => _generalSettings, EditDocumentHandler, snackbarMessageQueue, dialogTargetFinder);
            DocumentEditorViewModel = new DocumentEditorViewModel(() => _explicitConnection, snackbarMessageQueue, dialogTargetFinder);

            SetName();
        }
Beispiel #40
0
 /// <summary>
 /// Creates the highlighting colorizer for the specified highlighting definition.
 /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions.
 /// </summary>
 /// <returns></returns>
 protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
 {
     if (highlightingDefinition == null)
         throw new ArgumentNullException("highlightingDefinition");
     return new HighlightingColorizer(highlightingDefinition);
 }
Beispiel #41
0
 /// <summary>
 /// Shows the given output in the text view.
 /// Cancels any currently running decompilation tasks.
 /// </summary>
 public void ShowNodes(AvalonEditTextOutput textOutput, ILSpyTreeNode[] nodes, IHighlightingDefinition highlighting = null)
 {
     // Cancel the decompilation task:
     if (currentCancellationTokenSource != null)
     {
         currentCancellationTokenSource.Cancel();
         currentCancellationTokenSource = null;                 // prevent canceled task from producing output
     }
     if (this.nextDecompilationRun != null)
     {
         // remove scheduled decompilation run
         this.nextDecompilationRun.TaskCompletionSource.TrySetCanceled();
         this.nextDecompilationRun = null;
     }
     ShowOutput(textOutput, highlighting);
     decompiledNodes = nodes;
 }
Beispiel #42
0
		public string GenerateHtml(TextDocument document, IHighlightingDefinition highlightDefinition)
		{
			return GenerateHtml(document, new DocumentHighlighter(document, highlightDefinition.MainRuleSet));
		}
		protected override IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
		{
			return new CustomizableHighlightingColorizer(
				highlightingDefinition.MainRuleSet,
				FetchCustomizations(highlightingDefinition.Name));
		}
 public SyntaxHighlightingManager(Settings settings)
     : base(settings)
 {
     this.HighlightingDefinition = GetSyntaxHighlighting();
     this.Observer.RegisterHandler(s => s.SyntaxHighlightingStyle, HandleSettingChange);
 }
Beispiel #45
0
 void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue)
 {
     if (colorizer != null) {
         this.TextArea.TextView.LineTransformers.Remove(colorizer);
         colorizer = null;
     }
     if (newValue != null) {
         colorizer = CreateColorizer(newValue);
         if (colorizer != null)
             this.TextArea.TextView.LineTransformers.Insert(0, colorizer);
     }
 }
 private void HandleSettingChange(Settings settings)
 {
     this.HighlightingDefinition = GetSyntaxHighlighting();
 }
Beispiel #47
0
 public QueryDeveloperViewModel(Guid fileId, IExplicitConnectionCache explicitConnectionCache, IHighlightingDefinition sqlHighlightingDefinition, ISnackbarMessageQueue snackbarMessageQueue, IDialogTargetFinder dialogTargetFinder)
     : this(fileId, null, explicitConnectionCache, sqlHighlightingDefinition, snackbarMessageQueue, dialogTargetFinder)
 {
 }
 static ConfigEditorDocument()
 {
     ThisSyntaxName = LoadAvalonEditSyntaxFiles(System.IO.Path.Combine(App.SyntaxFilesPath, "armaconfig.xshd"));
 }
Beispiel #49
0
 private static void ApplySchemeEntry(this IHighlightingDefinition def, string rule, string entry)
 {
     def.GetNamedColor(rule).MergeWith(StringToHighlightingColor(entry));
 }
Beispiel #50
0
 protected override IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
 {
     Debug.Assert(LanguageTokens != null);
     if (highlightingDefinition.Name == "C#" || highlightingDefinition.Name == "VB" ||
         highlightingDefinition.Name == "IL")
         return new NewHighlightingColorizer(this);
     return base.CreateColorizer(highlightingDefinition);
 }
Beispiel #51
0
 protected override IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
 {
     return new NitraHighlightingColorizer(this);
 }
Beispiel #52
0
 /// <summary>
 /// Creates a new HighlightingColorizer instance.
 /// </summary>
 /// <param name="definition">The highlighting definition.</param>
 public HighlightingColorizer(IHighlightingDefinition definition)
 {
     _definition = definition ?? throw new ArgumentNullException(nameof(definition));
 }
Beispiel #53
0
 /// <summary>
 /// Sets the Syntax Highlighter to a specific Highlighter
 /// </summary>
 /// <param name="def">Highlighting Definition</param>
 public void SetHighlighter(IHighlightingDefinition def)
 {
     String syntax;
     if (this._enableHighlighting)
     {
         this._editor.SyntaxHighlighting = def;
         syntax = (this._editor.SyntaxHighlighting == null) ? "None" : def.Name;
     }
     else
     {
         syntax = def.Name;
     }
     this._currSyntax = syntax;
     this.SetCurrentHighlighterChecked(syntax);
     this.SetCurrentValidator(syntax);
     this.SetCurrentAutoCompleter(syntax);
 }
Beispiel #54
0
        /// <summary>
        /// USER SELECTION ARRAY WILL BREAK AT THE FIRST ERROR
        /// This won't happen for other type of extraction like in diff mode where we have to skip errors
        /// </summary>
        /// <param name="selection"></param>
        /// <returns></returns>
        public static async Task GetUserSelection(IList selection)
        {
            _timer = Stopwatch.StartNew();
            ImageBoxVm.imageBoxViewModel.Reset();
            AvalonEditVm.avalonEditViewModel.Reset();
            ExtractStopVm.stopViewModel.IsEnabled    = true;
            ExtractStopVm.extractViewModel.IsEnabled = false;
            StatusBarVm.statusBarViewModel.Set(string.Empty, Properties.Resources.Loading);
            Tasks.TokenSource = new CancellationTokenSource();

            await Task.Run(() =>
            {
                foreach (var item in selection)
                {
                    if (Tasks.TokenSource.IsCancellationRequested)
                    {
                        throw new TaskCanceledException(Properties.Resources.Canceled);
                    }

                    Thread.Sleep(10); // this is actually useful because it smh unfreeze the ui so the user can cancel even tho it's a Task so...
                    if (item is ListBoxViewModel selected)
                    {
                        if (Globals.CachedPakFiles.TryGetValue(selected.PakEntry.PakFileName, out var r))
                        {
                            string mount = r.MountPoint;
                            string ext   = selected.PakEntry.GetExtension();
                            switch (ext)
                            {
                            case ".ini":
                            case ".txt":
                            case ".bat":
                            case ".xml":
                            case ".h":
                            case ".uproject":
                            case ".uplugin":
                            case ".upluginmanifest":
                            case ".json":
                                {
                                    IHighlightingDefinition syntax = ext switch
                                    {
                                        ".ini" => AvalonEditVm.IniHighlighter,
                                        ".txt" => AvalonEditVm.IniHighlighter,
                                        ".bat" => AvalonEditVm.IniHighlighter,
                                        ".xml" => AvalonEditVm.XmlHighlighter,
                                        ".h" => AvalonEditVm.CppHighlighter,
                                        _ => AvalonEditVm.JsonHighlighter
                                    };
                                    using var asset  = GetMemoryStream(selected.PakEntry.PakFileName, mount + selected.PakEntry.GetPathWithoutExtension());
                                    asset.Position   = 0;
                                    using var reader = new StreamReader(asset);
                                    AvalonEditVm.avalonEditViewModel.Set(reader.ReadToEnd(), mount + selected.PakEntry.Name, syntax);
                                    break;
                                }

                            case ".locmeta":
                                {
                                    using var asset = GetMemoryStream(selected.PakEntry.PakFileName, mount + selected.PakEntry.GetPathWithoutExtension());
                                    asset.Position  = 0;
                                    AvalonEditVm.avalonEditViewModel.Set(JsonConvert.SerializeObject(new LocMetaReader(asset), Formatting.Indented), mount + selected.PakEntry.Name);
                                    break;
                                }

                            case ".locres":
                                {
                                    using var asset = GetMemoryStream(selected.PakEntry.PakFileName, mount + selected.PakEntry.GetPathWithoutExtension());
                                    asset.Position  = 0;
                                    AvalonEditVm.avalonEditViewModel.Set(JsonConvert.SerializeObject(new LocResReader(asset).Entries, Formatting.Indented), mount + selected.PakEntry.Name);
                                    break;
                                }

                            case ".udic":
                                {
                                    using var asset = GetMemoryStream(selected.PakEntry.PakFileName, mount + selected.PakEntry.GetPathWithoutExtension());
                                    asset.Position  = 0;
                                    AvalonEditVm.avalonEditViewModel.Set(JsonConvert.SerializeObject(new FOodleDictionaryArchive(asset).Header, Formatting.Indented), mount + selected.PakEntry.Name);
                                    break;
                                }

                            case ".bin":
                                {
                                    if (
                                        !selected.PakEntry.Name.Equals("FortniteGame/AssetRegistry.bin") && // this file is 85mb...
                                        selected.PakEntry.Name.Contains("AssetRegistry"))                   // only parse AssetRegistry (basically the ones in dynamic paks)
                                    {
                                        using var asset = GetMemoryStream(selected.PakEntry.PakFileName, mount + selected.PakEntry.GetPathWithoutExtension());
                                        asset.Position  = 0;
                                        AvalonEditVm.avalonEditViewModel.Set(JsonConvert.SerializeObject(new FAssetRegistryState(asset), Formatting.Indented), mount + selected.PakEntry.Name);
                                    }
                                    break;
                                }

                            case ".bnk":
                            case ".pck":
                                {
                                    using var asset = GetMemoryStream(selected.PakEntry.PakFileName, mount + selected.PakEntry.GetPathWithoutExtension());
                                    asset.Position  = 0;
                                    WwiseReader bnk = new WwiseReader(new BinaryReader(asset));
                                    Application.Current.Dispatcher.Invoke(delegate
                                    {
                                        DebugHelper.WriteLine("{0} {1} {2}", "[FModel]", "[Window]", $"Opening Audio Player for {selected.PakEntry.GetNameWithExtension()}");
                                        if (!FWindows.IsWindowOpen <Window>(Properties.Resources.AudioPlayer))
                                        {
                                            new AudioPlayer().LoadFiles(bnk.AudioFiles, mount + selected.PakEntry.GetPathWithoutFile());
                                        }
                                        else
                                        {
                                            ((AudioPlayer)FWindows.GetOpenedWindow <Window>(Properties.Resources.AudioPlayer)).LoadFiles(bnk.AudioFiles, mount + selected.PakEntry.GetPathWithoutFile());
                                        }
                                    });
                                    break;
                                }

                            case ".png":
                                {
                                    using var asset = GetMemoryStream(selected.PakEntry.PakFileName, mount + selected.PakEntry.GetPathWithoutExtension());
                                    asset.Position  = 0;
                                    ImageBoxVm.imageBoxViewModel.Set(SKBitmap.Decode(asset), mount + selected.PakEntry.Name);
                                    break;
                                }

                            case ".ushaderbytecode":
                                break;

                            default:
                                AvalonEditVm.avalonEditViewModel.Set(GetJsonProperties(selected.PakEntry, mount, true), mount + selected.PakEntry.Name);
                                break;
                            }

                            if (Properties.Settings.Default.AutoExport)
                            {
                                Export(selected.PakEntry, true);
                            }
                        }
                    }
                }
            }).ContinueWith(t =>
            {
                _timer.Stop();
                ExtractStopVm.stopViewModel.IsEnabled    = false;
                ExtractStopVm.extractViewModel.IsEnabled = true;

                if (t.Exception != null)
                {
                    Tasks.TaskCompleted(t.Exception);
                }
                else
                {
                    StatusBarVm.statusBarViewModel.Set(string.Format(Properties.Resources.TimeElapsed, _timer.ElapsedMilliseconds), Properties.Resources.Success);
                }
            },
                            TaskScheduler.FromCurrentSynchronizationContext());
        }
Beispiel #55
0
 protected override IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition)
 {
     return(new CustomizableHighlightingColorizer(
                highlightingDefinition.MainRuleSet,
                FetchCustomizations(highlightingDefinition.Name)));
 }
Beispiel #56
0
        /// <summary>
        /// Shows the given output in the text view.
        /// </summary>
        void ShowOutput(AvalonEditTextOutput textOutput, IHighlightingDefinition highlighting = null, DecompilerTextViewState state = null)
        {
            Debug.WriteLine("Showing {0} characters of output", textOutput.TextLength);
            Stopwatch w = Stopwatch.StartNew();

            ClearLocalReferenceMarks();
            textEditor.ScrollToHome();
            if (foldingManager != null)
            {
                FoldingManager.Uninstall(foldingManager);
                foldingManager = null;
            }
            textEditor.Document                  = null; // clear old document while we're changing the highlighting
            uiElementGenerator.UIElements        = textOutput.UIElements;
            referenceElementGenerator.References = textOutput.References;
            references       = textOutput.References;
            definitionLookup = textOutput.DefinitionLookup;
            textEditor.SyntaxHighlighting = highlighting;

            // Change the set of active element generators:
            foreach (var elementGenerator in activeCustomElementGenerators)
            {
                textEditor.TextArea.TextView.ElementGenerators.Remove(elementGenerator);
            }
            activeCustomElementGenerators.Clear();

            foreach (var elementGenerator in textOutput.elementGenerators)
            {
                textEditor.TextArea.TextView.ElementGenerators.Add(elementGenerator);
                activeCustomElementGenerators.Add(elementGenerator);
            }

            Debug.WriteLine("  Set-up: {0}", w.Elapsed); w.Restart();
            textEditor.Document = textOutput.GetDocument();
            Debug.WriteLine("  Assigning document: {0}", w.Elapsed); w.Restart();
            if (textOutput.Foldings.Count > 0)
            {
                if (state != null)
                {
                    state.RestoreFoldings(textOutput.Foldings);
                    textEditor.ScrollToVerticalOffset(state.VerticalOffset);
                    textEditor.ScrollToHorizontalOffset(state.HorizontalOffset);
                }
                foldingManager = FoldingManager.Install(textEditor.TextArea);
                foldingManager.UpdateFoldings(textOutput.Foldings.OrderBy(f => f.StartOffset), -1);
                Debug.WriteLine("  Updating folding: {0}", w.Elapsed); w.Restart();
            }

            // update debugger info
            DebugInformation.CodeMappings = textOutput.DebuggerMemberMappings.ToDictionary(m => m.MetadataToken);

            // update class bookmarks
            var document = textEditor.Document;

            manager.Bookmarks.Clear();
            foreach (var pair in textOutput.DefinitionLookup.definitions)
            {
                MemberReference member = pair.Key as MemberReference;
                int             offset = pair.Value;
                if (member != null)
                {
                    int line = document.GetLocation(offset).Line;
                    manager.Bookmarks.Add(new MemberBookmark(member, line));
                }
            }
        }
Beispiel #57
0
 public void ShowNode(AvalonEditTextOutput textOutput, ILSpyTreeNode node, IHighlightingDefinition highlighting = null)
 {
     ShowNodes(textOutput, new[] { node }, highlighting);
 }
        /// <summary>
        /// Converts a readonly TextDocument to a RichText and applies the provided highlighting definition.
        /// </summary>
        public static RichText ConvertTextDocumentToRichText(ReadOnlyDocument document, IHighlightingDefinition highlightingDefinition)
        {
            IHighlighter highlighter;

            if (highlightingDefinition != null)
            {
                highlighter = new DocumentHighlighter(document, highlightingDefinition);
            }
            else
            {
                highlighter = null;
            }
            return(ConvertTextDocumentToRichText(document, highlighter));
        }
        /// <summary>
        /// Change WPF theme.
        ///
        /// This method can be called when the theme is to be reseted by all means
        /// (eg.: when powering application up).
        ///
        /// !!! Use the CurrentTheme property to change !!!
        /// !!! the theme when App is running           !!!
        /// </summary>
        public void ResetTheme()
        {
            // Reset customized resources (if there are any from last change) and
            // enforce reload of original values from resource dictionary
            if (HighlightingManager.Instance.BackupDynResources != null)
            {
                try
                {
                    foreach (string t in HighlightingManager.Instance.BackupDynResources)
                    {
                        Application.Current.Resources[t] = null;
                    }
                }
                catch
                {
                }
                finally
                {
                    HighlightingManager.Instance.BackupDynResources = null;
                }
            }

            // Get WPF Theme definition from Themes Assembly
            ThemeBase nextThemeToSwitchTo = this.mThemesManager.SelectedTheme;

            this.SwitchToSelectedTheme(nextThemeToSwitchTo);

            // Backup highlighting names (if any) and restore highlighting associations after reloading highlighting definitions
            var HlNames = new List <string>();

            foreach (EdiViewModel f in this.Documents)
            {
                if (f != null)
                {
                    if (f.HighlightingDefinition != null)
                    {
                        HlNames.Add(f.HighlightingDefinition.Name);
                    }
                    else
                    {
                        HlNames.Add(null);
                    }
                }
            }

            // Is the current theme configured with a highlighting theme???
            ////this.Config.FindHighlightingTheme(
            HighlightingThemes hlThemes = nextThemeToSwitchTo.HighlightingStyles;

            // Re-load all highlighting patterns and re-apply highlightings
            HighlightingExtension.RegisterCustomHighlightingPatterns(hlThemes);

            //Re-apply highlightings after resetting highlighting manager
            List <EdiViewModel> l = this.Documents;

            for (int i = 0; i < l.Count; i++)
            {
                if (l[i] != null)
                {
                    if (HlNames[i] == null) // The highlighting is null if highlighting is switched off for this file(!)
                    {
                        continue;
                    }

                    IHighlightingDefinition hdef = HighlightingManager.Instance.GetDefinition(HlNames[i]);

                    if (hdef != null)
                    {
                        l[i].HighlightingDefinition = hdef;
                    }
                }
            }

            var backupDynResources = new List <string>();

            // Apply global styles to theming elements (dynamic resources in resource dictionary) of editor control
            if (HighlightingManager.Instance.HlThemes != null)
            {
                foreach (WidgetStyle w in HighlightingManager.Instance.HlThemes.GlobalStyles)
                {
                    ApplyWidgetStyle(w, backupDynResources);
                }
            }

            if (backupDynResources.Count > 0)
            {
                HighlightingManager.Instance.BackupDynResources = backupDynResources;
            }
        }
Beispiel #60
0
		public string GenerateHtml(string code, IHighlightingDefinition highlightDefinition)
		{
			return GenerateHtml(new TextDocument(code), highlightDefinition);
		}