Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HLScript/HeuristicLab.CodeEditor/3.3/CodeEditor.cs @ 12675

Last change on this file since 12675 was 10358, checked in by jkarder, 11 years ago

#2136:

  • refactored HLScriptGeneration to separate outputs from different running HL scripts.
  • added persistence support for HLScripts and fixed cloning
  • added code completion for all types in the currently loaded assemblies
  • merged trunk changes
File size: 15.3 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    #endregion
136
137    public event EventHandler TextEditorValidated;
138
139    protected void OnTextEditorValidated() {
140      if (TextEditorValidated != null)
141        TextEditorValidated(this, EventArgs.Empty);
142    }
143
144    public event EventHandler TextEditorTextChanged;
145
146    protected void OnTextEditorTextChanged() {
147      if (TextEditorTextChanged != null)
148        TextEditorTextChanged(this, EventArgs.Empty);
149    }
150
151    public CodeEditor() {
152      InitializeComponent();
153
154      textEditor.ActiveTextAreaControl.TextEditorProperties.SupportReadOnlySegments = true;
155
156      textEditor.SetHighlighting("C#");
157      textEditor.ShowEOLMarkers = false;
158      textEditor.ShowInvalidLines = false;
159      HostCallbackImplementation.Register(this);
160      CodeCompletionKeyHandler.Attach(this, textEditor);
161      ToolTipProvider.Attach(this, textEditor);
162
163      projectContentRegistry = new Dom.ProjectContentRegistry(); // Default .NET 2.0 registry
164      try {
165        string persistencePath = Path.Combine(Path.GetTempPath(), "HeuristicLab.CodeEditor");
166        if (!Directory.Exists(persistencePath))
167          Directory.CreateDirectory(persistencePath);
168        FileStream fs = File.Create(Path.Combine(persistencePath, "test.tmp"));
169        fs.Close();
170        File.Delete(Path.Combine(persistencePath, "test.tmp"));
171        // if we made it this far, enable on-disk parsing cache
172        projectContentRegistry.ActivatePersistence(persistencePath);
173      } catch (NotSupportedException) {
174      } catch (IOException) {
175      } catch (System.Security.SecurityException) {
176      } catch (UnauthorizedAccessException) {
177      } catch (ArgumentException) {
178      }
179      projectContent = new Dom.DefaultProjectContent();
180      projectContent.Language = Dom.LanguageProperties.CSharp;
181    }
182
183    protected override void OnLoad(EventArgs e) {
184      base.OnLoad(e);
185
186      if (DesignMode)
187        return;
188
189      textEditor.ActiveTextAreaControl.TextArea.KeyEventHandler += new ICSharpCode.TextEditor.KeyEventHandler(TextArea_KeyEventHandler);
190      textEditor.ActiveTextAreaControl.TextArea.DoProcessDialogKey += new DialogKeyProcessor(TextArea_DoProcessDialogKey);
191
192      parserThread = new Thread(ParserThread);
193      parserThread.IsBackground = true;
194      parserThread.Start();
195
196      textEditor.Validated += (s, a) => { OnTextEditorValidated(); };
197      textEditor.TextChanged += (s, a) => { OnTextEditorTextChanged(); };
198      InitializeImageList();
199    }
200
201    private void InitializeImageList() {
202      imageList1.Images.Clear();
203      imageList1.Images.Add("Icons.16x16.Class.png", VSImageLibrary.Class);
204      imageList1.Images.Add("Icons.16x16.Method.png", VSImageLibrary.Method);
205      imageList1.Images.Add("Icons.16x16.Property.png", VSImageLibrary.Properties);
206      imageList1.Images.Add("Icons.16x16.Field.png", VSImageLibrary.Field);
207      imageList1.Images.Add("Icons.16x16.Enum.png", VSImageLibrary.Enum);
208      imageList1.Images.Add("Icons.16x16.NameSpace.png", VSImageLibrary.Namespace);
209      imageList1.Images.Add("Icons.16x16.Event.png", VSImageLibrary.Event);
210    }
211
212    #region keyboard handlers: filter input in read-only areas
213
214    bool TextArea_KeyEventHandler(char ch) {
215      int caret = textEditor.ActiveTextAreaControl.Caret.Offset;
216      return caret < prefix.Length || caret > Doc.TextLength - suffix.Length;
217    }
218
219    bool TextArea_DoProcessDialogKey(Keys keyData) {
220      if (keyData == Keys.Return) {
221        int caret = textEditor.ActiveTextAreaControl.Caret.Offset;
222        if (caret < prefix.Length ||
223            caret > Doc.TextLength - suffix.Length) {
224          return true;
225        }
226      }
227      return false;
228    }
229
230    #endregion
231
232    public void ScrollAfterPrefix() {
233      int lineNr = prefix != null ? Doc.OffsetToPosition(prefix.Length).Line : 0;
234      textEditor.ActiveTextAreaControl.JumpTo(lineNr + 1);
235    }
236
237    private List<TextMarker> errorMarkers = new List<TextMarker>();
238    private List<Bookmark> errorBookmarks = new List<Bookmark>();
239    public void ShowCompileErrors(CompilerErrorCollection compilerErrors, string filename) {
240      Doc.MarkerStrategy.RemoveAll(m => errorMarkers.Contains(m));
241      Doc.BookmarkManager.RemoveMarks(m => errorBookmarks.Contains(m));
242      errorMarkers.Clear();
243      errorBookmarks.Clear();
244      errorLabel.Text = "";
245      errorLabel.ToolTipText = null;
246      if (compilerErrors == null)
247        return;
248      foreach (CompilerError error in compilerErrors) {
249        if (!error.FileName.EndsWith(filename)) {
250          errorLabel.Text = "Error in generated code";
251          errorLabel.ToolTipText = string.Format("{0}{1}:{2} -> {3}",
252            errorLabel.ToolTipText != null ? (errorLabel.ToolTipText + "\n\n") : "",
253            error.Line, error.Column,
254            error.ErrorText);
255          continue;
256        }
257        var startPosition = Doc.OffsetToPosition(prefix.Length);
258        if (error.Line == 1)
259          error.Column += startPosition.Column;
260        error.Line += startPosition.Line;
261        AddErrorMarker(error);
262        AddErrorBookmark(error);
263      }
264      Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
265      Doc.CommitUpdate();
266    }
267
268    private void AddErrorMarker(CompilerError error) {
269      var segment = GetSegmentAtOffset(error.Line, error.Column);
270      Color color = error.IsWarning ? Color.Blue : Color.Red;
271      var marker = new TextMarker(segment.Offset, segment.Length, TextMarkerType.WaveLine, color) {
272        ToolTip = error.ErrorText,
273      };
274      errorMarkers.Add(marker);
275      Doc.MarkerStrategy.AddMarker(marker);
276    }
277
278    private void AddErrorBookmark(CompilerError error) {
279      var bookmark = new ErrorBookmark(Doc, new TextLocation(error.Column, error.Line - 1));
280      errorBookmarks.Add(bookmark);
281      Doc.BookmarkManager.AddMark(bookmark);
282    }
283
284    private AbstractSegment GetSegmentAtOffset(int lineNr, int columnNr) {
285      lineNr = Math.Max(Doc.OffsetToPosition(prefix.Length).Line, lineNr);
286      lineNr = Math.Min(Doc.OffsetToPosition(Doc.TextLength - suffix.Length).Line, lineNr);
287      var line = Doc.GetLineSegment(lineNr - 1);
288      columnNr = Math.Max(0, columnNr);
289      columnNr = Math.Min(line.Length, columnNr);
290      var word = line.GetWord(columnNr);
291      AbstractSegment segment = new AbstractSegment();
292      if (word != null) {
293        segment.Offset = line.Offset + word.Offset;
294        segment.Length = word.Length;
295      } else {
296        segment.Offset = line.Offset + columnNr - 1;
297        segment.Length = 1;
298      }
299      return segment;
300    }
301
302    private HashSet<Assembly> assemblies = new HashSet<Assembly>();
303    public IEnumerable<Assembly> ReferencedAssemblies {
304      get { return assemblies; }
305    }
306    public void AddAssembly(Assembly a) {
307      ShowMessage("Loading " + a.GetName().Name + "...");
308      if (!assemblies.Contains(a)) {
309        var reference = projectContentRegistry.GetProjectContentForReference(a.GetName().Name, a.Location);
310        projectContent.AddReferencedContent(reference);
311        assemblies.Add(a);
312      }
313      ShowMessage("Ready");
314    }
315    public void RemoveAssembly(Assembly a) {
316      ShowMessage("Unloading " + a.GetName().Name + "...");
317      if (assemblies.Contains(a)) {
318        var content = projectContentRegistry.GetExistingProjectContent(a.Location);
319        if (content != null) {
320          projectContent.ReferencedContents.Remove(content);
321          projectContentRegistry.UnloadProjectContent(content);
322        }
323      }
324      ShowMessage("Ready");
325    }
326
327    private bool runParser = true;
328    private void ParserThread() {
329      BeginInvoke(new MethodInvoker(delegate { parserThreadLabel.Text = "Loading mscorlib..."; }));
330      projectContent.AddReferencedContent(projectContentRegistry.Mscorlib);
331      ParseStep();
332      BeginInvoke(new MethodInvoker(delegate { parserThreadLabel.Text = "Ready"; }));
333      while (runParser && !IsDisposed) {
334        ParseStep();
335        Thread.Sleep(2000);
336      }
337    }
338
339    private void ParseStep() {
340      try {
341        string code = null;
342        Invoke(new MethodInvoker(delegate { code = textEditor.Text; }));
343        TextReader textReader = new StringReader(code);
344        Dom.ICompilationUnit newCompilationUnit;
345        NRefactory.SupportedLanguage supportedLanguage;
346        supportedLanguage = NRefactory.SupportedLanguage.CSharp;
347        using (NRefactory.IParser p = NRefactory.ParserFactory.CreateParser(supportedLanguage, textReader)) {
348          p.ParseMethodBodies = false;
349          p.Parse();
350          newCompilationUnit = ConvertCompilationUnit(p.CompilationUnit);
351        }
352        projectContent.UpdateCompilationUnit(lastCompilationUnit, newCompilationUnit, DummyFileName);
353        lastCompilationUnit = newCompilationUnit;
354        parseInformation.SetCompilationUnit(newCompilationUnit);
355      } catch { }
356    }
357
358    Dom.ICompilationUnit ConvertCompilationUnit(NRefactory.Ast.CompilationUnit cu) {
359      Dom.NRefactoryResolver.NRefactoryASTConvertVisitor converter;
360      converter = new Dom.NRefactoryResolver.NRefactoryASTConvertVisitor(projectContent);
361      cu.AcceptVisitor(converter, null);
362      return converter.Cu;
363    }
364
365    private void ShowMessage(string m) {
366      if (this.Handle == null)
367        return;
368      BeginInvoke(new Action(() => parserThreadLabel.Text = m));
369    }
370
371    private void toolStripStatusLabel1_Click(object sender, EventArgs e) {
372      var proc = new Process();
373      proc.StartInfo.FileName = sharpDevelopLabel.Tag.ToString();
374      proc.Start();
375    }
376
377    private void CodeEditor_Resize(object sender, EventArgs e) {
378      var textArea = textEditor.ActiveTextAreaControl.TextArea;
379      var vScrollBar = textEditor.ActiveTextAreaControl.VScrollBar;
380      var hScrollBar = textEditor.ActiveTextAreaControl.HScrollBar;
381
382      textArea.SuspendLayout();
383      textArea.Width = textEditor.Width - vScrollBar.Width;
384      textArea.Height = textEditor.Height - hScrollBar.Height;
385      textArea.ResumeLayout();
386
387      vScrollBar.SuspendLayout();
388      vScrollBar.Location = new Point(textArea.Width, 0);
389      vScrollBar.Height = textArea.Height;
390      vScrollBar.ResumeLayout();
391
392      hScrollBar.SuspendLayout();
393      hScrollBar.Location = new Point(0, textArea.Height);
394      hScrollBar.Width = textArea.Width;
395      hScrollBar.ResumeLayout();
396    }
397  }
398}
Note: See TracBrowser for help on using the repository browser.