Free cookie consent management tool by TermsFeed Policy Generator

source: branches/OaaS/HeuristicLab.CodeEditor/3.3/CodeEditor.cs @ 14630

Last change on this file since 14630 was 5287, checked in by abeham, 14 years ago

#1337

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