Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.CodeEditor/3.2/CodeEditor.cs @ 2667

Last change on this file since 2667 was 2667, checked in by epitzer, 14 years ago

Ensure proper resizing of CodeEditor and don't crash when removing non-existent assemblies (#842)

File size: 14.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.Linq;
30using System.Collections.Generic;
31using System.Drawing;
32using System.Windows.Forms;
33using System.IO;
34using System.Threading;
35using HeuristicLab.Common.Resources;
36
37using NRefactory = ICSharpCode.NRefactory;
38using Dom = ICSharpCode.SharpDevelop.Dom;
39using ICSharpCode.TextEditor.Document;
40using System.CodeDom.Compiler;
41using ICSharpCode.TextEditor;
42using System.Reflection;
43using System.Diagnostics;
44
45namespace HeuristicLab.CodeEditor {
46
47  public partial class CodeEditor : UserControl {
48
49    #region Fields & Properties
50
51    internal Dom.ProjectContentRegistry projectContentRegistry;
52    internal Dom.DefaultProjectContent projectContent;
53    internal Dom.ParseInformation parseInformation = new Dom.ParseInformation();
54    Dom.ICompilationUnit lastCompilationUnit;
55    Thread parserThread;
56
57    /// <summary>
58    /// Many SharpDevelop.Dom methods take a file name, which is really just a unique identifier
59    /// for a file - Dom methods don't try to access code files on disk, so the file does not have
60    /// to exist.
61    /// SharpDevelop itself uses internal names of the kind "[randomId]/Class1.cs" to support
62    /// code-completion in unsaved files.
63    /// </summary>
64    public const string DummyFileName = "edited.cs";
65
66    private IDocument Doc {
67      get {
68        return textEditor.Document;
69      }
70    }
71
72    private string prefix = "";
73    private TextMarker prefixMarker =
74      new TextMarker(0, 1, TextMarkerType.SolidBlock, Color.LightGray) {
75        IsReadOnly = true,
76      };
77    public string Prefix {
78      get {
79        return prefix;
80      }
81      set {
82        if (value == null) value = "";
83        if (prefix == value) return;
84        Doc.MarkerStrategy.RemoveMarker(prefixMarker);
85        Doc.Remove(0, prefix.Length);
86        prefix = value;
87        if (value.Length > 0) {
88          Doc.Insert(0, value);
89          prefixMarker.Offset = 0;
90          prefixMarker.Length = prefix.Length;
91          Doc.MarkerStrategy.AddMarker(prefixMarker);
92        }
93        Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
94        Doc.CommitUpdate();
95      }
96    }
97
98    private string suffix = "";
99    private TextMarker suffixMarker =
100      new TextMarker(0, 1, TextMarkerType.SolidBlock, Color.LightGray) {
101        IsReadOnly = true,
102      };
103    public string Suffix {
104      get {
105        return suffix;
106      }
107      set {
108        if (value == null) value = "";
109        if (suffix == value) return;
110        Doc.MarkerStrategy.RemoveMarker(suffixMarker);
111        Doc.Remove(Doc.TextLength - suffix.Length, suffix.Length);
112        suffix = value;
113        if (value.Length > 0) {
114          suffixMarker.Offset = Doc.TextLength;
115          Doc.Insert(Doc.TextLength, value);
116          suffixMarker.Length = suffix.Length;
117          Doc.MarkerStrategy.AddMarker(suffixMarker);
118        }
119        Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
120        Doc.CommitUpdate();
121      }
122    }
123
124    public string UserCode {
125      get {
126        return Doc.GetText(
127          prefix.Length,
128          Doc.TextLength - suffix.Length - prefix.Length);
129      }
130      set {
131        Doc.Replace(prefix.Length, Doc.TextLength - suffix.Length - prefix.Length, value);
132        Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
133        Doc.CommitUpdate();
134      }
135    }
136
137    #endregion
138
139    public event EventHandler TextEditorValidated;
140
141    protected void OnTextEditorValidated() {
142      if (TextEditorValidated != null)
143        TextEditorValidated(this, EventArgs.Empty);
144    }
145
146    public CodeEditor() {
147      InitializeComponent();
148
149      textEditor.ActiveTextAreaControl.TextEditorProperties.SupportReadOnlySegments = true;
150
151      textEditor.SetHighlighting("C#");
152      textEditor.ShowEOLMarkers = false;
153      textEditor.ShowInvalidLines = false;
154      HostCallbackImplementation.Register(this);
155      CodeCompletionKeyHandler.Attach(this, textEditor);
156      ToolTipProvider.Attach(this, textEditor);
157
158      projectContentRegistry = new Dom.ProjectContentRegistry(); // Default .NET 2.0 registry
159      projectContentRegistry.ActivatePersistence(Path.Combine(Path.GetTempPath(),
160                                                  "CSharpCodeCompletion"));
161      projectContent = new Dom.DefaultProjectContent();
162      projectContent.Language = Dom.LanguageProperties.CSharp;
163    }
164
165    protected override void OnLoad(EventArgs e) {
166      base.OnLoad(e);
167
168      if (DesignMode)
169        return;
170
171      textEditor.ActiveTextAreaControl.TextArea.KeyDown += new System.Windows.Forms.KeyEventHandler(TextArea_KeyDown);
172      textEditor.ActiveTextAreaControl.TextArea.DoProcessDialogKey += new DialogKeyProcessor(TextArea_DoProcessDialogKey);
173
174      parserThread = new Thread(ParserThread);
175      parserThread.IsBackground = true;
176      parserThread.Start();
177
178      textEditor.Validated += (s, a) => { OnTextEditorValidated(); };
179      InitializeImageList();
180    }
181
182    private void InitializeImageList() {
183      imageList1.Images.Clear();
184      imageList1.Images.Add("Icons.16x16.Class.png", VS2008ImageLibrary.Class);
185      imageList1.Images.Add("Icons.16x16.Method.png", VS2008ImageLibrary.Method);
186      imageList1.Images.Add("Icons.16x16.Property.png", VS2008ImageLibrary.Properties);
187      imageList1.Images.Add("Icons.16x16.Field.png", VS2008ImageLibrary.Field);
188      imageList1.Images.Add("Icons.16x16.Enum.png", VS2008ImageLibrary.Enum);
189      imageList1.Images.Add("Icons.16x16.NameSpace.png", VS2008ImageLibrary.Namespace);
190      imageList1.Images.Add("Icons.16x16.Event.png", VS2008ImageLibrary.Event);
191    }
192
193    void TextArea_KeyDown(object sender, KeyEventArgs e) {
194      int caretOffset = textEditor.ActiveTextAreaControl.Caret.Offset;
195      if (caretOffset == 0 || caretOffset == Doc.TextLength)
196        e.Handled = true;
197    }
198
199    bool TextArea_DoProcessDialogKey(Keys keyData) {
200      if (keyData == Keys.Return) {
201        int caret = textEditor.ActiveTextAreaControl.Caret.Offset;
202        if (caret < prefix.Length ||
203            caret > Doc.TextLength - suffix.Length) {
204          return true;
205        }
206      }
207      return false;
208    }
209
210    public void ScrollAfterPrefix() {
211      int lineNr = prefix != null ? Doc.OffsetToPosition(prefix.Length).Line : 0;
212      textEditor.ActiveTextAreaControl.JumpTo(lineNr + 1);
213    }
214
215    private List<TextMarker> errorMarkers = new List<TextMarker>();
216    private List<Bookmark> errorBookmarks = new List<Bookmark>();
217    public void ShowCompileErrors(CompilerErrorCollection compilerErrors, string filename) {
218      Doc.MarkerStrategy.RemoveAll(m => errorMarkers.Contains(m));
219      Doc.BookmarkManager.RemoveMarks(m => errorBookmarks.Contains(m));
220      errorMarkers.Clear();
221      errorBookmarks.Clear();
222      errorLabel.Text = "";
223      errorLabel.ToolTipText = null;
224      if (compilerErrors == null)
225        return;
226      foreach (CompilerError error in compilerErrors) {
227        if (!error.FileName.EndsWith(filename)) {
228          errorLabel.Text = "error in generated code";
229          errorLabel.ToolTipText = string.Format("{0}{1}:{2} -> {3}",
230            errorLabel.ToolTipText != null ? (errorLabel.ToolTipText + "\n\n") : "",
231            error.Line, error.Column,
232            error.ErrorText);
233          continue;
234        }
235        var startPosition = Doc.OffsetToPosition(prefix.Length);
236        if (error.Line == 1)
237          error.Column += startPosition.Column;
238        error.Line += startPosition.Line;
239        AddErrorMarker(error);
240        AddErrorBookmark(error);
241      }
242      Doc.RequestUpdate(new TextAreaUpdate(TextAreaUpdateType.WholeTextArea));
243      Doc.CommitUpdate();
244    }
245
246    private void AddErrorMarker(CompilerError error) {
247      var segment = GetSegmentAtOffset(error.Line, error.Column);
248      Color color = error.IsWarning ? Color.Blue : Color.Red;
249      var marker = new TextMarker(segment.Offset, segment.Length, TextMarkerType.WaveLine, color) {
250        ToolTip = error.ErrorText,
251      };
252      errorMarkers.Add(marker);
253      Doc.MarkerStrategy.AddMarker(marker);
254    }
255
256    private void AddErrorBookmark(CompilerError error) {
257      var bookmark = new ErrorBookmark(Doc, new TextLocation(error.Column, error.Line - 1));
258      errorBookmarks.Add(bookmark);
259      Doc.BookmarkManager.AddMark(bookmark);
260    }
261
262    private AbstractSegment GetSegmentAtOffset(int lineNr, int columnNr) {
263      lineNr = Math.Max(Doc.OffsetToPosition(prefix.Length).Line, lineNr);
264      lineNr = Math.Min(Doc.OffsetToPosition(Doc.TextLength - suffix.Length).Line, lineNr);
265      var line = Doc.GetLineSegment(lineNr - 1);
266      columnNr = Math.Max(0, columnNr);
267      columnNr = Math.Min(line.Length, columnNr);
268      var word = line.GetWord(columnNr);
269      AbstractSegment segment = new AbstractSegment();
270      if (word != null) {
271        segment.Offset = line.Offset + word.Offset;
272        segment.Length = word.Length;
273      } else {
274        segment.Offset = line.Offset + columnNr - 1;
275        segment.Length = 1;
276      }
277      return segment;
278    }
279
280    private HashSet<Assembly> assemblies = new HashSet<Assembly>();
281    public IEnumerable<Assembly> ReferencedAssemblies {
282      get { return assemblies; }
283    }
284    public void AddAssembly(Assembly a) {
285      ShowMessage("Loading " + a.GetName().Name + "...");
286      if (assemblies.Contains(a))
287        return;
288      var reference = projectContentRegistry.GetProjectContentForReference(a.GetName().Name, a.Location);
289      projectContent.AddReferencedContent(reference);
290      assemblies.Add(a);
291      ShowMessage("Ready");
292    }
293    public void RemoveAssembly(Assembly a) {
294      ShowMessage("Unloading " + a.GetName().Name + "...");
295      if (!assemblies.Contains(a))
296        return;
297      var content = projectContentRegistry.GetExistingProjectContent(a.Location);
298      if (content != null) {
299        projectContent.ReferencedContents.Remove(content);
300        projectContentRegistry.UnloadProjectContent(content);
301      }
302      ShowMessage("Ready");
303    }
304
305    private void ParserThread() {
306      BeginInvoke(new MethodInvoker(delegate { parserThreadLabel.Text = "Loading mscorlib..."; }));
307      projectContent.AddReferencedContent(projectContentRegistry.Mscorlib);
308      ParseStep();
309      BeginInvoke(new MethodInvoker(delegate { parserThreadLabel.Text = "Ready"; }));
310      try {
311        while (!IsDisposed) {
312          ParseStep();
313          Thread.Sleep(2000);
314        }
315      } catch { }
316    }
317
318    private void ParseStep() {
319      string code = null;
320      Invoke(new MethodInvoker(delegate {
321        code = textEditor.Text;
322      }));
323      TextReader textReader = new StringReader(code);
324      Dom.ICompilationUnit newCompilationUnit;
325      NRefactory.SupportedLanguage supportedLanguage;
326      supportedLanguage = NRefactory.SupportedLanguage.CSharp;
327      using (NRefactory.IParser p = NRefactory.ParserFactory.CreateParser(supportedLanguage, textReader)) {
328        p.ParseMethodBodies = false;
329        p.Parse();
330        newCompilationUnit = ConvertCompilationUnit(p.CompilationUnit);
331      }
332      projectContent.UpdateCompilationUnit(lastCompilationUnit, newCompilationUnit, DummyFileName);
333      lastCompilationUnit = newCompilationUnit;
334      parseInformation.SetCompilationUnit(newCompilationUnit);
335    }
336
337    Dom.ICompilationUnit ConvertCompilationUnit(NRefactory.Ast.CompilationUnit cu) {
338      Dom.NRefactoryResolver.NRefactoryASTConvertVisitor converter;
339      converter = new Dom.NRefactoryResolver.NRefactoryASTConvertVisitor(projectContent);
340      cu.AcceptVisitor(converter, null);
341      return converter.Cu;
342    }
343
344    private void ShowMessage(string m) {
345      if (this.Handle == null)
346        return;
347      BeginInvoke(new Action(() => parserThreadLabel.Text = m));
348    }
349
350    private void toolStripStatusLabel1_Click(object sender, EventArgs e) {
351      var proc = new Process();
352      proc.StartInfo.FileName = sharpDevelopLabel.Tag.ToString();
353      proc.Start();
354    }
355
356    private void CodeEditor_Resize(object sender, EventArgs e) {
357      var textArea = textEditor.ActiveTextAreaControl.TextArea;
358      var vScrollBar = textEditor.ActiveTextAreaControl.VScrollBar;
359      var hScrollBar = textEditor.ActiveTextAreaControl.HScrollBar;
360
361      textArea.SuspendLayout();
362      textArea.Width = textEditor.Width - vScrollBar.Width;
363      textArea.Height = textEditor.Height - hScrollBar.Height;
364      textArea.ResumeLayout();
365
366      vScrollBar.SuspendLayout();
367      vScrollBar.Location = new Point(textArea.Width, 0);
368      vScrollBar.Height = textArea.Height;
369      vScrollBar.ResumeLayout();
370
371      hScrollBar.SuspendLayout();
372      hScrollBar.Location = new Point(0, textArea.Height);
373      hScrollBar.Width = textArea.Width;
374      hScrollBar.ResumeLayout();
375    }
376  }
377}
Note: See TracBrowser for help on using the repository browser.