Free cookie consent management tool by TermsFeed Policy Generator

source: branches/Async/HeuristicLab.CodeEditor/3.3/CodeEditor.cs @ 12912

Last change on this file since 12912 was 11436, checked in by jkarder, 10 years ago

#2262:

  • IEnumerable<T> extension methods are supported by the variables collection
  • INamedItem variables get the item's name per default
  • variables can be renamed by pressing F2
  • variables are removed faster
  • multiple variables can be selected
  • the code editor supports scrolling while scripts are executed
File size: 15.4 KB
Line 
1// CSharp Editor Example with Code Completion
2// Copyright (c) 2006, Daniel Grunwald
3// All rights reserved.
4//
5// Redistribution and use in source and binary forms, with or without modification, are
6// permitted provided that the following conditions are met:
7//
8// - Redistributions of source code must retain the above copyright notice, this list
9//   of conditions and the following disclaimer.
10//
11// - Redistributions in binary form must reproduce the above copyright notice, this list
12//   of conditions and the following disclaimer in the documentation and/or other materials
13//   provided with the distribution.
14//
15// - Neither the name of the ICSharpCode team nor the names of its contributors may be used to
16//   endorse or promote products derived from this software without specific prior written
17//   permission.
18//
19// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS &AS IS& AND ANY EXPRESS
20// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
21// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
22// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
26// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27
28using System;
29using System.CodeDom.Compiler;
30using System.Collections.Generic;
31using System.Diagnostics;
32using System.Drawing;
33using System.IO;
34using System.Reflection;
35using System.Threading;
36using System.Windows.Forms;
37using HeuristicLab.Common.Resources;
38using ICSharpCode.TextEditor;
39using ICSharpCode.TextEditor.Document;
40using Dom = ICSharpCode.SharpDevelop.Dom;
41using NRefactory = ICSharpCode.NRefactory;
42
43namespace HeuristicLab.CodeEditor {
44
45  public partial class CodeEditor : UserControl {
46
47    #region Fields & Properties
48
49    internal Dom.ProjectContentRegistry projectContentRegistry;
50    internal Dom.DefaultProjectContent projectContent;
51    internal Dom.ParseInformation parseInformation = new Dom.ParseInformation();
52    Dom.ICompilationUnit lastCompilationUnit;
53    Thread parserThread;
54
55    /// <summary>
56    /// Many SharpDevelop.Dom methods take a file name, which is really just a unique identifier
57    /// for a file - Dom methods don't try to access code files on disk, so the file does not have
58    /// to exist.
59    /// SharpDevelop itself uses internal names of the kind "[randomId]/Class1.cs" to support
60    /// code-completion in unsaved files.
61    /// </summary>
62    public const string DummyFileName = "edited.cs";
63
64    private IDocument Doc {
65      get {
66        return textEditor.Document;
67      }
68    }
69
70    private string prefix = "";
71    private TextMarker prefixMarker =
72      new TextMarker(0, 1, TextMarkerType.SolidBlock, Color.LightGray) {
73        IsReadOnly = true,
74      };
75    public string Prefix {
76      get {
77        return prefix;
78      }
79      set {
80        if (value == null) value = "";
81        if (prefix == value) return;
82        Doc.MarkerStrategy.RemoveMarker(prefixMarker);
83        Doc.Remove(0, prefix.Length);
84        prefix = value;
85        if (value.Length > 0) {
86          Doc.Insert(0, value);
87          prefixMarker.Offset = 0;
88          prefixMarker.Length = prefix.Length;
89          Doc.MarkerStrategy.AddMarker(prefixMarker);
90        }
91        Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
92        Doc.CommitUpdate();
93      }
94    }
95
96    private string suffix = "";
97    private TextMarker suffixMarker =
98      new TextMarker(0, 1, TextMarkerType.SolidBlock, Color.LightGray) {
99        IsReadOnly = true,
100      };
101    public string Suffix {
102      get {
103        return suffix;
104      }
105      set {
106        if (value == null) value = "";
107        if (suffix == value) return;
108        Doc.MarkerStrategy.RemoveMarker(suffixMarker);
109        Doc.Remove(Doc.TextLength - suffix.Length, suffix.Length);
110        suffix = value;
111        if (value.Length > 0) {
112          suffixMarker.Offset = Doc.TextLength;
113          Doc.Insert(Doc.TextLength, value);
114          suffixMarker.Length = suffix.Length;
115          Doc.MarkerStrategy.AddMarker(suffixMarker);
116        }
117        Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
118        Doc.CommitUpdate();
119      }
120    }
121
122    public string UserCode {
123      get {
124        return Doc.GetText(
125          prefix.Length,
126          Doc.TextLength - suffix.Length - prefix.Length);
127      }
128      set {
129        Doc.Replace(prefix.Length, Doc.TextLength - suffix.Length - prefix.Length, value);
130        Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
131        Doc.CommitUpdate();
132      }
133    }
134
135    public bool ReadOnly {
136      get { return Doc.ReadOnly; }
137      set { Doc.ReadOnly = value; }
138    }
139
140    #endregion
141
142    public event EventHandler TextEditorValidated;
143
144    protected void OnTextEditorValidated() {
145      if (TextEditorValidated != null)
146        TextEditorValidated(this, EventArgs.Empty);
147    }
148
149    public event EventHandler TextEditorTextChanged;
150
151    protected void OnTextEditorTextChanged() {
152      if (TextEditorTextChanged != null)
153        TextEditorTextChanged(this, EventArgs.Empty);
154    }
155
156    public CodeEditor() {
157      InitializeComponent();
158
159      textEditor.ActiveTextAreaControl.TextEditorProperties.SupportReadOnlySegments = true;
160
161      textEditor.SetHighlighting("C#");
162      textEditor.ShowEOLMarkers = false;
163      textEditor.ShowInvalidLines = false;
164      HostCallbackImplementation.Register(this);
165      CodeCompletionKeyHandler.Attach(this, textEditor);
166      ToolTipProvider.Attach(this, textEditor);
167
168      projectContentRegistry = new Dom.ProjectContentRegistry(); // Default .NET 2.0 registry
169      try {
170        string persistencePath = Path.Combine(Path.GetTempPath(), "HeuristicLab.CodeEditor");
171        if (!Directory.Exists(persistencePath))
172          Directory.CreateDirectory(persistencePath);
173        FileStream fs = File.Create(Path.Combine(persistencePath, "test.tmp"));
174        fs.Close();
175        File.Delete(Path.Combine(persistencePath, "test.tmp"));
176        // if we made it this far, enable on-disk parsing cache
177        projectContentRegistry.ActivatePersistence(persistencePath);
178      } catch (NotSupportedException) {
179      } catch (IOException) {
180      } catch (System.Security.SecurityException) {
181      } catch (UnauthorizedAccessException) {
182      } catch (ArgumentException) {
183      }
184      projectContent = new Dom.DefaultProjectContent();
185      projectContent.Language = Dom.LanguageProperties.CSharp;
186    }
187
188    protected override void OnLoad(EventArgs e) {
189      base.OnLoad(e);
190
191      if (DesignMode)
192        return;
193
194      textEditor.ActiveTextAreaControl.TextArea.KeyEventHandler += new ICSharpCode.TextEditor.KeyEventHandler(TextArea_KeyEventHandler);
195      textEditor.ActiveTextAreaControl.TextArea.DoProcessDialogKey += new DialogKeyProcessor(TextArea_DoProcessDialogKey);
196
197      parserThread = new Thread(ParserThread);
198      parserThread.IsBackground = true;
199      parserThread.Start();
200
201      textEditor.Validated += (s, a) => { OnTextEditorValidated(); };
202      textEditor.TextChanged += (s, a) => { OnTextEditorTextChanged(); };
203      InitializeImageList();
204    }
205
206    private void InitializeImageList() {
207      imageList1.Images.Clear();
208      imageList1.Images.Add("Icons.16x16.Class.png", VSImageLibrary.Class);
209      imageList1.Images.Add("Icons.16x16.Method.png", VSImageLibrary.Method);
210      imageList1.Images.Add("Icons.16x16.Property.png", VSImageLibrary.Properties);
211      imageList1.Images.Add("Icons.16x16.Field.png", VSImageLibrary.Field);
212      imageList1.Images.Add("Icons.16x16.Enum.png", VSImageLibrary.Enum);
213      imageList1.Images.Add("Icons.16x16.NameSpace.png", VSImageLibrary.Namespace);
214      imageList1.Images.Add("Icons.16x16.Event.png", VSImageLibrary.Event);
215    }
216
217    #region keyboard handlers: filter input in read-only areas
218
219    bool TextArea_KeyEventHandler(char ch) {
220      int caret = textEditor.ActiveTextAreaControl.Caret.Offset;
221      return caret < prefix.Length || caret > Doc.TextLength - suffix.Length;
222    }
223
224    bool TextArea_DoProcessDialogKey(Keys keyData) {
225      if (keyData == Keys.Return) {
226        int caret = textEditor.ActiveTextAreaControl.Caret.Offset;
227        if (caret < prefix.Length ||
228            caret > Doc.TextLength - suffix.Length) {
229          return true;
230        }
231      }
232      return false;
233    }
234
235    #endregion
236
237    public void ScrollAfterPrefix() {
238      int lineNr = prefix != null ? Doc.OffsetToPosition(prefix.Length).Line : 0;
239      textEditor.ActiveTextAreaControl.JumpTo(lineNr + 1);
240    }
241
242    private List<TextMarker> errorMarkers = new List<TextMarker>();
243    private List<Bookmark> errorBookmarks = new List<Bookmark>();
244    public void ShowCompileErrors(CompilerErrorCollection compilerErrors, string filename) {
245      Doc.MarkerStrategy.RemoveAll(m => errorMarkers.Contains(m));
246      Doc.BookmarkManager.RemoveMarks(m => errorBookmarks.Contains(m));
247      errorMarkers.Clear();
248      errorBookmarks.Clear();
249      errorLabel.Text = "";
250      errorLabel.ToolTipText = null;
251      if (compilerErrors == null)
252        return;
253      foreach (CompilerError error in compilerErrors) {
254        if (!error.FileName.EndsWith(filename)) {
255          errorLabel.Text = "Error in generated code";
256          errorLabel.ToolTipText = string.Format("{0}{1}:{2} -> {3}",
257            errorLabel.ToolTipText != null ? (errorLabel.ToolTipText + "\n\n") : "",
258            error.Line, error.Column,
259            error.ErrorText);
260          continue;
261        }
262        var startPosition = Doc.OffsetToPosition(prefix.Length);
263        if (error.Line == 1)
264          error.Column += startPosition.Column;
265        error.Line += startPosition.Line;
266        AddErrorMarker(error);
267        AddErrorBookmark(error);
268      }
269      Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
270      Doc.CommitUpdate();
271    }
272
273    private void AddErrorMarker(CompilerError error) {
274      var segment = GetSegmentAtOffset(error.Line, error.Column);
275      Color color = error.IsWarning ? Color.Blue : Color.Red;
276      var marker = new TextMarker(segment.Offset, segment.Length, TextMarkerType.WaveLine, color) {
277        ToolTip = error.ErrorText,
278      };
279      errorMarkers.Add(marker);
280      Doc.MarkerStrategy.AddMarker(marker);
281    }
282
283    private void AddErrorBookmark(CompilerError error) {
284      var bookmark = new ErrorBookmark(Doc, new TextLocation(error.Column, error.Line - 1));
285      errorBookmarks.Add(bookmark);
286      Doc.BookmarkManager.AddMark(bookmark);
287    }
288
289    private AbstractSegment GetSegmentAtOffset(int lineNr, int columnNr) {
290      lineNr = Math.Max(Doc.OffsetToPosition(prefix.Length).Line, lineNr);
291      lineNr = Math.Min(Doc.OffsetToPosition(Doc.TextLength - suffix.Length).Line, lineNr);
292      var line = Doc.GetLineSegment(lineNr - 1);
293      columnNr = Math.Max(0, columnNr);
294      columnNr = Math.Min(line.Length, columnNr);
295      var word = line.GetWord(columnNr);
296      AbstractSegment segment = new AbstractSegment();
297      if (word != null) {
298        segment.Offset = line.Offset + word.Offset;
299        segment.Length = word.Length;
300      } else {
301        segment.Offset = line.Offset + columnNr - 1;
302        segment.Length = 1;
303      }
304      return segment;
305    }
306
307    private HashSet<Assembly> assemblies = new HashSet<Assembly>();
308    public IEnumerable<Assembly> ReferencedAssemblies {
309      get { return assemblies; }
310    }
311    public void AddAssembly(Assembly a) {
312      ShowMessage("Loading " + a.GetName().Name + "...");
313      if (!assemblies.Contains(a)) {
314        var reference = projectContentRegistry.GetProjectContentForReference(a.GetName().Name, a.Location);
315        projectContent.AddReferencedContent(reference);
316        assemblies.Add(a);
317      }
318      ShowMessage("Ready");
319    }
320    public void RemoveAssembly(Assembly a) {
321      ShowMessage("Unloading " + a.GetName().Name + "...");
322      if (assemblies.Contains(a)) {
323        var content = projectContentRegistry.GetExistingProjectContent(a.Location);
324        if (content != null) {
325          projectContent.ReferencedContents.Remove(content);
326          projectContentRegistry.UnloadProjectContent(content);
327        }
328      }
329      ShowMessage("Ready");
330    }
331
332    private bool runParser = true;
333    private void ParserThread() {
334      BeginInvoke(new MethodInvoker(delegate { parserThreadLabel.Text = "Loading mscorlib..."; }));
335      projectContent.AddReferencedContent(projectContentRegistry.Mscorlib);
336      ParseStep();
337      BeginInvoke(new MethodInvoker(delegate { parserThreadLabel.Text = "Ready"; }));
338      while (runParser && !IsDisposed) {
339        ParseStep();
340        Thread.Sleep(2000);
341      }
342    }
343
344    private void ParseStep() {
345      try {
346        string code = null;
347        Invoke(new MethodInvoker(delegate { code = textEditor.Text; }));
348        TextReader textReader = new StringReader(code);
349        Dom.ICompilationUnit newCompilationUnit;
350        NRefactory.SupportedLanguage supportedLanguage;
351        supportedLanguage = NRefactory.SupportedLanguage.CSharp;
352        using (NRefactory.IParser p = NRefactory.ParserFactory.CreateParser(supportedLanguage, textReader)) {
353          p.ParseMethodBodies = false;
354          p.Parse();
355          newCompilationUnit = ConvertCompilationUnit(p.CompilationUnit);
356        }
357        projectContent.UpdateCompilationUnit(lastCompilationUnit, newCompilationUnit, DummyFileName);
358        lastCompilationUnit = newCompilationUnit;
359        parseInformation.SetCompilationUnit(newCompilationUnit);
360      } catch { }
361    }
362
363    Dom.ICompilationUnit ConvertCompilationUnit(NRefactory.Ast.CompilationUnit cu) {
364      Dom.NRefactoryResolver.NRefactoryASTConvertVisitor converter;
365      converter = new Dom.NRefactoryResolver.NRefactoryASTConvertVisitor(projectContent);
366      cu.AcceptVisitor(converter, null);
367      return converter.Cu;
368    }
369
370    private void ShowMessage(string m) {
371      if (this.Handle == null)
372        return;
373      BeginInvoke(new Action(() => parserThreadLabel.Text = m));
374    }
375
376    private void toolStripStatusLabel1_Click(object sender, EventArgs e) {
377      var proc = new Process();
378      proc.StartInfo.FileName = sharpDevelopLabel.Tag.ToString();
379      proc.Start();
380    }
381
382    private void CodeEditor_Resize(object sender, EventArgs e) {
383      var textArea = textEditor.ActiveTextAreaControl.TextArea;
384      var vScrollBar = textEditor.ActiveTextAreaControl.VScrollBar;
385      var hScrollBar = textEditor.ActiveTextAreaControl.HScrollBar;
386
387      textArea.SuspendLayout();
388      textArea.Width = textEditor.Width - vScrollBar.Width;
389      textArea.Height = textEditor.Height - hScrollBar.Height;
390      textArea.ResumeLayout();
391
392      vScrollBar.SuspendLayout();
393      vScrollBar.Location = new Point(textArea.Width, 0);
394      vScrollBar.Height = textArea.Height;
395      vScrollBar.ResumeLayout();
396
397      hScrollBar.SuspendLayout();
398      hScrollBar.Location = new Point(0, textArea.Height);
399      hScrollBar.Width = textArea.Width;
400      hScrollBar.ResumeLayout();
401    }
402  }
403}
Note: See TracBrowser for help on using the repository browser.