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