diff options
Diffstat (limited to 'main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor')
42 files changed, 2937 insertions, 2730 deletions
diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs index 245f4d7a50..2eb68774ed 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AbstractUsagesExtension.cs @@ -251,7 +251,7 @@ namespace MonoDevelop.SourceEditor OnUsagesUpdated (EventArgs.Empty); } - public class UsageMarker : TextLineMarker + class UsageMarker : TextLineMarker { List<UsageSegment> usages = new List<UsageSegment> (); @@ -324,7 +324,7 @@ namespace MonoDevelop.SourceEditor } } - public class UsageSegment + class UsageSegment { public readonly ReferenceUsageType UsageType; public readonly TextSegment TextSegment; diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AutoSave.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AutoSave.cs deleted file mode 100644 index c96c5161bb..0000000000 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/AutoSave.cs +++ /dev/null @@ -1,220 +0,0 @@ -// -// AutoSave.cs -// -// Author: -// Mike Krüger <mkrueger@novell.com> -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using MonoDevelop.Core; -using Gtk; - -namespace MonoDevelop.SourceEditor -{ - static class AutoSave - { - //FIXME: is this path a good one? wouldn't it be better to put autosaves beside the files anyway? - static string autoSavePath = UserProfile.Current.CacheDir.Combine ("AutoSave"); - static bool autoSaveEnabled; - - static AutoSave () - { - try { - if (!Directory.Exists (autoSavePath)) - Directory.CreateDirectory (autoSavePath); - } catch (Exception e) { - LoggingService.LogError ("Can't create auto save path:" + autoSavePath +". Auto save is disabled.", e); - autoSaveEnabled = false; - return; - } - autoSaveEnabled = true; - StartAutoSaveThread (); - } - - static string GetAutoSaveFileName (string fileName) - { - if (fileName == null) - return null; - string newFileName = Path.Combine (Path.GetDirectoryName (fileName), Path.GetFileNameWithoutExtension (fileName) + Path.GetExtension (fileName) + "~"); - newFileName = Path.Combine (autoSavePath, newFileName.Replace(',','_').Replace(" ","").Replace (":","").Replace (Path.DirectorySeparatorChar, '_').Replace (Path.AltDirectorySeparatorChar, '_')); - return newFileName; - } - - public static bool AutoSaveExists (string fileName) - { - if (!autoSaveEnabled) - return false; - try { - var autoSaveFilename = GetAutoSaveFileName (fileName); - bool autoSaveExists = File.Exists (autoSaveFilename); - if (autoSaveExists) { - if (File.GetLastWriteTimeUtc (autoSaveFilename) < File.GetLastWriteTimeUtc (fileName)) { - File.Delete (autoSaveFilename); - return false; - } - } - return autoSaveExists; - } catch (Exception e) { - LoggingService.LogError ("Error in auto save - disableing.", e); - DisableAutoSave (); - return false; - } - } - - static void CreateAutoSave (string fileName, string content) - { - if (!autoSaveEnabled) - return; - try { - // Directory may have removed/unmounted. Therefore this operation is not guaranteed to work. - string tmpFile = Path.GetTempFileName (); - File.WriteAllText (tmpFile, content); - - var autosaveFileName = GetAutoSaveFileName (fileName); - if (File.Exists (autosaveFileName)) - File.Delete (autosaveFileName); - File.Move (tmpFile, autosaveFileName); - Counters.AutoSavedFiles++; - } catch (Exception e) { - LoggingService.LogError ("Error in auto save while creating: " + fileName +". Disableing auto save.", e); - DisableAutoSave (); - } - } - -#region AutoSave - class FileContent - { - public string FileName; - public Mono.TextEditor.TextDocument Content; - - public FileContent (string fileName, Mono.TextEditor.TextDocument content) - { - this.FileName = fileName; - this.Content = content; - } - } - - public static bool Running { - get { - return autoSaveThreadRunning; - } - } - - static readonly AutoResetEvent resetEvent = new AutoResetEvent (false); - static readonly AutoResetEvent saveEvent = new AutoResetEvent (false); - static bool autoSaveThreadRunning = false; - static Thread autoSaveThread; - static Queue<FileContent> queue = new Queue<FileContent> (); - static object contentLock = new object (); - - static void StartAutoSaveThread () - { - autoSaveThreadRunning = true; - if (autoSaveThread == null) { - autoSaveThread = new Thread (AutoSaveThread); - autoSaveThread.Name = "Autosave"; - autoSaveThread.IsBackground = true; - autoSaveThread.Start (); - } - } - - static void AutoSaveThread () - { - while (autoSaveThreadRunning) { - resetEvent.WaitOne (); - while (queue.Count > 0) { - var content = queue.Dequeue (); - // Don't create an auto save for unsaved files. - if (string.IsNullOrEmpty (content.FileName)) - continue; - string text = null; - bool set = false; - Application.Invoke (delegate { - try { - text = content.Content.Text; - set = true; - } catch (Exception e) { - LoggingService.LogError ("Exception in auto save thread.", e); - return; - } finally { - saveEvent.Set(); - } - } - ); - saveEvent.WaitOne (); - if (set) - CreateAutoSave (content.FileName, text); - } - } - } - - public static string LoadAutoSave (string fileName) - { - string autoSaveFileName = GetAutoSaveFileName (fileName); - return Mono.TextEditor.Utils.TextFileUtility.ReadAllText (autoSaveFileName); - } - - public static void RemoveAutoSaveFile (string fileName) - { - if (!autoSaveEnabled) - return; - if (AutoSaveExists (fileName)) { - string autoSaveFileName = GetAutoSaveFileName (fileName); - try { - lock (contentLock) { - File.Delete (autoSaveFileName); - } - } catch (Exception e) { - LoggingService.LogError ("Can't delete auto save file: " + autoSaveFileName +". Disableing auto save.", e); - DisableAutoSave (); - } - } - } - - public static void InformAutoSaveThread (Mono.TextEditor.TextDocument content) - { - if (content == null || !autoSaveEnabled) - return; - if (content.IsDirty) { - queue.Enqueue (new FileContent (content.FileName, content)); - resetEvent.Set (); - } else { - RemoveAutoSaveFile (content.FileName); - } - } - - public static void DisableAutoSave () - { - autoSaveThreadRunning = false; - if (autoSaveThread != null) { - resetEvent.Set (); - autoSaveThread.Join (); - autoSaveThread = null; - } - autoSaveEnabled = false; - } -#endregion - } -} diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/CompileErrorTooltipProvider.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/CompileErrorTooltipProvider.cs index 45dc49b306..9e90b4c685 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/CompileErrorTooltipProvider.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/CompileErrorTooltipProvider.cs @@ -26,24 +26,25 @@ // using System; -using Mono.TextEditor; +using MonoDevelop.Ide.Editor; +using MonoDevelop.Components; namespace MonoDevelop.SourceEditor { - - - public class CompileErrorTooltipProvider: TooltipProvider + class CompileErrorTooltipProvider: TooltipProvider { - - public CompileErrorTooltipProvider() + internal static ExtensibleTextEditor GetExtensibleTextEditor (TextEditor editor) { + var view = editor.GetContent<SourceEditorView> (); + if (view == null) + return null; + return view.TextEditor; } #region ITooltipProvider implementation - - public override TooltipItem GetItem (Mono.TextEditor.TextEditor editor, int offset) + public override TooltipItem GetItem (TextEditor editor, DocumentContext ctx, int offset) { - var ed = editor as ExtensibleTextEditor; + var ed = GetExtensibleTextEditor (editor); if (ed == null) return null; @@ -51,25 +52,23 @@ namespace MonoDevelop.SourceEditor if (string.IsNullOrEmpty (errorInformation)) return null; - return new TooltipItem (errorInformation, editor.Document.GetLineByOffset (offset)); + return new TooltipItem (errorInformation, editor.GetLineByOffset (offset)); } - - protected override Gtk.Window CreateTooltipWindow (Mono.TextEditor.TextEditor editor, int offset, Gdk.ModifierType modifierState, TooltipItem item) + + public override Control CreateTooltipWindow (TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Gdk.ModifierType modifierState) { - LanguageItemWindow result = new LanguageItemWindow ((ExtensibleTextEditor) editor, modifierState, null, (string)item.Item, null); + var result = new LanguageItemWindow (GetExtensibleTextEditor (editor), modifierState, null, (string)item.Item, null); if (result.IsEmpty) return null; return result; } - protected override void GetRequiredPosition (Mono.TextEditor.TextEditor editor, Gtk.Window tipWindow, out int requiredWidth, out double xalign) + public override void GetRequiredPosition (TextEditor editor, Control tipWindow, out int requiredWidth, out double xalign) { - LanguageItemWindow win = (LanguageItemWindow) tipWindow; + var win = (LanguageItemWindow) tipWindow; requiredWidth = win.SetMaxWidth (win.Screen.Width); xalign = 0.5; } - #endregion - } } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/Counters.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/Counters.cs index 5d26f8797e..e55ef141ff 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/Counters.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/Counters.cs @@ -34,6 +34,5 @@ namespace MonoDevelop.SourceEditor public static Counter EditorsInMemory = InstrumentationService.CreateCounter ("Editors in Memory", "Text Editor"); public static Counter SourceViewsInMemory = InstrumentationService.CreateCounter ("Source Views in Memory", "Text Editor"); public static Counter LoadedEditors = InstrumentationService.CreateCounter ("Loaded Editors", "Text Editor"); - public static Counter AutoSavedFiles = InstrumentationService.CreateCounter ("Autosaved Files", "Text Editor"); } } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueTooltipProvider.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueTooltipProvider.cs index 41fd96c87d..8f73a75308 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueTooltipProvider.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueTooltipProvider.cs @@ -29,17 +29,22 @@ using System; using System.Collections.Generic; -using Mono.TextEditor; using MonoDevelop.Ide; using MonoDevelop.Ide.Gui; using MonoDevelop.Debugger; using MonoDevelop.Components; using Mono.Debugging.Client; -using TextEditor = Mono.TextEditor.TextEditor; + +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.Semantics; +using ICSharpCode.NRefactory.CSharp; +using ICSharpCode.NRefactory.CSharp.TypeSystem; +using ICSharpCode.NRefactory.CSharp.Resolver; +using MonoDevelop.Ide.Editor; namespace MonoDevelop.SourceEditor { - public class DebugValueTooltipProvider: TooltipProvider, IDisposable + class DebugValueTooltipProvider: TooltipProvider, IDisposable { Dictionary<string,ObjectValue> cachedValues = new Dictionary<string,ObjectValue> (); DebugValueWindow tooltip; @@ -74,9 +79,10 @@ namespace MonoDevelop.SourceEditor #region ITooltipProvider implementation - public override TooltipItem GetItem (TextEditor editor, int offset) + + public override TooltipItem GetItem (TextEditor editor, DocumentContext ctx, int offset) { - if (offset >= editor.Document.TextLength) + if (offset >= editor.Length) return null; if (!DebuggingService.IsDebugging || DebuggingService.IsRunning) @@ -86,7 +92,9 @@ namespace MonoDevelop.SourceEditor if (frame == null) return null; - var ed = (ExtensibleTextEditor) editor; + var ed = CompileErrorTooltipProvider.GetExtensibleTextEditor (editor); + if (ed == null) + return null; string expression = null; int startOffset; @@ -94,20 +102,22 @@ namespace MonoDevelop.SourceEditor startOffset = ed.SelectionRange.Offset; expression = ed.SelectedText; } else { - var doc = IdeApp.Workbench.ActiveDocument; + var doc = ctx; if (doc == null || doc.ParsedDocument == null) return null; var resolver = doc.GetContent<IDebuggerExpressionResolver> (); - var data = editor.GetTextEditorData (); + var data = doc.GetContent<SourceEditorView> (); if (resolver != null) { - expression = resolver.ResolveExpression (data, doc, offset, out startOffset); + var result = resolver.ResolveExpressionAsync (editor, doc, offset, default(System.Threading.CancellationToken)).Result; + expression = result.Text; + startOffset = result.Span.Start; } else { - int endOffset = data.FindCurrentWordEnd (offset); - startOffset = data.FindCurrentWordStart (offset); + int endOffset = data.GetTextEditorData ().FindCurrentWordEnd (offset); + startOffset = data.GetTextEditorData ().FindCurrentWordStart (offset); - expression = data.GetTextAt (startOffset, endOffset - startOffset); + expression = editor.GetTextAt (startOffset, endOffset - startOffset); } } @@ -131,26 +141,29 @@ namespace MonoDevelop.SourceEditor return new TooltipItem (val, startOffset, expression.Length); } - - public override Gtk.Window ShowTooltipWindow (TextEditor editor, int offset, Gdk.ModifierType modifierState, int mouseX, int mouseY, TooltipItem item) + + public override Control CreateTooltipWindow (TextEditor editor, DocumentContext ctx, TooltipItem item, int offset, Gdk.ModifierType modifierState) { - var location = editor.OffsetToLocation (item.ItemSegment.Offset); + return new DebugValueWindow (editor, offset, DebuggingService.CurrentFrame, (ObjectValue) item.Item, null); + } + + public override void ShowTooltipWindow (TextEditor editor, Control tipWindow, TooltipItem item, Gdk.ModifierType modifierState, int mouseX, int mouseY) + { + var location = editor.OffsetToLocation (item.Offset); var point = editor.LocationToPoint (location); int lineHeight = (int) editor.LineHeight; - int y = point.Y; + int y = (int)point.Y; // find the top of the line that the mouse is hovering over while (y + lineHeight < mouseY) y += lineHeight; var caret = new Gdk.Rectangle (mouseX, y, 1, lineHeight); - tooltip = new DebugValueWindow (editor, offset, DebuggingService.CurrentFrame, (ObjectValue) item.Item, null); + tooltip = (DebugValueWindow)tipWindow; tooltip.ShowPopup (editor, caret, PopupPosition.TopLeft); - - return tooltip; } - public override bool IsInteractive (TextEditor editor, Gtk.Window tipWindow) + public override bool IsInteractive (TextEditor editor, Control tipWindow) { return DebuggingService.IsDebugging; } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueWindow.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueWindow.cs index 8af679e42c..9bb7863700 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueWindow.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DebugValueWindow.cs @@ -34,10 +34,11 @@ using Gtk; using Mono.TextEditor; using Gdk; using MonoDevelop.Ide; +using MonoDevelop.Ide.Editor; namespace MonoDevelop.SourceEditor { - public class BaseWindow : Gtk.Window + class BaseWindow : Gtk.Window { public BaseWindow () : base(Gtk.WindowType.Toplevel) { @@ -64,21 +65,21 @@ namespace MonoDevelop.SourceEditor } } - public class DebugValueWindow : PopoverWindow + class DebugValueWindow : PopoverWindow { ObjectValueTreeView tree; ScrolledWindow sw; // PinWindow pinWindow; // TreeIter currentPinIter; - public DebugValueWindow (Mono.TextEditor.TextEditor editor, int offset, StackFrame frame, ObjectValue value, PinnedWatch watch): base (Gtk.WindowType.Toplevel) + public DebugValueWindow (TextEditor editor, int offset, StackFrame frame, ObjectValue value, PinnedWatch watch): base (Gtk.WindowType.Toplevel) { this.TypeHint = WindowTypeHint.PopupMenu; this.AllowShrink = false; this.AllowGrow = false; this.Decorated = false; - TransientFor = (Gtk.Window) editor.Toplevel; + TransientFor = (Gtk.Window) ((Gtk.Widget)editor).Toplevel; // Avoid getting the focus when the window is shown. We'll get it when the mouse enters the window AcceptFocus = false; @@ -99,9 +100,9 @@ namespace MonoDevelop.SourceEditor tree.AllowPinning = true; tree.RootPinAlwaysVisible = true; tree.PinnedWatch = watch; - DocumentLocation location = editor.Document.OffsetToLocation (offset); + var location = editor.OffsetToLocation (offset); tree.PinnedWatchLine = location.Line; - tree.PinnedWatchFile = ((ExtensibleTextEditor)editor).View.ContentName; + tree.PinnedWatchFile = editor.FileName; tree.AddValue (value); tree.Selection.UnselectAll (); diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DynamicAbbrevHandler.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DynamicAbbrevHandler.cs deleted file mode 100644 index db50031bb3..0000000000 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/DynamicAbbrevHandler.cs +++ /dev/null @@ -1,195 +0,0 @@ -// -// DynamicAbbrevHandler.cs -// -// Author: -// Mike Krüger <mkrueger@novell.com> -// -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System.Linq; -using MonoDevelop.Components.Commands; -using MonoDevelop.Ide.Gui; -using System.Collections.Generic; -using MonoDevelop.Ide; - -namespace MonoDevelop.SourceEditor -{ - public class DynamicAbbrevHandler : CommandHandler - { - enum AbbrevState { - SearchBackward, - SearchForward, - SearchOtherBuffers, - CycleThroughFoundWords - } - - static SourceEditorView lastView = null; - static string lastAbbrev = null; - static int lastTriggerOffset = 0; - static int lastInsertPos = 0; - static List<string> foundWords = new List<string> (); - static int lastStartOffset = 0; - static AbbrevState curState; - - protected override void Run (object data) - { - MonoDevelop.Ide.Gui.Document doc = IdeApp.Workbench.ActiveDocument; - if (doc == null) - return; - SourceEditorView view = IdeApp.Workbench.ActiveDocument.GetContent<SourceEditorView> (); - if (view == null) - return; - - string abbrevWord; - int offset; - int startOffset; - - if (lastView == view && view.TextEditor.Caret.Offset == lastTriggerOffset) { - abbrevWord = lastAbbrev; - offset = lastStartOffset; - } else { - abbrevWord = GetWordBeforeCaret (view.TextEditor); - lastAbbrev = abbrevWord; - offset = view.TextEditor.Caret.Offset - abbrevWord.Length - 1; - lastInsertPos = lastTriggerOffset = offset + 1; - foundWords.Clear (); - foundWords.Add (abbrevWord); - curState = AbbrevState.SearchBackward; - } - - lastView = view; - switch (curState) { - case AbbrevState.SearchBackward: - while (offset > 0) { - if (IsMatchAt (view, offset, abbrevWord)) { - int endOffset = SearchEndPos (offset, view); - string curWord = view.TextEditor.Document.GetTextBetween (offset, endOffset); - if (foundWords.Contains (curWord)) { - offset--; - continue; - } - foundWords.Add (curWord); - ReplaceWord (view, curWord); - lastStartOffset = offset - 1; - return; - } - offset--; - } - offset = view.TextEditor.Caret.Offset; - curState = AbbrevState.SearchForward; - goto case AbbrevState.SearchForward; - case AbbrevState.SearchForward: - while (offset < view.TextEditor.Document.TextLength) { - if (IsMatchAt (view, offset, abbrevWord)) { - int endOffset = SearchEndPos (offset, view); - string curWord = view.TextEditor.Document.GetTextBetween (offset, endOffset); - if (foundWords.Contains (curWord)) { - offset++; - continue; - } - foundWords.Add (curWord); - ReplaceWord (view, curWord); - lastStartOffset = offset + 1; - return; - } - offset++; - } - curState = AbbrevState.SearchOtherBuffers; - goto case AbbrevState.SearchOtherBuffers; - case AbbrevState.SearchOtherBuffers: - foreach (Document curDoc in IdeApp.Workbench.Documents) { - SourceEditorView otherView = curDoc.GetContent<SourceEditorView> (); - if (curDoc == doc || otherView == null || otherView.Document == null) - continue; - for (int i = 0; i < otherView.Document.TextLength; i++) { - if (IsMatchAt (otherView, i, abbrevWord)) { - int endOffset = SearchEndPos (i, otherView); - string curWord = otherView.TextEditor.Document.GetTextBetween (i, endOffset); - if (foundWords.Contains (curWord)) - continue; - foundWords.Add (curWord); - } - } - } - curState = AbbrevState.CycleThroughFoundWords; - goto case AbbrevState.CycleThroughFoundWords; - case AbbrevState.CycleThroughFoundWords: - int index = foundWords.IndexOf (view.TextEditor.Document.GetTextAt (lastInsertPos, view.TextEditor.Caret.Offset - lastInsertPos)); - if (index < 0) - break; - startOffset = offset; - offset = startOffset + foundWords[index].Length; - index = (index + foundWords.Count + 1) % foundWords.Count; - ReplaceWord (view, foundWords[index]); - break; - } - } - - public static bool IsIdentifierPart (char ch) - { - return char.IsLetterOrDigit (ch) || ch == '_'; - } - - static string GetWordBeforeCaret (MonoDevelop.SourceEditor.ExtensibleTextEditor editor) - { - int startOffset = editor.Caret.Offset; - int offset = startOffset - 1; - while (offset > 0) { - char ch = editor.Document.GetCharAt (offset); - if (!IsIdentifierPart (ch)) { - offset++; - break; - } - offset--; - } - if (offset >= startOffset) - return ""; - return editor.Document.GetTextBetween (offset, startOffset); - } - - static void ReplaceWord (MonoDevelop.SourceEditor.SourceEditorView view, string curWord) - { - view.TextEditor.Replace (lastInsertPos, view.TextEditor.Caret.Offset - lastInsertPos, curWord); - view.TextEditor.Document.CommitLineUpdate (view.TextEditor.Caret.Line); - lastTriggerOffset = view.TextEditor.Caret.Offset; - } - - static int SearchEndPos (int offset, MonoDevelop.SourceEditor.SourceEditorView view) - { - while (offset < view.TextEditor.Document.TextLength && IsIdentifierPart (view.TextEditor.Document.GetCharAt (offset))) { - offset++; - } - return offset; - } - - static bool IsMatchAt (MonoDevelop.SourceEditor.SourceEditorView view, int offset, string abbrevWord) - { - if (offset + abbrevWord.Length >= view.TextEditor.Document.TextLength) - return false; - if (offset > 0 && IsIdentifierPart (view.TextEditor.Document.GetCharAt (offset - 1))) - return false; - if (offset + abbrevWord.Length < view.TextEditor.Document.TextLength && !IsIdentifierPart (view.TextEditor.Document.GetCharAt (offset + abbrevWord.Length))) - return false; - return view.TextEditor.Document.GetTextAt (offset, abbrevWord.Length) == abbrevWord; - } - } -} -
\ No newline at end of file diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/EditActions.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/EditActions.cs index f126440083..bda75e6a0a 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/EditActions.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/EditActions.cs @@ -29,7 +29,7 @@ using System.Linq; namespace MonoDevelop.SourceEditor { - public class TabAction + class TabAction { ExtensibleTextEditor editor; @@ -72,7 +72,7 @@ namespace MonoDevelop.SourceEditor static void RemoveCharBeforCaret (TextEditorData data) { - if (!data.IsSomethingSelected && ((ISourceEditorOptions)data.Options).AutoInsertMatchingBracket) { + if (!data.IsSomethingSelected && MonoDevelop.Ide.Editor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket) { if (data.Caret.Offset > 0) { var line = data.GetLine (data.Caret.Line); var stack = line.StartSpan.Clone(); diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/EditorFactory.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/EditorFactory.cs new file mode 100644 index 0000000000..eba8185a7d --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/EditorFactory.cs @@ -0,0 +1,87 @@ +// +// EditorFactory.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using MonoDevelop.Ide.Editor; +using MonoDevelop.SourceEditor.Wrappers; +using Mono.TextEditor; +using Mono.TextEditor.Highlighting; + +namespace MonoDevelop.SourceEditor +{ + sealed class EditorFactory : ITextEditorFactory + { + + #region ITextEditorFactory implementation + + ITextDocument ITextEditorFactory.CreateNewDocument () + { + return new TextDocumentWrapper (new TextDocument ()); + } + + ITextDocument ITextEditorFactory.CreateNewDocument (MonoDevelop.Core.Text.ITextSource textSource, string fileName, string mimeType) + { + return new TextDocumentWrapper (new TextDocument (textSource.Text) { + Encoding = textSource.Encoding, + UseBom = textSource.UseBOM, + MimeType = mimeType, + FileName = fileName + }); + } + + IReadonlyTextDocument ITextEditorFactory.CreateNewReadonlyDocument (MonoDevelop.Core.Text.ITextSource textSource, string fileName, string mimeType) + { + return new TextDocumentWrapper (new TextDocument (textSource.Text) { + Encoding = textSource.Encoding, + UseBom = textSource.UseBOM, + ReadOnly = true, + MimeType = mimeType, + FileName = fileName + }); + } + + ITextEditorImpl ITextEditorFactory.CreateNewEditor () + { + return new SourceEditorView (); + } + + ITextEditorImpl ITextEditorFactory.CreateNewEditor (IReadonlyTextDocument document) + { + return new SourceEditorView (document); + } + + string[] ITextEditorFactory.GetSyntaxProperties (string mimeType, string name) + { + var mode = SyntaxModeService.GetSyntaxMode (null, mimeType); + if (mode == null) + return null; + System.Collections.Generic.List<string> value; + if (!mode.Properties.TryGetValue (name, out value)) + return null; + return value.ToArray (); + } + #endregion + } +}
\ No newline at end of file diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs index 44fb24dce2..53219debb7 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ErrorText.cs @@ -38,7 +38,7 @@ using MonoDevelop.Components; namespace MonoDevelop.SourceEditor { - public class ErrorText + class ErrorText { public TaskListEntry Task { get; set; } public bool IsError { get; set; } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ExtensibleTextEditor.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ExtensibleTextEditor.cs index 165ddd148b..b32501488e 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ExtensibleTextEditor.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ExtensibleTextEditor.cs @@ -41,15 +41,18 @@ using Mono.Addins; using MonoDevelop.Projects.Text; using MonoDevelop.Ide; using MonoDevelop.Ide.CodeFormatting; -using MonoDevelop.SourceEditor.Extension; using ICSharpCode.NRefactory.TypeSystem; using MonoDevelop.Ide.TypeSystem; using ICSharpCode.NRefactory.Semantics; using MonoDevelop.Components; +using MonoDevelop.Ide.Editor.Extension; +using MonoDevelop.Ide.Editor; +using MonoDevelop.Ide.Editor.Highlighting; +using MonoDevelop.SourceEditor.Wrappers; namespace MonoDevelop.SourceEditor { - public class ExtensibleTextEditor : Mono.TextEditor.TextEditor + class ExtensibleTextEditor : Mono.TextEditor.MonoTextEditor { internal object MemoryProbe = Counters.EditorsInMemory.CreateMemoryProbe (); @@ -57,20 +60,79 @@ namespace MonoDevelop.SourceEditor ExtensionContext extensionContext; Adjustment cachedHAdjustment, cachedVAdjustment; - public ITextEditorExtension Extension { - get; - set; + TextEditorExtension editorExtension; + bool needToAddLastExtension; + + public TextEditorExtension EditorExtension { + get { + return editorExtension; + } + set { + editorExtension = value; + needToAddLastExtension = true; + } } - - public new ISourceEditorOptions Options { - get { return (ISourceEditorOptions)base.Options; } + + SemanticHighlighting semanticHighlighting; + public SemanticHighlighting SemanticHighlighting { + get { + return semanticHighlighting; + } + set { + semanticHighlighting = value; + UpdateSemanticHighlighting (); + } + } + + void UpdateSemanticHighlighting () + { + if (Document.SyntaxMode is SemanticHighlightingSyntaxMode) + return; + if (semanticHighlighting == null) { + Document.MimeType = Document.MimeType; + return; + } + Document.SyntaxMode = new SemanticHighlightingSyntaxMode (this, Document.SyntaxMode, semanticHighlighting); + } + + static Gdk.ModifierType ConvertModifiers (ModifierKeys s) + { + Gdk.ModifierType m = Gdk.ModifierType.None; + if ((s & ModifierKeys.Shift) != 0) + m |= Gdk.ModifierType.ShiftMask; + if ((s & ModifierKeys.Control) != 0) + m |= Gdk.ModifierType.ControlMask; + if ((s & ModifierKeys.Alt) != 0) + m |= Gdk.ModifierType.Mod1Mask; + if ((s & ModifierKeys.Command) != 0) + m |= Gdk.ModifierType.Mod2Mask; + return m; + } + + class LastEditorExtension : TextEditorExtension + { + readonly ExtensibleTextEditor ext; + public LastEditorExtension (ExtensibleTextEditor ext) + { + if (ext == null) + throw new ArgumentNullException ("ext"); + this.ext = ext; + } + + public override bool KeyPress (KeyDescriptor descriptor) + { + ext.SimulateKeyPress ((Gdk.Key)descriptor.SpecialKey, (uint)descriptor.KeyChar, ConvertModifiers (descriptor.ModifierKeys)); + if (descriptor.SpecialKey == SpecialKey.Escape) + return true; + return false; + } } static ExtensibleTextEditor () { var icon = Xwt.Drawing.Image.FromResource ("gutter-bookmark-15.png"); - BookmarkMarker.DrawBookmarkFunc = delegate(TextEditor editor, Cairo.Context cr, DocumentLine lineSegment, double x, double y, double width, double height) { + BookmarkMarker.DrawBookmarkFunc = delegate(Mono.TextEditor.MonoTextEditor editor, Cairo.Context cr, DocumentLine lineSegment, double x, double y, double width, double height) { if (!lineSegment.IsBookmarked) return; cr.DrawImage ( @@ -83,14 +145,14 @@ namespace MonoDevelop.SourceEditor } - public ExtensibleTextEditor (SourceEditorView view, ISourceEditorOptions options, Mono.TextEditor.TextDocument doc) : base(doc, options) + public ExtensibleTextEditor (SourceEditorView view, Mono.TextEditor.ITextEditorOptions options, Mono.TextEditor.TextDocument doc) : base(doc, options) { Initialize (view); } public ExtensibleTextEditor (SourceEditorView view) { - base.Options = new StyledSourceEditorOptions (view.Project, null); + base.Options = new StyledSourceEditorOptions (DefaultSourceEditorOptions.Instance); Initialize (view); } @@ -101,17 +163,11 @@ namespace MonoDevelop.SourceEditor void Initialize (SourceEditorView view) { this.view = view; - Caret.PositionChanged += delegate { - if (Extension != null) { - try { - Extension.CursorPositionChanged (); - } catch (Exception ex) { - ReportExtensionError (ex); - } - } - }; - + Document.TextReplaced += HandleSkipCharsOnReplace; + Document.SyntaxModeChanged += delegate { + UpdateSemanticHighlighting (); + }; UpdateEditMode (); this.DoPopupMenu = ShowPopup; @@ -133,21 +189,7 @@ namespace MonoDevelop.SourceEditor } } - public ExtensionContext ExtensionContext { - get { - return extensionContext; - } - set { - if (extensionContext != null) { - extensionContext.RemoveExtensionNodeHandler ("MonoDevelop/SourceEditor2/TooltipProviders", OnTooltipProviderChanged); - ClearTooltipProviders (); - } - extensionContext = value; - if (extensionContext != null) - extensionContext.AddExtensionNodeHandler ("MonoDevelop/SourceEditor2/TooltipProviders", OnTooltipProviderChanged); - } - } - + static bool? testNewViMode = null; static bool TestNewViMode { get { @@ -159,7 +201,7 @@ namespace MonoDevelop.SourceEditor void UpdateEditMode () { - if (Options.UseViModes) { + if (MonoDevelop.Ide.Editor.DefaultSourceEditorOptions.Instance.UseViModes) { if (TestNewViMode) { if (!(CurrentMode is NewIdeViMode)) CurrentMode = new NewIdeViMode (this); @@ -170,8 +212,8 @@ namespace MonoDevelop.SourceEditor } else { // if (!(CurrentMode is SimpleEditMode)){ SimpleEditMode simpleMode = new SimpleEditMode (); - simpleMode.KeyBindings [EditMode.GetKeyCode (Gdk.Key.Tab)] = new TabAction (this).Action; - simpleMode.KeyBindings [EditMode.GetKeyCode (Gdk.Key.BackSpace)] = EditActions.AdvancedBackspace; + simpleMode.KeyBindings [Mono.TextEditor.EditMode.GetKeyCode (Gdk.Key.Tab)] = new TabAction (this).Action; + simpleMode.KeyBindings [Mono.TextEditor.EditMode.GetKeyCode (Gdk.Key.BackSpace)] = EditActions.AdvancedBackspace; CurrentMode = simpleMode; // } } @@ -190,8 +232,7 @@ namespace MonoDevelop.SourceEditor protected override void OnDestroyed () { UnregisterAdjustments (); - Extension = null; - ExtensionContext = null; + extensionContext = null; view = null; base.OnDestroyed (); if (Options != null) { @@ -199,23 +240,7 @@ namespace MonoDevelop.SourceEditor base.Options = null; } } - - void OnTooltipProviderChanged (object s, ExtensionNodeEventArgs a) - { - TooltipProvider provider; - try { - provider = (TooltipProvider) a.ExtensionObject; - } catch (Exception e) { - LoggingService.LogError ("Can't create tooltip provider:"+ a.ExtensionNode, e); - return; - } - if (a.Change == ExtensionChange.Add) { - AddTooltipProvider (provider); - } else { - RemoveTooltipProvider (provider); - } - } - + public void FireOptionsChange () { this.OptionsChanged (null, null); @@ -255,7 +280,14 @@ namespace MonoDevelop.SourceEditor { isInKeyStroke = true; try { - return Extension.KeyPress (key, (char)ch, state); + if (needToAddLastExtension) { + var ext = EditorExtension; + while (ext.Next != null) + ext = ext.Next; + ext.Next = new LastEditorExtension (this); + needToAddLastExtension = false; + } + return EditorExtension.KeyPress (KeyDescriptor.FromGtk (key, (char)ch, state)); } catch (Exception ex) { ReportExtensionError (ex); } finally { @@ -320,7 +352,7 @@ namespace MonoDevelop.SourceEditor { bool result = true; if (key == Gdk.Key.Escape) { - bool b = Extension != null ? ExtensionKeyPress (key, ch, state) : base.OnIMProcessedKeyPressEvent (key, ch, state); + bool b = EditorExtension != null ? ExtensionKeyPress (key, ch, state) : base.OnIMProcessedKeyPressEvent (key, ch, state); if (b) { view.SourceEditorWidget.RemoveSearchWidget (); return true; @@ -385,7 +417,7 @@ namespace MonoDevelop.SourceEditor char insertionChar = '\0'; bool insertMatchingBracket = false; IDisposable undoGroup = null; - if (skipChar == null && Options.AutoInsertMatchingBracket && braceIndex >= 0 && !IsSomethingSelected) { + if (skipChar == null && MonoDevelop.Ide.Editor.DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket && braceIndex >= 0 && !IsSomethingSelected) { if (!inStringOrComment) { char closingBrace = closingBrackets [braceIndex]; char openingBrace = openBrackets [braceIndex]; @@ -421,8 +453,8 @@ namespace MonoDevelop.SourceEditor Caret.IsInInsertMode = false; skipChars.Remove (skipChar); } - if (Extension != null) { - if (!DefaultSourceEditorOptions.Instance.GenerateFormattingUndoStep) { + if (EditorExtension != null) { + if (!MonoDevelop.Ide.Editor.DefaultSourceEditorOptions.Instance.GenerateFormattingUndoStep) { using (var undo = Document.OpenUndoGroup ()) { if (ExtensionKeyPress (key, ch, state)) result = base.OnIMProcessedKeyPressEvent (key, ch, state); @@ -465,31 +497,23 @@ namespace MonoDevelop.SourceEditor internal string GetErrorInformationAt (int offset) { - DocumentLocation location = Document.OffsetToLocation (offset); + var location = Document.OffsetToLocation (offset); DocumentLine line = Document.GetLine (location.Line); if (line == null) return null; - var error = line.Markers.FirstOrDefault (m => m is ErrorMarker) as ErrorMarker; + + var error = Document.GetTextSegmentMarkersAt (offset).OfType<ErrorMarker> ().FirstOrDefault (); if (error != null) { - if (error.Info.ErrorType == ErrorType.Warning) + if (error.Error.ErrorType == MonoDevelop.Ide.TypeSystem.ErrorType.Warning) return GettextCatalog.GetString ("<b>Parser Warning</b>: {0}", - GLib.Markup.EscapeText (error.Info.Message)); + GLib.Markup.EscapeText (error.Error.Message)); return GettextCatalog.GetString ("<b>Parser Error</b>: {0}", - GLib.Markup.EscapeText (error.Info.Message)); + GLib.Markup.EscapeText (error.Error.Message)); } return null; } - internal ParsedDocument ParsedDocument { - get { - var doc = IdeApp.Workbench.ActiveDocument; - if (doc != null) - return doc.ParsedDocument; - return null; - } - } - public MonoDevelop.Projects.Project Project { get { var doc = IdeApp.Workbench.ActiveDocument; @@ -501,10 +525,10 @@ namespace MonoDevelop.SourceEditor int oldOffset = -1; - public ResolveResult GetLanguageItem (int offset, out DomRegion region) + public Microsoft.CodeAnalysis.ISymbol GetLanguageItem (int offset, out MonoDevelop.Ide.Editor.DocumentRegion region) { oldOffset = offset; - region = DomRegion.Empty; + region = MonoDevelop.Ide.Editor.DocumentRegion.Empty; if (textEditorResolverProvider != null) { return textEditorResolverProvider.GetLanguageItem (view.WorkbenchWindow.Document, offset, out region); @@ -516,7 +540,7 @@ namespace MonoDevelop.SourceEditor { if (IsSomethingSelected) { var result = GetLanguageItem (Caret.Offset, Document.GetTextAt (SelectionRange)); - if (result != null && !result.IsError) + if (result != null) return CodeTemplateContext.InExpression; } return CodeTemplateContext.Standard; @@ -529,7 +553,7 @@ namespace MonoDevelop.SourceEditor internal set { this.textEditorResolverProvider = value; } } - public ResolveResult GetLanguageItem (int offset, string expression) + public Microsoft.CodeAnalysis.ISymbol GetLanguageItem (int offset, string expression) { oldOffset = offset; @@ -580,7 +604,7 @@ namespace MonoDevelop.SourceEditor ParameterInformationWindowManager.HideWindow (null, view); HideTooltip (); const string menuPath = "/MonoDevelop/SourceEditor2/ContextMenu/Editor"; - var ctx = ExtensionContext ?? AddinManager.AddinEngine; + var ctx = view.WorkbenchWindow?.ExtensionContext ?? AddinManager.AddinEngine; CommandEntrySet cset = IdeApp.CommandService.CreateCommandEntrySet (ctx, menuPath); @@ -649,7 +673,7 @@ namespace MonoDevelop.SourceEditor string word = GetWordBeforeCaret (); foreach (CodeTemplate template in CodeTemplateService.GetCodeTemplates (Document.MimeType)) { if (template.Shortcut == word) { - InsertTemplate (template, view.WorkbenchWindow.Document); + InsertTemplate (template, view.WorkbenchWindow.Document.Editor, view.WorkbenchWindow.Document); return true; } } @@ -657,13 +681,16 @@ namespace MonoDevelop.SourceEditor } - internal void InsertTemplate (CodeTemplate template, MonoDevelop.Ide.Gui.Document document) + internal void InsertTemplate (CodeTemplate template, MonoDevelop.Ide.Editor.TextEditor editor, MonoDevelop.Ide.Editor.DocumentContext context) { - using (var undo = Document.OpenUndoGroup ()) { - var result = template.InsertTemplateContents (document); - - var links = result.TextLinks; + using (var undo = editor.OpenUndoGroup ()) { + var result = template.InsertTemplateContents (editor, context); + var links = result.TextLinks.Select (l => new Mono.TextEditor.TextLink (l.Name) { + Links = l.Links.Select (s => new TextSegment (s.Offset, s.Length)).ToList (), + IsEditable = l.IsEditable, + IsIdentifier = l.IsIdentifier + }).ToList (); var tle = new TextLinkEditMode (this, result.InsertPosition, links); tle.TextLinkMode = TextLinkMode.General; if (tle.ShouldStartTextLinkMode) { @@ -1006,7 +1033,7 @@ namespace MonoDevelop.SourceEditor RunAction (SelectionActions.MovePageUp); } - [CommandHandler (MonoDevelop.SourceEditor.SourceEditorCommands.PulseCaret)] + [CommandHandler (MonoDevelop.Ide.Commands.TextEditorCommands.PulseCaret)] internal void OnPulseCaretCommand () { StartCaretPulseAnimation (); @@ -1037,18 +1064,6 @@ namespace MonoDevelop.SourceEditor RunAction (Mono.TextEditor.Vi.ViActions.Join); } } - - [CommandHandler (MonoDevelop.Ide.Commands.EditCommands.SortSelectedLines)] - void SortSelectedLines () - { - RunAction (MiscActions.SortSelectedLines); - } - - [CommandUpdateHandler (MonoDevelop.Ide.Commands.EditCommands.SortSelectedLines)] - void UpdateSortSelectedLines (CommandInfo ci) - { - ci.Enabled = GetTextEditorData ().IsMultiLineSelection; - } #endregion } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/FileRegistry.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/FileRegistry.cs index e069c63271..44a5eecce6 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/FileRegistry.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/FileRegistry.cs @@ -31,6 +31,7 @@ using MonoDevelop.Core; using Services = MonoDevelop.Projects.Services; using MonoDevelop.Ide; using MonoDevelop.Ide.TypeSystem; +using MonoDevelop.Ide.Editor; namespace MonoDevelop.SourceEditor { @@ -42,7 +43,6 @@ namespace MonoDevelop.SourceEditor { readonly static List<SourceEditorView> openFiles = new List<SourceEditorView> (); readonly static FileSystemWatcher fileSystemWatcher; - readonly static StringComparison fileNameComparer = Platform.IsWindows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; public static bool SuspendFileWatch { get; @@ -84,7 +84,7 @@ namespace MonoDevelop.SourceEditor bool foundOneChange = false; foreach (var file in e) { foreach (var view in openFiles) { - if (SkipView (view) || !string.Equals (view.ContentName, file.FileName, fileNameComparer)) + if (SkipView (view) || !string.Equals (view.ContentName, file.FileName, FilePath.PathComparison)) continue; if (!view.IsDirty/* && (IdeApp.Workbench.AutoReloadDocuments || file.AutoReload)*/) view.SourceEditorWidget.Reload (); @@ -129,7 +129,7 @@ namespace MonoDevelop.SourceEditor foreach (var view in openFiles) { if (SkipView (view)) continue; - if (string.Equals (view.ContentName, fileName, fileNameComparer)) { + if (string.Equals (view.ContentName, fileName, FilePath.PathComparison)) { if (view.LastSaveTimeUtc == File.GetLastWriteTimeUtc (fileName)) continue; if (!view.IsDirty/* && IdeApp.Workbench.AutoReloadDocuments*/) diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/GotoLineNumberWidget.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/GotoLineNumberWidget.cs index b19f1e26ad..a8ad10acd7 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/GotoLineNumberWidget.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/GotoLineNumberWidget.cs @@ -35,7 +35,7 @@ namespace MonoDevelop.SourceEditor { public partial class GotoLineNumberWidget : Gtk.Bin { - readonly TextEditor textEditor; + readonly MonoTextEditor textEditor; readonly Widget frame; double vSave, hSave; @@ -45,7 +45,7 @@ namespace MonoDevelop.SourceEditor void HandleViewTextEditorhandleSizeAllocated (object o, SizeAllocatedArgs args) { int newX = textEditor.Allocation.Width - this.Allocation.Width - 8; - var containerChild = ((TextEditor.EditorContainerChild)textEditor [frame]); + var containerChild = ((MonoTextEditor.EditorContainerChild)textEditor [frame]); if (newX != containerChild.X) { this.entryLineNumber.WidthRequest = textEditor.Allocation.Width / 4; containerChild.X = newX; @@ -58,7 +58,7 @@ namespace MonoDevelop.SourceEditor Destroy (); } - public GotoLineNumberWidget (TextEditor textEditor, Widget frame) + public GotoLineNumberWidget (MonoTextEditor textEditor, Widget frame) { this.textEditor = textEditor; this.frame = frame; diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/HoverCloseButton.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/HoverCloseButton.cs index 0284769bc6..e63b93c8d3 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/HoverCloseButton.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/HoverCloseButton.cs @@ -29,7 +29,7 @@ using Gdk; namespace MonoDevelop.SourceEditor { - public class HoverCloseButton : EventBox + class HoverCloseButton : EventBox { bool hovered; diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/IdeViMode.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/IdeViMode.cs index d7dcbada63..5905336f38 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/IdeViMode.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/IdeViMode.cs @@ -34,7 +34,7 @@ using MonoDevelop.Ide; namespace MonoDevelop.SourceEditor { - public class NewIdeViMode : Mono.TextEditor.Vi.NewViEditMode + class NewIdeViMode : Mono.TextEditor.Vi.NewViEditMode { public NewIdeViMode (ExtensibleTextEditor editor) { @@ -48,7 +48,7 @@ namespace MonoDevelop.SourceEditor } } - public class IdeViMode : Mono.TextEditor.Vi.ViEditMode + class IdeViMode : Mono.TextEditor.Vi.ViEditMode { new ExtensibleTextEditor editor; TabAction tabAction; diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/LanguageItemWindow.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/LanguageItemWindow.cs index 10172f1446..f659b77a2b 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/LanguageItemWindow.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/LanguageItemWindow.cs @@ -39,7 +39,7 @@ using ICSharpCode.NRefactory.Semantics; namespace MonoDevelop.SourceEditor { - public class LanguageItemWindow: MonoDevelop.Components.TooltipWindow + class LanguageItemWindow: MonoDevelop.Components.TooltipWindow { public bool IsEmpty { get; set; } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SyntaxModeService.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ListDataProviderWrapper.cs index 1f57d22a7e..34d0b8fa5f 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SyntaxModeService.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ListDataProviderWrapper.cs @@ -1,21 +1,20 @@ -// -// SyntaxModeService.cs -// +// SourceEditorView.cs +// // Author: // Mike Krüger <mkrueger@novell.com> // -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// +// Copyright (c) 2008 Novell, Inc (http://www.novell.com) +// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,36 +22,42 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. - -using System; -using Mono.TextEditor.Highlighting; -using Mono.Addins; - +using Mono.TextEditor.PopupWindow; namespace MonoDevelop.SourceEditor { - public static class SyntaxModeService + class ListDataProviderWrapper : IListDataProvider<string> { - static SyntaxModeService () + MonoDevelop.Ide.CodeTemplates.IListDataProvider<string> dataProvider; + + public ListDataProviderWrapper (MonoDevelop.Ide.CodeTemplates.IListDataProvider<string> dataProvider) + { + this.dataProvider = dataProvider; + } + + #region IListDataProvider implementation + Xwt.Drawing.Image IListDataProvider<string>.GetIcon (int index) { -// Console.WriteLine ("SETUP SMS"); - AddinManager.AddExtensionNodeHandler ("/MonoDevelop/SourceEditor2/CustomModes", delegate(object sender, ExtensionNodeEventArgs args) { - SyntaxModeCodon syntaxModeCodon = (SyntaxModeCodon)args.ExtensionNode; - switch (args.Change) { - case ExtensionChange.Add: -// Console.WriteLine ("INstall:" + syntaxModeCodon.MimeTypes); - Mono.TextEditor.Highlighting.SyntaxModeService.InstallSyntaxMode (syntaxModeCodon.MimeTypes, new SyntaxModeProvider (d => { - var result = syntaxModeCodon.SyntaxMode; - result.Document = d; - return result; - })); - break; - } - }); + return dataProvider.GetIcon (index); } - - public static void EnsureLoad () + + string IListDataProvider<string>.GetText (int index) { + return dataProvider.GetText (index); + } + + int IListDataProvider<string>.Count { + get { + return dataProvider.Count; + } + } + + string IListDataProvider<string>.this [int index] { + get { + return dataProvider[index]; + } } + #endregion } + } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MarkerOperationsHandler.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MarkerOperationsHandler.cs index 1aab3dd990..7d9f239948 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MarkerOperationsHandler.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MarkerOperationsHandler.cs @@ -35,7 +35,7 @@ using MonoDevelop.Ide; namespace MonoDevelop.SourceEditor { - public class MarkerOperationsHandler : CommandHandler + class MarkerOperationsHandler : CommandHandler { protected override void Run (object data) { diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleCache.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleCache.cs index c7f1464e68..5ace0ccd36 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleCache.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleCache.cs @@ -43,7 +43,7 @@ namespace MonoDevelop.SourceEditor internal Dictionary<string, LayoutDescriptor> textWidthDictionary = new Dictionary<string, LayoutDescriptor> (); internal Dictionary<DocumentLine, double> lineWidthDictionary = new Dictionary<DocumentLine, double> (); - internal TextEditor editor; + internal MonoTextEditor editor; internal Pango.FontDescription fontDescription; internal Pango.FontDescription tooltipFontDescription; @@ -51,7 +51,7 @@ namespace MonoDevelop.SourceEditor public MessageBubbleTextMarker CurrentSelectedTextMarker; - public MessageBubbleCache (TextEditor editor) + public MessageBubbleCache (MonoTextEditor editor) { this.editor = editor; errorPixbuf = Xwt.Drawing.Image.FromResource ("gutter-error-15.png"); diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleCommands.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleCommands.cs deleted file mode 100644 index 2f28478563..0000000000 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleCommands.cs +++ /dev/null @@ -1,76 +0,0 @@ -// -// MessageBubbleCommands.cs -// -// Author: -// Mike Krüger <mkrueger@novell.com> -// -// Copyright (c) 2010 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. -using System; -using MonoDevelop.Ide; -using MonoDevelop.Components.Commands; -using MonoDevelop.Core; - -namespace MonoDevelop.SourceEditor -{ - public enum MessageBubbleCommands - { - HideIssues, - ToggleIssues - } - - class HideIssuesHandler : CommandHandler - { - protected override void Update (CommandInfo info) - { - base.Update (info); - info.Text = IdeApp.Preferences.DefaultHideMessageBubbles ? GettextCatalog.GetString ("_Show Message Bubbles") : GettextCatalog.GetString ("_Hide Message Bubbles"); - } - - protected override void Run (object data) - { - IdeApp.Preferences.DefaultHideMessageBubbles = !IdeApp.Preferences.DefaultHideMessageBubbles; - } - } - - class ToggleIssuesHandler : CommandHandler - { - protected override void Run (object data) - { - Action action = data as Action; - if (action != null) - action (); - } - - protected override void Update (CommandArrayInfo ainfo) - { - CommandInfo info = ainfo.Add (GettextCatalog.GetString ("_Errors & Warnings"), new Action (delegate { - MonoDevelop.Ide.IdeApp.Preferences.ShowMessageBubbles = MonoDevelop.Ide.ShowMessageBubbles.ForErrorsAndWarnings; - })); - info.Checked = MonoDevelop.Ide.IdeApp.Preferences.ShowMessageBubbles == MonoDevelop.Ide.ShowMessageBubbles.ForErrorsAndWarnings; - - info = ainfo.Add (GettextCatalog.GetString ("E_rrors only"), new Action (delegate { - MonoDevelop.Ide.IdeApp.Preferences.ShowMessageBubbles = MonoDevelop.Ide.ShowMessageBubbles.ForErrors; - })); - info.Checked = MonoDevelop.Ide.IdeApp.Preferences.ShowMessageBubbles == MonoDevelop.Ide.ShowMessageBubbles.ForErrors; - } - } -} - diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs index d92e322486..6facc36d75 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/MessageBubbleTextMarker.cs @@ -34,24 +34,25 @@ using MonoDevelop.Ide; using System.Text.RegularExpressions; using Mono.TextEditor.Highlighting; using MonoDevelop.Ide.Fonts; -using MonoDevelop.Components; using Gtk; +using MonoDevelop.Components; +using MonoDevelop.SourceEditor.Wrappers; namespace MonoDevelop.SourceEditor { - class MessageBubbleTextMarker : MarginMarker, IDisposable, IActionTextLineMarker + class MessageBubbleTextMarker : MarginMarker, IDisposable, IActionTextLineMarker, MonoDevelop.Ide.Editor.IMessageBubbleLineMarker { readonly MessageBubbleCache cache; internal const int border = 4; - TextEditor editor { + MonoTextEditor editor { get { return cache.editor;} } public override bool IsVisible { get { return !task.Completed; } - set { task.Completed = !value; } + set { task.Completed = !value; editor.QueueDraw (); } } public bool UseVirtualLines { get; set; } @@ -62,12 +63,13 @@ namespace MonoDevelop.SourceEditor } TaskListEntry task; + TaskListEntry primaryTask; DocumentLine lineSegment; // int editorAllocHeight = -1; // int lastLineLength = -1; internal double lastHeight = 0; - public double GetLineHeight (TextEditor editor) + public double GetLineHeight (MonoTextEditor editor) { return editor.LineHeight; /* @@ -96,8 +98,10 @@ namespace MonoDevelop.SourceEditor return height;*/ } - public void SetPrimaryError (string text) + public void SetPrimaryError (TaskListEntry task) { + this.primaryTask = task; + var text = task.Description; EnsureLayoutCreated (editor); var match = mcsErrorFormat.Match (text); @@ -143,6 +147,15 @@ namespace MonoDevelop.SourceEditor string initialText; bool isError; + + public MessageBubbleTextMarker (MessageBubbleCache cache) + { + if (cache == null) + throw new ArgumentNullException ("cache"); + this.cache = cache; + this.IsVisible = true; + } + internal MessageBubbleTextMarker (MessageBubbleCache cache, TaskListEntry task, DocumentLine lineSegment, bool isError, string errorMessage) { if (cache == null) @@ -160,13 +173,16 @@ namespace MonoDevelop.SourceEditor static System.Text.RegularExpressions.Regex mcsErrorFormat = new System.Text.RegularExpressions.Regex ("(.+)\\(CS\\d+\\)\\Z"); public void AddError (TaskListEntry task, bool isError, string errorMessage) { + if (this.task == null) { + this.task = task; + } var match = mcsErrorFormat.Match (errorMessage); if (match.Success) errorMessage = match.Groups [1].Value; errors.Add (new ErrorText (task, isError, errorMessage)); DisposeLayout (); } - + public void DisposeLayout () { layouts = null; @@ -271,7 +287,7 @@ namespace MonoDevelop.SourceEditor get { return layouts; } } - internal void EnsureLayoutCreated (TextEditor editor) + internal void EnsureLayoutCreated (MonoTextEditor editor) { if (layouts != null) return; @@ -332,12 +348,12 @@ namespace MonoDevelop.SourceEditor } #region IActionTextMarker implementation - public bool MousePressed (TextEditor editor, MarginMouseEventArgs args) + public bool MousePressed (MonoTextEditor editor, MarginMouseEventArgs args) { return false; } - public void MouseHover (TextEditor editor, MarginMouseEventArgs args, TextLineMarkerHoverResult result) + public void MouseHover (MonoTextEditor editor, MarginMouseEventArgs args, TextLineMarkerHoverResult result) { if (!IsVisible) return; @@ -355,12 +371,12 @@ namespace MonoDevelop.SourceEditor double bubbleWidth; bool bubbleIsReduced; - public override void Draw (TextEditor editor, Cairo.Context g, double y, LineMetrics metrics) + public override void Draw (MonoTextEditor editor, Cairo.Context g, LineMetrics metrics) { } - public override void DrawAfterEol (TextEditor textEditor, Cairo.Context g, double y, EndOfLineMetrics metrics) + public override void DrawAfterEol (MonoTextEditor textEditor, Cairo.Context g, EndOfLineMetrics metrics) { if (!IsVisible) return; @@ -374,6 +390,7 @@ namespace MonoDevelop.SourceEditor var sx = metrics.TextRenderEndPosition; var width = LayoutWidth + errorCounterWidth + editor.LineHeight; var drawLayout = layouts[0].Layout; + var y = metrics.LineYRenderStartPosition; bool customLayout = true; //sx + width > editor.Allocation.Width; bool hideText = false; bubbleIsReduced = customLayout; @@ -494,7 +511,7 @@ namespace MonoDevelop.SourceEditor return margin is IconMargin; } - void DrawIconMarginBackground (TextEditor ed, Cairo.Context cr, MarginDrawMetrics metrics) + void DrawIconMarginBackground (MonoTextEditor ed, Cairo.Context cr, MarginDrawMetrics metrics) { cr.Rectangle (metrics.X, metrics.Y, metrics.Width, metrics.Height); cr.SetSourceColor (IconMarginColor.Color); @@ -510,7 +527,7 @@ namespace MonoDevelop.SourceEditor } } - public override void DrawForeground (TextEditor editor, Cairo.Context cr, MarginDrawMetrics metrics) + public override void DrawForeground (MonoTextEditor editor, Cairo.Context cr, MarginDrawMetrics metrics) { var tx = Math.Round (metrics.X + (metrics.Width - cache.errorPixbuf.Width) / 2) - 1; var ty = Math.Floor (metrics.Y + (metrics.Height - cache.errorPixbuf.Height) / 2); @@ -521,7 +538,7 @@ namespace MonoDevelop.SourceEditor cr.Restore (); } - public override bool DrawBackground (TextEditor editor, Cairo.Context cr, MarginDrawMetrics metrics) + public override bool DrawBackground (MonoTextEditor editor, Cairo.Context cr, MarginDrawMetrics metrics) { if (metrics.Margin is FoldMarkerMargin || metrics.Margin is GutterMargin || metrics.Margin is ActionMargin) return DrawMarginBackground (editor, metrics.Margin, cr, metrics.Area, lineSegment, metrics.LineNumber, metrics.X, metrics.Y, metrics.Height); @@ -532,7 +549,7 @@ namespace MonoDevelop.SourceEditor return false; } - bool DrawMarginBackground (TextEditor e, Margin margin, Cairo.Context cr, Cairo.Rectangle area, DocumentLine documentLine, long line, double x, double y, double lineHeight) + bool DrawMarginBackground (MonoTextEditor e, Margin margin, Cairo.Context cr, Cairo.Rectangle area, DocumentLine documentLine, long line, double x, double y, double lineHeight) { if (cache.CurrentSelectedTextMarker != null && cache.CurrentSelectedTextMarker != this) return false; @@ -547,7 +564,7 @@ namespace MonoDevelop.SourceEditor #region text background - public override bool DrawBackground (TextEditor editor, Cairo.Context g, double y, LineMetrics metrics) + public override bool DrawBackground (MonoTextEditor editor, Cairo.Context g, LineMetrics metrics) { if (!IsVisible) return false; @@ -569,7 +586,7 @@ namespace MonoDevelop.SourceEditor int active = editor.Document.GetTextAt (lineSegment) == initialText ? 0 : 1; bool highlighted = active == 0 && isCaretInLine; - + var y = metrics.LineYRenderStartPosition; // draw background if (!markerShouldDrawnAsHidden) { DrawRectangle (g, x, y, right, editor.LineHeight); @@ -627,7 +644,7 @@ namespace MonoDevelop.SourceEditor return true; } - void DrawErrorMarkers (TextEditor editor, Cairo.Context g, LineMetrics metrics, double y) + void DrawErrorMarkers (MonoTextEditor editor, Cairo.Context g, LineMetrics metrics, double y) { uint curIndex = 0, byteIndex = 0; @@ -652,5 +669,38 @@ namespace MonoDevelop.SourceEditor } #endregion + + MonoDevelop.Ide.Editor.IDocumentLine MonoDevelop.Ide.Editor.ITextLineMarker.Line { + get { + return new DocumentLineWrapper (LineSegment); + } + } + + void MonoDevelop.Ide.Editor.IMessageBubbleLineMarker.AddTask (TaskListEntry task) + { + AddError (task, task.Severity == TaskSeverity.Error, task.Description); + } + + TaskListEntry MonoDevelop.Ide.Editor.IMessageBubbleLineMarker.PrimaryTask { + get { + return primaryTask; + } + set { + SetPrimaryError (task); + } + } + + int MonoDevelop.Ide.Editor.IMessageBubbleLineMarker.TaskCount { + get { + return errors.Count; + } + } + + IEnumerable<TaskListEntry> MonoDevelop.Ide.Editor.IMessageBubbleLineMarker.Tasks { + get { + return errors.Select (e => e.Task); + } + } + } } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/OverlayMessageWindow.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/OverlayMessageWindow.cs index 0d9afdeea5..13752b4b1c 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/OverlayMessageWindow.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/OverlayMessageWindow.cs @@ -31,7 +31,7 @@ using Gdk; namespace MonoDevelop.SourceEditor { - public class OverlayMessageWindow : Gtk.EventBox + class OverlayMessageWindow : Gtk.EventBox { const int border = 8; @@ -50,7 +50,7 @@ namespace MonoDevelop.SourceEditor this.ShowAll (); textEditor.AddTopLevelWidget (this, 0, 0); textEditor.SizeAllocated += HandleSizeAllocated; - var child = (TextEditor.EditorContainerChild)textEditor [this]; + var child = (MonoTextEditor.EditorContainerChild)textEditor [this]; child.FixedPosition = true; } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/PinnedWatchWidget.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/PinnedWatchWidget.cs index c53fa61362..343a2e43d5 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/PinnedWatchWidget.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/PinnedWatchWidget.cs @@ -37,12 +37,12 @@ using Gtk; namespace MonoDevelop.SourceEditor { - public class PinnedWatchWidget : Gtk.EventBox + class PinnedWatchWidget : Gtk.EventBox { readonly ObjectValueTreeView valueTree; ObjectValue objectValue; - TextEditor Editor { + MonoTextEditor Editor { get; set; } @@ -70,7 +70,7 @@ namespace MonoDevelop.SourceEditor } } - public PinnedWatchWidget (TextEditor editor, PinnedWatch watch) + public PinnedWatchWidget (MonoTextEditor editor, PinnedWatch watch) { objectValue = watch.Value; Editor = editor; diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SearchAndReplaceWidget.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SearchAndReplaceWidget.cs index cb6cedc56f..3bcb5c7387 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SearchAndReplaceWidget.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SearchAndReplaceWidget.cs @@ -54,7 +54,7 @@ namespace MonoDevelop.SourceEditor set; } - readonly TextEditor textEditor; + readonly MonoTextEditor textEditor; readonly Widget frame; bool isReplaceMode = true; Widget[] replaceWidgets; @@ -101,7 +101,7 @@ namespace MonoDevelop.SourceEditor if (frame == null || textEditor == null) return; int newX = textEditor.Allocation.Width - Allocation.Width - 8; - TextEditor.EditorContainerChild containerChild = ((TextEditor.EditorContainerChild)textEditor [frame]); + MonoTextEditor.EditorContainerChild containerChild = ((MonoTextEditor.EditorContainerChild)textEditor [frame]); if (newX != containerChild.X) { searchEntry.WidthRequest = textEditor.Allocation.Width / 3; containerChild.X = newX; @@ -118,7 +118,7 @@ namespace MonoDevelop.SourceEditor return "(" + nextShortcut + ")"; } - public SearchAndReplaceWidget (TextEditor textEditor, Widget frame) + public SearchAndReplaceWidget (MonoTextEditor textEditor, Widget frame) { if (textEditor == null) throw new ArgumentNullException ("textEditor"); @@ -827,7 +827,7 @@ But I leave it in in the case I've missed something. Mike textEditor.SearchPattern = searchPattern; } - public static SearchResult FindNext (TextEditor textEditor) + public static SearchResult FindNext (MonoTextEditor textEditor) { textEditor.SearchPattern = SearchAndReplaceOptions.SearchPattern; SearchResult result = textEditor.FindNext (true); @@ -848,7 +848,7 @@ But I leave it in in the case I've missed something. Mike return result; } - public static SearchResult FindPrevious (TextEditor textEditor) + public static SearchResult FindPrevious (MonoTextEditor textEditor) { textEditor.SearchPattern = SearchAndReplaceOptions.SearchPattern; SearchResult result = textEditor.FindPrevious (true); diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorCommands.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorCommands.cs index 847f0e93a1..53776a244b 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorCommands.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorCommands.cs @@ -33,9 +33,6 @@ namespace MonoDevelop.SourceEditor public enum SourceEditorCommands { MarkerOperations, - DynamicAbbrev, - PulseCaret, - ToggleErrorTextMarker, NextIssue, PrevIssue, diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorDisplayBinding.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorDisplayBinding.cs deleted file mode 100644 index 704ca02a68..0000000000 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorDisplayBinding.cs +++ /dev/null @@ -1,109 +0,0 @@ -// SourceEditorDisplayBinding.cs -// -// Author: -// Mike Krüger <mkrueger@novell.com> -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; -using System.IO; -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide; -using MonoDevelop.Ide.Codons; -using MonoDevelop.Projects; - -namespace MonoDevelop.SourceEditor -{ - public class SourceEditorDisplayBinding : IViewDisplayBinding - { - static bool IsInitialized = false; - - public static FilePath SyntaxModePath { - get { - return UserProfile.Current.UserDataRoot.Combine ("HighlightingSchemes"); - } - } - - static SourceEditorDisplayBinding () - { - InitSourceEditor (); - } - - public static void InitSourceEditor () - { - if (IsInitialized) - return; - IsInitialized = true; - - MonoDevelop.SourceEditor.Extension.TemplateExtensionNodeLoader.Init (); - DefaultSourceEditorOptions.Init (); - SyntaxModeService.EnsureLoad (); - LoadCustomStylesAndModes (); - } - - internal static void LoadCustomStylesAndModes () - { - bool success = true; - if (!Directory.Exists (SyntaxModePath)) { - try { - Directory.CreateDirectory (SyntaxModePath); - } catch (Exception e) { - success = false; - LoggingService.LogError ("Can't create syntax mode directory", e); - } - } - if (success) - Mono.TextEditor.Highlighting.SyntaxModeService.LoadStylesAndModes (SyntaxModePath); - } - - public string Name { - get { - return GettextCatalog.GetString ("Source Code Editor"); - } - } - - public bool CanHandle (FilePath fileName, string mimeType, Project ownerProject) - { - if (fileName != null) - return DesktopService.GetFileIsText (fileName, mimeType); - - if (!string.IsNullOrEmpty (mimeType)) - return DesktopService.GetMimeTypeIsText (mimeType); - - return false; - } - - public IViewContent CreateContent (FilePath fileName, string mimeType, Project ownerProject) - { - return new SourceEditorView (); - } - - public bool CanHandleFile (string fileName) - { - return DesktopService.GetFileIsText (fileName); - } - - public bool CanUseAsDefault { - get { return true; } - } - } -} diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorOptions.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorOptions.cs deleted file mode 100644 index 67208ec589..0000000000 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorOptions.cs +++ /dev/null @@ -1,682 +0,0 @@ -// SourceEditorOptions.cs -// -// Author: -// Mike Krüger <mkrueger@novell.com> -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the "Software"), to deal -// in the Software without restriction, including without limitation the rights -// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -// copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -// THE SOFTWARE. - -using System; - -using Mono.TextEditor; -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Ide; -using MonoDevelop.Ide.Fonts; - -namespace MonoDevelop.SourceEditor -{ - [Obsolete ("Use WordNavigationStyle")] - public enum ControlLeftRightMode - { - MonoDevelop, - Emacs, - SharpDevelop - } - - public enum WordNavigationStyle - { - Unix, - Windows - } - - public enum LineEndingConversion { - Ask, - LeaveAsIs, - ConvertAlways - } - - public class DefaultSourceEditorOptions : TextEditorOptions, ISourceEditorOptions - { - static DefaultSourceEditorOptions instance; - //static TextStylePolicy defaultPolicy; - static bool inited; - - public static DefaultSourceEditorOptions Instance { - get { return instance; } - } - - static DefaultSourceEditorOptions () - { - Init (); - } - - public static void Init () - { - if (inited) - return; - inited = true; - - TextStylePolicy policy = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<TextStylePolicy> ("text/plain"); - instance = new DefaultSourceEditorOptions (policy); - MonoDevelop.Projects.Policies.PolicyService.DefaultPolicies.PolicyChanged += instance.HandlePolicyChanged; - } - - void HandlePolicyChanged (object sender, MonoDevelop.Projects.Policies.PolicyChangedEventArgs args) - { - TextStylePolicy pol = MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<TextStylePolicy> ("text/plain"); - UpdateStylePolicy (pol); - } - - DefaultSourceEditorOptions (MonoDevelop.Ide.Gui.Content.TextStylePolicy currentPolicy) - { - LoadAllPrefs (); - UpdateStylePolicy (currentPolicy); - PropertyService.PropertyChanged += UpdatePreferences; - FontService.RegisterFontChangedCallback ("Editor", UpdateFont); - FontService.RegisterFontChangedCallback ("Pad", UpdateFont); - - } - - public override void Dispose() - { - PropertyService.PropertyChanged -= UpdatePreferences; - FontService.RemoveCallback (UpdateFont); - } - - void UpdateFont () - { - base.FontName = FontName; - base.GutterFontName = GutterFontName; - this.OnChanged (EventArgs.Empty); - - } - - void UpdateStylePolicy (MonoDevelop.Ide.Gui.Content.TextStylePolicy currentPolicy) - { - this.defaultEolMarker = TextStylePolicy.GetEolMarker (currentPolicy.EolMarker); - - base.TabsToSpaces = currentPolicy.TabsToSpaces; // PropertyService.Get ("TabsToSpaces", false); - base.IndentationSize = currentPolicy.TabWidth; //PropertyService.Get ("TabIndent", 4); - base.RulerColumn = currentPolicy.FileWidth; //PropertyService.Get ("RulerColumn", 80); - base.AllowTabsAfterNonTabs = !currentPolicy.NoTabsAfterNonTabs; //PropertyService.Get ("AllowTabsAfterNonTabs", true); - base.RemoveTrailingWhitespaces = currentPolicy.RemoveTrailingWhitespace; //PropertyService.Get ("RemoveTrailingWhitespaces", true); - } - - // Need to be picky about only updating individual properties when they change. - // The old approach called LoadAllPrefs on any prefs event, which sometimes caused - // massive change event storms. - void UpdatePreferences (object sender, PropertyChangedEventArgs args) - { - try { - switch (args.Key) { - case "TabIsReindent": - this.TabIsReindent = (bool)args.NewValue; - break; - case "AutoInsertMatchingBracket": - this.AutoInsertMatchingBracket = (bool)args.NewValue; - break; - case "UnderlineErrors": - this.UnderlineErrors = (bool)args.NewValue; - break; - case "IndentStyle": - if (args.NewValue == null) { - LoggingService.LogWarning ("tried to set indent style == null"); - } else if (!(args.NewValue is IndentStyle)) { - LoggingService.LogWarning ("tried to set indent style to " + args.NewValue + " which isn't from type IndentStyle instead it is from:" + args.NewValue.GetType ()); - this.IndentStyle = (IndentStyle)Enum.Parse (typeof(IndentStyle), args.NewValue.ToString ()); - } else - this.IndentStyle = (IndentStyle)args.NewValue; - break; - case "ShowLineNumberMargin": - base.ShowLineNumberMargin = (bool)args.NewValue; - break; - case "ShowFoldMargin": - base.ShowFoldMargin = (bool)args.NewValue; - break; - case "HighlightCaretLine": - base.HighlightCaretLine = (bool)args.NewValue; - break; - case "HighlightMatchingBracket": - base.HighlightMatchingBracket = (bool)args.NewValue; - break; - case "ShowRuler": - base.ShowRuler = (bool)args.NewValue; - break; - case "FontName": - base.FontName = (string)args.NewValue; - break; - case "GutterFontName": - base.GutterFontName = (string)args.NewValue; - break; - case "ColorScheme": - base.ColorScheme = (string)args.NewValue; - break; - case "DefaultRegionsFolding": - this.DefaultRegionsFolding = (bool)args.NewValue; - break; - case "DefaultCommentFolding": - this.DefaultCommentFolding = (bool)args.NewValue; - break; - case "UseViModes": - this.UseViModes = (bool)args.NewValue; - break; - case "OnTheFlyFormatting": - this.OnTheFlyFormatting = (bool)args.NewValue; - break; - case "WordNavigationStyle": - this.WordNavigationStyle = (WordNavigationStyle)args.NewValue; - break; - case "EnableAnimations": - base.EnableAnimations = (bool)args.NewValue; - break; - case "DrawIndentationMarkers": - base.DrawIndentationMarkers = (bool)args.NewValue; - break; - case "EnableQuickDiff": - base.EnableQuickDiff = (bool)args.NewValue; - break; - case "GenerateFormattingUndoStep": - base.GenerateFormattingUndoStep = (bool)args.NewValue; - break; - } - } catch (Exception ex) { - LoggingService.LogError ("SourceEditorOptions error with property value for '" + (args.Key ?? "") + "'", ex); - } - } - - void LoadAllPrefs () - { - this.tabIsReindent = PropertyService.Get ("TabIsReindent", false); - // this.autoInsertTemplates = PropertyService.Get ("AutoInsertTemplates", false); - this.autoInsertMatchingBracket = PropertyService.Get ("AutoInsertMatchingBracket", false); - this.smartSemicolonPlacement = PropertyService.Get ("SmartSemicolonPlacement", false); - this.underlineErrors = PropertyService.Get ("UnderlineErrors", true); - this.indentStyle = PropertyService.Get ("IndentStyle", IndentStyle.Smart); - base.ShowLineNumberMargin = PropertyService.Get ("ShowLineNumberMargin", true); - base.ShowFoldMargin = PropertyService.Get ("ShowFoldMargin", false); - base.HighlightCaretLine = PropertyService.Get ("HighlightCaretLine", false); - base.HighlightMatchingBracket = PropertyService.Get ("HighlightMatchingBracket", true); - base.ShowRuler = PropertyService.Get ("ShowRuler", false); - base.FontName = PropertyService.Get ("FontName", "Mono 10"); - base.GutterFontName = PropertyService.Get ("GutterFontName", ""); - base.ColorScheme = PropertyService.Get ("ColorScheme", "Default"); - this.defaultRegionsFolding = PropertyService.Get ("DefaultRegionsFolding", false); - this.defaultCommentFolding = PropertyService.Get ("DefaultCommentFolding", true); - this.useViModes = PropertyService.Get ("UseViModes", false); - this.onTheFlyFormatting = PropertyService.Get ("OnTheFlyFormatting", true); - - WordNavigationStyle defaultWordNavigation = WordNavigationStyle.Unix; - if (Platform.IsWindows || PropertyService.Get ("ControlLeftRightMode", (string)null) == "SharpDevelop") { - defaultWordNavigation = WordNavigationStyle.Windows; - } - this.WordNavigationStyle = PropertyService.Get ("WordNavigationStyle", defaultWordNavigation); - - base.EnableAnimations = PropertyService.Get ("EnableAnimations", true); - this.EnableHighlightUsages = PropertyService.Get ("EnableHighlightUsages", false); - base.DrawIndentationMarkers = PropertyService.Get ("DrawIndentationMarkers", false); - this.lineEndingConversion = PropertyService.Get ("LineEndingConversion", LineEndingConversion.Ask); - base.GenerateFormattingUndoStep = PropertyService.Get ("GenerateFormattingUndoStep", false); - base.ShowWhitespaces = PropertyService.Get ("ShowWhitespaces", Mono.TextEditor.ShowWhitespaces.Never); - base.IncludeWhitespaces = PropertyService.Get ("IncludeWhitespaces", Mono.TextEditor.IncludeWhitespaces.All); - base.WrapLines = PropertyService.Get ("WrapLines", false); - base.EnableQuickDiff = PropertyService.Get ("EnableQuickDiff", false); - } - - #region new options - - public bool EnableAutoCodeCompletion { - get { return CompletionTextEditorExtension.EnableAutoCodeCompletion; } - set { CompletionTextEditorExtension.EnableAutoCodeCompletion.Set (value); } - } - - bool defaultRegionsFolding; - public bool DefaultRegionsFolding { - get { - return defaultRegionsFolding; - } - set { - if (value != this.defaultRegionsFolding) { - this.defaultRegionsFolding = value; - PropertyService.Set ("DefaultRegionsFolding", value); - OnChanged (EventArgs.Empty); - } - } - } - - bool defaultCommentFolding; - public bool DefaultCommentFolding { - get { - return defaultCommentFolding; - } - set { - if (value != this.defaultCommentFolding) { - this.defaultCommentFolding = value; - PropertyService.Set ("DefaultCommentFolding", value); - OnChanged (EventArgs.Empty); - } - } - } - - public bool EnableSemanticHighlighting { - get { - return true; - } - } - /* - bool autoInsertTemplates; - public bool AutoInsertTemplates { - get { - return autoInsertTemplates; - } - set { - if (value != this.autoInsertTemplates) { - this.autoInsertTemplates = value; - PropertyService.Set ("AutoInsertTemplates", value); - OnChanged (EventArgs.Empty); - } - } - }*/ - - bool tabIsReindent; - public bool TabIsReindent { - get { - return tabIsReindent; - } - set { - if (value != this.tabIsReindent) { - this.tabIsReindent = value; - PropertyService.Set ("TabIsReindent", value); - OnChanged (EventArgs.Empty); - } - } - } - - bool autoInsertMatchingBracket; - public bool AutoInsertMatchingBracket { - get { - return autoInsertMatchingBracket; - } - set { - if (value != this.autoInsertMatchingBracket) { - this.autoInsertMatchingBracket = value; - PropertyService.Set ("AutoInsertMatchingBracket", value); - OnChanged (EventArgs.Empty); - } - } - } - - bool smartSemicolonPlacement; - public bool SmartSemicolonPlacement { - get { - return smartSemicolonPlacement; - } - set { - if (value != this.smartSemicolonPlacement) { - this.smartSemicolonPlacement= value; - PropertyService.Set ("SmartSemicolonPlacement", value); - OnChanged (EventArgs.Empty); - } - } - } - - bool underlineErrors; - public bool UnderlineErrors { - get { - return underlineErrors; - } - set { - if (value != this.underlineErrors) { - this.underlineErrors = value; - PropertyService.Set ("UnderlineErrors", value); - OnChanged (EventArgs.Empty); - } - } - } - - IndentStyle indentStyle; - public override IndentStyle IndentStyle { - get { - return indentStyle; - } - set { - if (value != this.indentStyle) { - this.indentStyle = value; - PropertyService.Set ("IndentStyle", value); - OnChanged (EventArgs.Empty); - } - } - } - - EditorFontType editorFontType; - public EditorFontType EditorFontType { - get { - return editorFontType; - } - set { - if (value != this.editorFontType) { - this.editorFontType = value; - PropertyService.Set ("EditorFontType", value); - OnChanged (EventArgs.Empty); - } - } - } - - bool enableHighlightUsages; - public bool EnableHighlightUsages { - get { - return enableHighlightUsages; - } - set { - if (value != this.enableHighlightUsages) { - this.enableHighlightUsages = value; - PropertyService.Set ("EnableHighlightUsages", value); - OnChanged (EventArgs.Empty); - } - } - } - - LineEndingConversion lineEndingConversion; - public LineEndingConversion LineEndingConversion { - get { - return lineEndingConversion; - } - set { - if (value != this.lineEndingConversion) { - this.lineEndingConversion = value; - PropertyService.Set ("LineEndingConversion", value); - OnChanged (EventArgs.Empty); - } - } - } - - - #endregion - - bool useViModes = false; - public bool UseViModes { - get { - return useViModes; - } - set { - if (useViModes == value) - return; - useViModes = value; - PropertyService.Set ("UseViModes", value); - OnChanged (EventArgs.Empty); - } - } - - bool onTheFlyFormatting = false; - public bool OnTheFlyFormatting { - get { - return onTheFlyFormatting; - } - set { - if (onTheFlyFormatting == value) - return; - onTheFlyFormatting = value; - PropertyService.Set ("OnTheFlyFormatting", value); - OnChanged (EventArgs.Empty); - } - } - - #region old options - string defaultEolMarker; - public override string DefaultEolMarker { - get { return defaultEolMarker; } - } - - WordNavigationStyle wordNavigationStyle = Platform.IsWindows - ? WordNavigationStyle.Windows - : WordNavigationStyle.Unix; - - [Obsolete("Use WordNavigationStyle")] - public ControlLeftRightMode ControlLeftRightMode { - get { - return WordNavigationStyle == WordNavigationStyle.Unix - ? ControlLeftRightMode.MonoDevelop - : ControlLeftRightMode.SharpDevelop; - } - set { - switch (value) { - case ControlLeftRightMode.Emacs: - case ControlLeftRightMode.MonoDevelop: - WordNavigationStyle = WordNavigationStyle.Unix; - return; - default: - WordNavigationStyle = WordNavigationStyle.Windows; - return; - } - } - } - - public WordNavigationStyle WordNavigationStyle { - get { - return wordNavigationStyle; - } - set { - if (wordNavigationStyle != value) { - wordNavigationStyle = value; - PropertyService.Set ("WordNavigationStyle", value); - SetWordFindStrategy (); - OnChanged (EventArgs.Empty); - } - } - } - - IWordFindStrategy wordFindStrategy = null; - public override IWordFindStrategy WordFindStrategy { - get { - if (wordFindStrategy == null) - SetWordFindStrategy (); - return this.wordFindStrategy; - } - set { - throw new System.NotImplementedException (); - } - } - - void SetWordFindStrategy () - { - if (useViModes) { - wordFindStrategy = new Mono.TextEditor.Vi.ViWordFindStrategy (); - return; - } - - switch (WordNavigationStyle) { - case WordNavigationStyle.Windows: - wordFindStrategy = new SharpDevelopWordFindStrategy (); - break; - default: - wordFindStrategy = new EmacsWordFindStrategy (); - break; - } - } - - public override bool AllowTabsAfterNonTabs { - set { - if (value != AllowTabsAfterNonTabs) { - PropertyService.Set ("AllowTabsAfterNonTabs", value); - base.AllowTabsAfterNonTabs = value; - } - } - } - - public override bool TabsToSpaces { - set { - PropertyService.Set ("TabsToSpaces", value); - base.TabsToSpaces = value; - } - } - - public override int IndentationSize { - set { - PropertyService.Set ("TabIndent", value); - base.IndentationSize = value; - } - } - - public override int TabSize { - get { - return IndentationSize; - } - set { - IndentationSize = value; - } - } - - public override bool RemoveTrailingWhitespaces { - set { - PropertyService.Set ("RemoveTrailingWhitespaces", value); - base.RemoveTrailingWhitespaces = value; - } - } - - - public override bool ShowLineNumberMargin { - set { - PropertyService.Set ("ShowLineNumberMargin", value); - base.ShowLineNumberMargin = value; - } - } - - public override bool ShowFoldMargin { - set { - PropertyService.Set ("ShowFoldMargin", value); - base.ShowFoldMargin = value; - } - } - - public override bool HighlightCaretLine { - set { - PropertyService.Set ("HighlightCaretLine", value); - base.HighlightCaretLine = value; - } - } - - public override bool EnableSyntaxHighlighting { - get { - return true; - } - set { - // nothing - } - } - - public override bool HighlightMatchingBracket { - set { - PropertyService.Set ("HighlightMatchingBracket", value); - base.HighlightMatchingBracket = value; - } - } - - public override int RulerColumn { - set { - PropertyService.Set ("RulerColumn", value); - base.RulerColumn = value; - } - } - - public override bool ShowRuler { - set { - PropertyService.Set ("ShowRuler", value); - base.ShowRuler = value; - } - } - - public override bool EnableAnimations { - set { - PropertyService.Set ("EnableAnimations", value); - base.EnableAnimations = value; - } - } - - public override bool DrawIndentationMarkers { - set { - PropertyService.Set ("DrawIndentationMarkers", value); - base.DrawIndentationMarkers = value; - } - } - - public override ShowWhitespaces ShowWhitespaces { - set { - PropertyService.Set ("ShowWhitespaces", value); - base.ShowWhitespaces = value; - } - } - - public override IncludeWhitespaces IncludeWhitespaces { - set { - PropertyService.Set ("IncludeWhitespaces", value); - base.IncludeWhitespaces = value; - } - } - - public override bool WrapLines { - set { - PropertyService.Set ("WrapLines", value); - base.WrapLines = value; - } - } - - public override bool EnableQuickDiff { - set { - PropertyService.Set ("EnableQuickDiff", value); - base.EnableQuickDiff = value; - } - } - - public override string FontName { - get { - return FontService.FilterFontName (FontService.GetUnderlyingFontName ("Editor")); - } - set { - throw new InvalidOperationException ("Set font through font service"); - } - } - - public override string GutterFontName { - get { - return FontService.FilterFontName (FontService.GetUnderlyingFontName ("Editor")); - } - set { - throw new InvalidOperationException ("Set font through font service"); - } - } - - public override string ColorScheme { - set { - string newColorScheme = !String.IsNullOrEmpty (value) ? value : "Default"; - PropertyService.Set ("ColorScheme", newColorScheme); - base.ColorScheme = newColorScheme; - } - } - - public override bool GenerateFormattingUndoStep { - set { - PropertyService.Set ("GenerateFormattingUndoStep", value); - base.GenerateFormattingUndoStep = value; - } - } - - #endregion - } -} diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorPrintOperation.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorPrintOperation.cs index 2aeda98637..69f79fce32 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorPrintOperation.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorPrintOperation.cs @@ -28,6 +28,7 @@ using Gtk; using Mono.TextEditor; using System.Text; using MonoDevelop.Core; +using MonoDevelop.Ide.Editor; namespace MonoDevelop.SourceEditor { @@ -284,7 +285,15 @@ namespace MonoDevelop.SourceEditor private SourceEditorPrintSettings () { - Font = DefaultSourceEditorOptions.Instance.Font; + try { + Font = Pango.FontDescription.FromString (DefaultSourceEditorOptions.Instance.FontName); + } catch { + Console.WriteLine ("Could not load font: {0}", DefaultSourceEditorOptions.Instance.FontName); + } + if (Font == null || String.IsNullOrEmpty (Font.Family)) + Font = Pango.FontDescription.FromString (TextEditorOptions.DEFAULT_FONT); + //if (Font != null) + // Font.Size = (int)(Font.Size * DefaultSourceEditorOptions.Instance.Zoom); TabSize = DefaultSourceEditorOptions.Instance.TabSize; HeaderFormat = "%F"; FooterFormat = GettextCatalog.GetString ("Page %N of %Q"); diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs index 305bced3be..ec7e3fd5ad 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorView.cs @@ -55,13 +55,18 @@ using System.Text; using Mono.Addins; using MonoDevelop.Components; using Mono.TextEditor.Utils; +using MonoDevelop.Ide.Editor; +using MonoDevelop.SourceEditor.Wrappers; +using MonoDevelop.Ide.Editor.Extension; +using MonoDevelop.Ide.Editor.Highlighting; namespace MonoDevelop.SourceEditor { - public class SourceEditorView : AbstractViewContent, IExtensibleTextEditor, IBookmarkBuffer, IClipboardHandler, - ICompletionWidget, ISplittable, IFoldable, IToolboxDynamicProvider, IEncodedTextContent, - ICustomFilteringToolboxConsumer, IZoomable, ITextEditorResolver, Mono.TextEditor.ITextEditorDataProvider, - ICodeTemplateHandler, ICodeTemplateContextProvider, ISupportsProjectReload, IPrintable + partial class SourceEditorView : AbstractViewContent, IBookmarkBuffer, IClipboardHandler, ITextFile, + ICompletionWidget, ISplittable, IFoldable, IToolboxDynamicProvider, + ICustomFilteringToolboxConsumer, IZoomable, ITextEditorResolver, ITextEditorDataProvider, + ICodeTemplateHandler, ICodeTemplateContextProvider, ISupportsProjectReload, IPrintable, + ITextEditorImpl, IEditorActionHost, ITextMarkerFactory, IUndoHandler { readonly SourceEditorWidget widget; bool isDisposed = false; @@ -79,10 +84,13 @@ namespace MonoDevelop.SourceEditor bool writeAllowed; bool writeAccessChecked; - public Mono.TextEditor.TextDocument Document { + public TextDocument Document { get { return widget.TextEditor.Document; } + set { + widget.TextEditor.Document = value; + } } public DateTime LastSaveTimeUtc { @@ -93,7 +101,8 @@ namespace MonoDevelop.SourceEditor lastSaveTimeUtc = value; } } - public ExtensibleTextEditor TextEditor { + + internal ExtensibleTextEditor TextEditor { get { return widget.TextEditor; } @@ -105,7 +114,7 @@ namespace MonoDevelop.SourceEditor } } - public override Gtk.Widget Control { + public override Widget Control { get { return widget != null ? widget.Vbox : null; } @@ -116,42 +125,12 @@ namespace MonoDevelop.SourceEditor return Document.LineCount; } } - - public override Project Project { - get { - return base.Project; - } - set { - if (value != base.Project) - ((StyledSourceEditorOptions)SourceEditorWidget.TextEditor.Options).UpdateStyleParent (value, loadedMimeType); - base.Project = value; - } - } public override string TabPageLabel { get { return GettextCatalog.GetString ("Source"); } } - uint autoSaveTimer = 0; - void InformAutoSave () - { - RemoveAutoSaveTimer (); - autoSaveTimer = GLib.Timeout.Add (500, delegate { - AutoSave.InformAutoSaveThread (Document); - autoSaveTimer = 0; - return false; - }); - } - - void RemoveAutoSaveTimer () - { - if (autoSaveTimer == 0) - return; - GLib.Source.Remove (autoSaveTimer); - autoSaveTimer = 0; - } - bool wasEdited = false; uint removeMarkerTimeout; Queue<MessageBubbleTextMarker> markersToRemove = new Queue<MessageBubbleTextMarker> (); @@ -177,19 +156,27 @@ namespace MonoDevelop.SourceEditor }); } - public SourceEditorView () + public SourceEditorView (IReadonlyTextDocument document = null) { Counters.LoadedEditors++; widget = new SourceEditorWidget (this); - widget.TextEditor.Document.SyntaxModeChanged += HandleSyntaxModeChanged; + if (document != null) { + var textDocument = document as TextDocument; + if (textDocument != null) { + widget.TextEditor.Document = textDocument; + } else { + widget.TextEditor.Document.Text = document.Text; + } + } + widget.TextEditor.Document.TextReplaced += HandleTextReplaced; widget.TextEditor.Document.LineChanged += HandleLineChanged; + widget.TextEditor.Document.LineInserted += HandleLineChanged; + widget.TextEditor.Document.LineRemoved += HandleLineChanged; widget.TextEditor.Document.BeginUndo += HandleBeginUndo; widget.TextEditor.Document.EndUndo += HandleEndUndo; - widget.TextEditor.Document.Undone += HandleUndone; - widget.TextEditor.Document.Redone += HandleUndone; widget.TextEditor.Document.TextReplacing += OnTextReplacing; widget.TextEditor.Document.TextReplaced += OnTextReplaced; @@ -201,13 +188,13 @@ namespace MonoDevelop.SourceEditor widget.TextEditor.Caret.PositionChanged += HandlePositionChanged; widget.TextEditor.IconMargin.ButtonPressed += OnIconButtonPress; - + debugStackLineMarker = new DebugStackLineTextMarker (widget.TextEditor); currentDebugLineMarker = new CurrentDebugLineTextMarker (widget.TextEditor); - this.WorkbenchWindowChanged += HandleWorkbenchWindowChanged; - this.ContentNameChanged += delegate { - this.Document.FileName = this.ContentName; + WorkbenchWindowChanged += HandleWorkbenchWindowChanged; + ContentNameChanged += delegate { + Document.FileName = ContentName; if (String.IsNullOrEmpty (ContentName) || !File.Exists (ContentName)) return; @@ -240,10 +227,14 @@ namespace MonoDevelop.SourceEditor widget.TextEditor.Options.Changed += HandleWidgetTextEditorOptionsChanged; IdeApp.Preferences.DefaultHideMessageBubblesChanged += HandleIdeAppPreferencesDefaultHideMessageBubblesChanged; Document.AddAnnotation (this); + if (document != null) { + Document.MimeType = document.MimeType; + Document.FileName = document.FileName; + } FileRegistry.Add (this); } - void HandleLineChanged (object sender, LineEventArgs e) + void HandleLineChanged (object sender, Mono.TextEditor.LineEventArgs e) { UpdateBreakpoints (); UpdateWidgetPositions (); @@ -255,6 +246,9 @@ namespace MonoDevelop.SourceEditor marker.GetLineHeight (widget.TextEditor); } } + var handler = LineChanged; + if (handler != null) + handler (this, new MonoDevelop.Ide.Editor.LineEventArgs (new DocumentLineWrapper (e.Line))); } void HandleTextReplaced (object sender, DocumentChangeEventArgs args) @@ -265,9 +259,6 @@ namespace MonoDevelop.SourceEditor if (widget.TextEditor.Document.IsInAtomicUndo) { wasEdited = true; } - else { - InformAutoSave (); - } } int startIndex = args.Offset; @@ -279,37 +270,23 @@ namespace MonoDevelop.SourceEditor ResetRemoveMarker (); } - void HandleSyntaxModeChanged (object sender, SyntaxModeChangeEventArgs e) - { - var oldProvider = e.OldMode as IQuickTaskProvider; - if (oldProvider != null) - widget.RemoveQuickTaskProvider (oldProvider); - var newProvider = e.NewMode as IQuickTaskProvider; - if (newProvider != null) - widget.AddQuickTaskProvider (newProvider); - } - - void HandleEndUndo (object sender, TextDocument.UndoOperationEventArgs e) { - if (wasEdited) - InformAutoSave (); + OnEndUndo (EventArgs.Empty); } void HandleBeginUndo (object sender, EventArgs e) { wasEdited = false; + OnBeginUndo (EventArgs.Empty); } - void HandleUndone (object sender, TextDocument.UndoOperationEventArgs e) - { - AutoSave.InformAutoSaveThread (Document); - } void HandlePositionChanged (object sender, DocumentLocationEventArgs e) { OnCaretPositionSet (EventArgs.Empty); FireCompletionContextChanged (); + OnCaretPositionChanged (EventArgs.Empty); } void HandleFileExtensionRemoved (object sender, FileExtensionEventArgs args) @@ -326,7 +303,7 @@ namespace MonoDevelop.SourceEditor AddFileExtension (args.Extension); } - Dictionary<TopLevelWidgetExtension,Gtk.Widget> widgetExtensions = new Dictionary<TopLevelWidgetExtension, Widget> (); + Dictionary<TopLevelWidgetExtension,Widget> widgetExtensions = new Dictionary<TopLevelWidgetExtension, Widget> (); Dictionary<FileExtension,Tuple<TextLineMarker,DocumentLine>> markerExtensions = new Dictionary<FileExtension, Tuple<TextLineMarker,DocumentLine>> (); void LoadExtensions () @@ -360,22 +337,22 @@ namespace MonoDevelop.SourceEditor if (line == null) return; - var marker = lineExt.CreateMarker (); + var marker = (TextLineMarker)lineExt.CreateMarker (); widget.TextEditor.Document.AddMarker (line, marker); widget.TextEditor.QueueDraw (); - markerExtensions [extension] = new Tuple<TextLineMarker,DocumentLine> (marker, line); + markerExtensions [extension] = new Tuple<TextLineMarker, DocumentLine> (marker, line); } } void HandleScrollToViewRequested (object sender, EventArgs e) { var widgetExtension = (TopLevelWidgetExtension)sender; - Gtk.Widget w; + Widget w; if (widgetExtensions.TryGetValue (widgetExtension, out w)) { int x, y; widget.TextEditor.TextArea.GetTopLevelWidgetPosition (w, out x, out y); var size = w.SizeRequest (); - Gtk.Application.Invoke (delegate { + Application.Invoke (delegate { widget.TextEditor.ScrollTo (new Gdk.Rectangle (x, y, size.Width, size.Height)); }); } @@ -385,7 +362,7 @@ namespace MonoDevelop.SourceEditor { if (extension is TopLevelWidgetExtension) { var widgetExtension = (TopLevelWidgetExtension)extension; - Gtk.Widget w; + Widget w; if (!widgetExtensions.TryGetValue (widgetExtension, out w)) return; widgetExtensions.Remove (widgetExtension); @@ -417,7 +394,7 @@ namespace MonoDevelop.SourceEditor } } - bool CalcWidgetPosition (TopLevelWidgetExtension widgetExtension, Gtk.Widget w, out int x, out int y) + bool CalcWidgetPosition (TopLevelWidgetExtension widgetExtension, Widget w, out int x, out int y) { DocumentLine line = widget.TextEditor.Document.GetLine (widgetExtension.Line); if (line == null) { @@ -426,10 +403,10 @@ namespace MonoDevelop.SourceEditor } int lw, lh; - var wrapper = widget.TextEditor.TextViewMargin.GetLayout (line); - wrapper.Layout.GetPixelSize (out lw, out lh); - if (wrapper.IsUncached) - wrapper.Dispose (); + var tmpWrapper = widget.TextEditor.TextViewMargin.GetLayout (line); + tmpWrapper.Layout.GetPixelSize (out lw, out lh); + if (tmpWrapper.IsUncached) + tmpWrapper.Dispose (); lh = (int) TextEditor.TextViewMargin.GetLineHeight (widgetExtension.Line); x = (int)widget.TextEditor.TextViewMargin.XOffset + lw + 4; y = (int)widget.TextEditor.LineToY (widgetExtension.Line); @@ -487,9 +464,8 @@ namespace MonoDevelop.SourceEditor void HandleWorkbenchWindowChanged (object sender, EventArgs e) { if (WorkbenchWindow != null) { - widget.TextEditor.ExtensionContext = WorkbenchWindow.ExtensionContext; WorkbenchWindow.ActiveViewContentChanged += HandleActiveViewContentChanged; - this.WorkbenchWindowChanged -= HandleWorkbenchWindowChanged; + WorkbenchWindowChanged -= HandleWorkbenchWindowChanged; } } @@ -509,7 +485,7 @@ namespace MonoDevelop.SourceEditor { var task = e.Tasks != null ? e.Tasks.FirstOrDefault () : null; var doc = Document; - if (task == null || doc == null || task.FileName != doc.FileName || this.TextEditor == null) + if (task == null || doc == null || task.FileName != doc.FileName || TextEditor == null) return; var lineSegment = doc.GetLine (task.Line); if (lineSegment == null) @@ -518,7 +494,7 @@ namespace MonoDevelop.SourceEditor if (marker == null) return; - marker.SetPrimaryError (task.Description); + marker.SetPrimaryError (task); if (TextEditor != null && TextEditor.IsComposited) { /*if (messageBubbleHighlightPopupWindow != null) @@ -534,7 +510,7 @@ namespace MonoDevelop.SourceEditor void HandleIdeAppPreferencesDefaultHideMessageBubblesChanged (object sender, PropertyChangedEventArgs e) { currentErrorMarkers.ForEach (marker => marker.IsVisible = !IdeApp.Preferences.DefaultHideMessageBubbles); - this.TextEditor.QueueDraw (); + TextEditor.QueueDraw (); } void HandleIdeAppPreferencesShowMessageBubblesChanged (object sender, PropertyChangedEventArgs e) @@ -544,7 +520,7 @@ namespace MonoDevelop.SourceEditor void HandleErrorListPadTaskToggled (object sender, TaskEventArgs e) { - this.TextEditor.QueueDraw (); + TextEditor.QueueDraw (); } MessageBubbleCache messageBubbleCache; @@ -593,7 +569,7 @@ namespace MonoDevelop.SourceEditor //NRE and bring down MD /*if (messageBubbleHighlightPopupWindow != null) messageBubbleHighlightPopupWindow.Destroy ();*/ - + currentErrorMarkers.ForEach (em => { widget.Document.RemoveMarker (em); em.Dispose (); @@ -610,9 +586,9 @@ namespace MonoDevelop.SourceEditor return text; } - public override void Save (string fileName) + public override void Save (FileSaveInformation fileSaveInformation) { - Save (fileName, this.encoding); + Save (fileSaveInformation.FileName, fileSaveInformation.Encoding ?? encoding); } public void Save (string fileName, Encoding encoding) @@ -620,9 +596,6 @@ namespace MonoDevelop.SourceEditor if (widget.HasMessageBar) return; - if (!string.IsNullOrEmpty (ContentName)) - AutoSave.RemoveAutoSaveFile (ContentName); - if (ContentName != fileName) { FileService.RequestFileEdit ((FilePath) fileName); writeAllowed = true; @@ -630,7 +603,7 @@ namespace MonoDevelop.SourceEditor } if (warnOverwrite) { - if (fileName == ContentName) { + if (string.Equals (fileName, ContentName, FilePath.PathComparison)) { string question = GettextCatalog.GetString ( "This file {0} has been changed outside of {1}. Are you sure you want to overwrite the file?", fileName, BrandingService.ApplicationName @@ -701,7 +674,7 @@ namespace MonoDevelop.SourceEditor // writeBom =!Mono.TextEditor.Utils.TextFileUtility.IsASCII (writeText); } } - Mono.TextEditor.Utils.TextFileUtility.WriteText (fileName, writeText, writeEncoding, writeBom); + TextFileUtility.WriteText (fileName, writeText, writeEncoding, writeBom); } catch (InvalidEncodingException) { var result = MessageService.AskQuestion (GettextCatalog.GetString ("Can't save file with current codepage."), GettextCatalog.GetString ("Some unicode characters in this file could not be saved with the current encoding.\nDo you want to resave this file as Unicode ?\nYou can choose another encoding in the 'save as' dialog."), @@ -709,9 +682,9 @@ namespace MonoDevelop.SourceEditor AlertButton.Cancel, new AlertButton (GettextCatalog.GetString ("Save as Unicode"))); if (result != AlertButton.Cancel) { - this.hadBom = true; + hadBom = true; this.encoding = Encoding.UTF8; - Mono.TextEditor.Utils.TextFileUtility.WriteText (fileName, Document.Text, encoding, hadBom); + TextFileUtility.WriteText (fileName, Document.Text, encoding, hadBom); } else { return; } @@ -737,17 +710,12 @@ namespace MonoDevelop.SourceEditor ContentName = fileName; UpdateMimeType (fileName); Document.SetNotDirtyState (); - this.IsDirty = false; - } - - public override void DiscardChanges () - { - if (!string.IsNullOrEmpty (ContentName)) - AutoSave.RemoveAutoSaveFile (ContentName); + IsDirty = false; } - public override void LoadNew (Stream content, string mimeType) + public void InformLoadComplete () { + /* Document.MimeType = mimeType; string text = null; if (content != null) { @@ -757,52 +725,18 @@ namespace MonoDevelop.SourceEditor } this.CreateDocumentParsedHandler (); RunFirstTimeFoldUpdate (text); + */ Document.InformLoadComplete (); } - public override void Load (string fileName) + public override void LoadNew (Stream content, string mimeType) { - Load (fileName, null); + throw new NotSupportedException ("Moved to TextEditorViewContent.LoadNew."); } - - void RunFirstTimeFoldUpdate (string text) + + public override void Load (FileOpenInformation fileOpenInformation) { - if (string.IsNullOrEmpty (text)) - return; - ParsedDocument parsedDocument = null; - - var foldingParser = TypeSystemService.GetFoldingParser (Document.MimeType); - if (foldingParser != null) { - parsedDocument = foldingParser.Parse (Document.FileName, text); - } else { - var normalParser = TypeSystemService.GetParser (Document.MimeType); - if (normalParser != null) { - using (var sr = new StringReader (text)) - parsedDocument = normalParser.Parse (true, Document.FileName, sr, null); - } - } - if (parsedDocument != null) - widget.UpdateParsedDocument (parsedDocument); - } - - void CreateDocumentParsedHandler () - { - this.WorkbenchWindowChanged += delegate { - if (WorkbenchWindow == null) - return; - WorkbenchWindow.DocumentChanged += delegate { - if (WorkbenchWindow.Document == null) - return; - foreach (var provider in WorkbenchWindow.Document.GetContents<IQuickTaskProvider> ()) { - widget.AddQuickTaskProvider (provider); - } - foreach (var provider in WorkbenchWindow.Document.GetContents<IUsageProvider> ()) { - widget.AddUsageTaskProvider (provider); - } - ownerDocument = WorkbenchWindow.Document; - ownerDocument.DocumentParsed += HandleDocumentParsed; - }; - }; + Load (fileOpenInformation.FileName, fileOpenInformation.Encoding); } MonoDevelop.Ide.Gui.Document ownerDocument; @@ -813,11 +747,6 @@ namespace MonoDevelop.SourceEditor protected virtual void HandleDocumentParsed (object sender, EventArgs e) { widget.UpdateParsedDocument (ownerDocument.ParsedDocument); - } - - void IEncodedTextContent.Load (string fileName, Encoding loadEncoding) - { - Load (fileName, loadEncoding); } protected virtual string ProcessLoadText (string text) @@ -827,9 +756,8 @@ namespace MonoDevelop.SourceEditor public void Load (string fileName, Encoding loadEncoding, bool reload = false) { - // Handle the "reload" case. - if (ContentName == fileName) - AutoSave.RemoveAutoSaveFile (fileName); + widget.TextEditor.Document.TextReplaced -= OnTextReplaced; + if (warnOverwrite) { warnOverwrite = false; widget.RemoveMessageBar (); @@ -841,7 +769,7 @@ namespace MonoDevelop.SourceEditor bool didLoadCleanly; if (AutoSave.AutoSaveExists (fileName)) { widget.ShowAutoSaveWarning (fileName); - this.encoding = loadEncoding; + encoding = loadEncoding; didLoadCleanly = false; } else { @@ -864,22 +792,22 @@ namespace MonoDevelop.SourceEditor didLoadCleanly = true; } // TODO: Would be much easier if the view would be created after the containers. - CreateDocumentParsedHandler (); ContentName = fileName; lastSaveTimeUtc = File.GetLastWriteTimeUtc (ContentName); - RunFirstTimeFoldUpdate (text); widget.TextEditor.Caret.Offset = 0; UpdateExecutionLocation (); UpdateBreakpoints (); UpdatePinnedWatches (); LoadExtensions (); - this.IsDirty = !didLoadCleanly; + IsDirty = !didLoadCleanly; UpdateTasks (null, null); widget.TextEditor.TextArea.SizeAllocated += HandleTextEditorVAdjustmentChanged; if (didLoadCleanly) { - Document.InformLoadComplete (); + InformLoadComplete (); widget.EnsureCorrectEolMarker (fileName); } + + widget.TextEditor.Document.TextReplaced += OnTextReplaced; } void HandleTextEditorVAdjustmentChanged (object sender, EventArgs e) @@ -890,8 +818,8 @@ namespace MonoDevelop.SourceEditor internal void LoadSettings () { - FileSettingsStore.Settings settings; - if (widget == null || string.IsNullOrEmpty (ContentName) || !FileSettingsStore.TryGetValue (ContentName, out settings)) + MonoDevelop.Ide.Editor.FileSettingsStore.Settings settings; + if (widget == null || string.IsNullOrEmpty (ContentName) || !MonoDevelop.Ide.Editor.FileSettingsStore.TryGetValue (ContentName, out settings)) return; widget.TextEditor.Caret.Offset = settings.CaretOffset; @@ -913,7 +841,7 @@ namespace MonoDevelop.SourceEditor // } if (string.IsNullOrEmpty (ContentName)) return; - FileSettingsStore.Store (ContentName, new FileSettingsStore.Settings () { + MonoDevelop.Ide.Editor.FileSettingsStore.Store (ContentName, new MonoDevelop.Ide.Editor.FileSettingsStore.Settings { CaretOffset = widget.TextEditor.Caret.Offset, vAdjustment = widget.TextEditor.VAdjustment.Value, hAdjustment = widget.TextEditor.HAdjustment.Value//, @@ -926,7 +854,7 @@ namespace MonoDevelop.SourceEditor Encoding encoding; bool hadBom = false; - internal void ReplaceContent (string fileName, string content, Encoding encoding) + internal void ReplaceContent (string fileName, string content, Encoding enc) { if (warnOverwrite) { warnOverwrite = false; @@ -939,18 +867,16 @@ namespace MonoDevelop.SourceEditor Document.Replace (0, Document.TextLength, content); Document.DiffTracker.Reset (); inLoad = false; - this.encoding = encoding; + encoding = enc; ContentName = fileName; - RunFirstTimeFoldUpdate (content); - CreateDocumentParsedHandler (); UpdateExecutionLocation (); UpdateBreakpoints (); UpdatePinnedWatches (); LoadExtensions (); IsDirty = false; - Document.InformLoadComplete (); + InformLoadComplete (); } - + void UpdateMimeType (string fileName) { // Look for a mime type for which there is a syntax mode @@ -966,7 +892,6 @@ namespace MonoDevelop.SourceEditor } } } - ((StyledSourceEditorOptions)SourceEditorWidget.TextEditor.Options).UpdateStyleParent (Project, loadedMimeType); } } @@ -976,13 +901,15 @@ namespace MonoDevelop.SourceEditor public override void Dispose () { + if (isDisposed) + return; + isDisposed = true; + ClearExtensions (); FileRegistry.Remove (this); - RemoveAutoSaveTimer (); - + StoreSettings (); - this.isDisposed = true; Counters.LoadedEditors--; /* if (messageBubbleHighlightPopupWindow != null) @@ -996,13 +923,10 @@ namespace MonoDevelop.SourceEditor ClipbardRingUpdated -= UpdateClipboardRing; - widget.TextEditor.Document.SyntaxModeChanged -= HandleSyntaxModeChanged; widget.TextEditor.Document.TextReplaced -= HandleTextReplaced; widget.TextEditor.Document.LineChanged -= HandleLineChanged; widget.TextEditor.Document.BeginUndo -= HandleBeginUndo; widget.TextEditor.Document.EndUndo -= HandleEndUndo; - widget.TextEditor.Document.Undone -= HandleUndone; - widget.TextEditor.Document.Redone -= HandleUndone; widget.TextEditor.Caret.PositionChanged -= HandlePositionChanged; widget.TextEditor.IconMargin.ButtonPressed -= OnIconButtonPress; widget.TextEditor.Document.TextReplacing -= OnTextReplacing; @@ -1043,13 +967,6 @@ namespace MonoDevelop.SourceEditor RemoveMarkerQueue (); } - - public Ambience GetAmbience () - { - string file = this.IsUntitled ? this.UntitledName : this.ContentName; - return AmbienceService.GetAmbienceForFile (file); - } - bool CheckReadOnly (int line) { @@ -1069,9 +986,9 @@ namespace MonoDevelop.SourceEditor void OnTextReplaced (object s, DocumentChangeEventArgs a) { - this.IsDirty = Document.IsDirty; + IsDirty = Document.IsDirty; - DocumentLocation location = Document.OffsetToLocation (a.Offset); + var location = Document.OffsetToLocation (a.Offset); int i = 0, lines = 0; while (i != -1 && i < oldReplaceText.Length) { @@ -1198,10 +1115,10 @@ namespace MonoDevelop.SourceEditor if (w.OffsetX < 0) { w.OffsetY = (int)widget.TextEditor.LineToY (w.Line); int lw, lh; - var wrapper = widget.TextEditor.TextViewMargin.GetLayout (line); - wrapper.Layout.GetPixelSize (out lw, out lh); - if (wrapper.IsUncached) - wrapper.Dispose (); + var tmpWrapper = widget.TextEditor.TextViewMargin.GetLayout (line); + tmpWrapper.Layout.GetPixelSize (out lw, out lh); + if (tmpWrapper.IsUncached) + tmpWrapper.Dispose (); w.OffsetX = (int)widget.TextEditor.TextViewMargin.XOffset + lw + 4; } wi.Widget = new PinnedWatchWidget (widget.TextEditor, w); @@ -1405,7 +1322,7 @@ namespace MonoDevelop.SourceEditor void OnIconButtonPress (object s, MarginMouseEventArgs args) { - if (args.LineNumber < DocumentLocation.MinLine) + if (args.LineNumber < Mono.TextEditor.DocumentLocation.MinLine) return; if (args.TriggersContextMenu ()) { @@ -1420,51 +1337,23 @@ namespace MonoDevelop.SourceEditor WorkbenchWindow.ExtensionContext ?? AddinManager.AddinEngine, "/MonoDevelop/SourceEditor2/IconContextMenu/Editor"); } else if (args.Button == 1) { - if (!string.IsNullOrEmpty (this.Document.FileName)) { + if (!string.IsNullOrEmpty (Document.FileName)) { if (args.LineSegment != null) { int column = TextEditor.Caret.Line == args.LineNumber ? TextEditor.Caret.Column : 1; lock (breakpoints) - breakpoints.Toggle (this.Document.FileName, args.LineNumber, column); + breakpoints.Toggle (Document.FileName, args.LineNumber, column); } } } } - - #region IExtensibleTextEditor - public ITextEditorExtension Extension { - get; - set; - } - - ITextEditorExtension IExtensibleTextEditor.AttachExtension (ITextEditorExtension extension) - { - Extension = extension; - this.widget.TextEditor.Extension = extension; - return this.widget; - } - -// protected override void OnMoveCursor (MovementStep step, int count, bool extend_selection) -// { -// base.OnMoveCursor (step, count, extend_selection); -// if (extension != null) -// extension.CursorPositionChanged (); -// } - -// protected override bool OnKeyPressEvent (Gdk.EventKey evnt) -// { -// if (extension != null) -// return extension.KeyPress (evnt.Key, evnt.State); -// return this.KeyPress (evnt.Key, evnt.State); -// } - #endregion - + #region IEditableTextBuffer public bool EnableUndo { get { if (widget == null) return false; - return /*this.TextEditor.PreeditOffset < 0 &&*/ this.Document.CanUndo && widget.EditorHasFocus; + return /*this.TextEditor.PreeditOffset < 0 &&*/ Document.CanUndo && widget.EditorHasFocus; } } @@ -1482,14 +1371,14 @@ namespace MonoDevelop.SourceEditor }*/ if (MiscActions.CancelPreEditMode (TextEditor.GetTextEditorData ())) return; - MiscActions.Undo (this.TextEditor.GetTextEditorData ()); + MiscActions.Undo (TextEditor.GetTextEditorData ()); } public bool EnableRedo { get { if (widget == null) return false; - return /*this.TextEditor.PreeditOffset < 0 && */ this.Document.CanRedo && widget.EditorHasFocus; + return /*this.TextEditor.PreeditOffset < 0 && */ Document.CanRedo && widget.EditorHasFocus; } } @@ -1526,7 +1415,7 @@ namespace MonoDevelop.SourceEditor { if (MiscActions.CancelPreEditMode (TextEditor.GetTextEditorData ())) return; - MiscActions.Redo (this.TextEditor.GetTextEditorData ()); + MiscActions.Redo (TextEditor.GetTextEditorData ()); } public IDisposable OpenUndoGroup () @@ -1553,8 +1442,7 @@ namespace MonoDevelop.SourceEditor } public event EventHandler CaretPositionSet; - public event EventHandler<TextChangedEventArgs> TextChanged; - + public bool HasInputFocus { get { return TextEditor.HasFocus; } } @@ -1565,7 +1453,6 @@ namespace MonoDevelop.SourceEditor } #endregion - #region ITextBuffer public int CursorPosition { get { return TextEditor.Caret.Offset; @@ -1574,56 +1461,28 @@ namespace MonoDevelop.SourceEditor TextEditor.Caret.Offset = value; } } - - public int SelectionStartPosition { - get { - if (!TextEditor.IsSomethingSelected) - return TextEditor.Caret.Offset; - return TextEditor.SelectionRange.Offset; - } - } - - public int SelectionEndPosition { - get { - if (!TextEditor.IsSomethingSelected) - return TextEditor.Caret.Offset; - return TextEditor.SelectionRange.EndOffset; - } - } - - public void Select (int startPosition, int endPosition) - { - TextEditor.SelectionRange = new TextSegment (startPosition, endPosition - startPosition); - TextEditor.ScrollToCaret (); - } - - public void ShowPosition (int position) - { - // TODO - } - #endregion #region ITextFile public FilePath Name { get { - return this.ContentName ?? this.UntitledName; + return ContentName ?? UntitledName; } } public string Text { get { - return this.widget.TextEditor.Document.Text; + return widget.TextEditor.Document.Text; } set { this.IsDirty = true; - TextDocument document = this.widget.TextEditor.Document; + var document = this.widget.TextEditor.Document; document.Replace (0, document.TextLength, value); } } public int Length { get { - return this.widget.TextEditor.Document.TextLength; + return widget.TextEditor.Document.TextLength; } } @@ -1647,17 +1506,17 @@ namespace MonoDevelop.SourceEditor public char GetCharAt (int position) { - return this.widget.TextEditor.Document.GetCharAt (position); + return widget.TextEditor.Document.GetCharAt (position); } public int GetPositionFromLineColumn (int line, int column) { - return this.widget.TextEditor.Document.LocationToOffset (new DocumentLocation (line, column)); + return widget.TextEditor.Document.LocationToOffset (new Mono.TextEditor.DocumentLocation (line, column)); } public void GetLineColumnFromPosition (int position, out int line, out int column) { - DocumentLocation location = this.widget.TextEditor.Document.OffsetToLocation (position); + var location = widget.TextEditor.Document.OffsetToLocation (position); line = location.Line; column = location.Column; } @@ -1666,25 +1525,25 @@ namespace MonoDevelop.SourceEditor #region IEditableTextFile public int InsertText (int position, string text) { - return this.widget.TextEditor.Insert (position, text); + return widget.TextEditor.Insert (position, text); } public void DeleteText (int position, int length) { - this.widget.TextEditor.Remove (position, length); + widget.TextEditor.Remove (position, length); } #endregion #region IBookmarkBuffer DocumentLine GetLine (int position) { - DocumentLocation location = Document.OffsetToLocation (position); + var location = Document.OffsetToLocation (position); return Document.GetLine (location.Line); } public void SetBookmarked (int position, bool mark) { - DocumentLine line = GetLine (position); + var line = GetLine (position); if (line != null && line.IsBookmarked != mark) { int lineNumber = widget.TextEditor.Document.OffsetToLineNumber (line.Offset); line.IsBookmarked = mark; @@ -1695,8 +1554,8 @@ namespace MonoDevelop.SourceEditor public bool IsBookmarked (int position) { - DocumentLine line = GetLine (position); - return line != null ? line.IsBookmarked : false; + var line = GetLine (position); + return line != null && line.IsBookmarked; } public void PrevBookmark () @@ -1794,7 +1653,7 @@ namespace MonoDevelop.SourceEditor get { if (TextEditor.IsSomethingSelected) { if (TextEditor.MainSelection.SelectionMode == Mono.TextEditor.SelectionMode.Block) - return System.Math.Abs (TextEditor.MainSelection.Anchor.Column - TextEditor.MainSelection.Lead.Column); + return Math.Abs (TextEditor.MainSelection.Anchor.Column - TextEditor.MainSelection.Lead.Column); return TextEditor.SelectionRange.Length; } return 0; @@ -1813,9 +1672,13 @@ namespace MonoDevelop.SourceEditor get { return TextEditor.Caret.Offset; } + set { + TextEditor.Caret.Offset = value; + TextEditor.ScrollToCaret (); + } } - public Gtk.Style GtkStyle { + public Style GtkStyle { get { return widget.Vbox.Style.Copy (); } @@ -1838,7 +1701,7 @@ namespace MonoDevelop.SourceEditor var loc = editor.Caret.Location; result.TriggerLine = loc.Line; result.TriggerLineOffset = loc.Column - 1; - var p = this.widget.TextEditor.LocationToPoint (loc); + var p = widget.TextEditor.LocationToPoint (loc); int tx, ty; editor.ParentWindow.GetOrigin (out tx, out ty); tx += editor.Allocation.X + p.X; @@ -1850,7 +1713,7 @@ namespace MonoDevelop.SourceEditor return result; } - public Gdk.Point DocumentToScreenLocation (DocumentLocation location) + public Gdk.Point DocumentToScreenLocation (Mono.TextEditor.DocumentLocation location) { var p = widget.TextEditor.LocationToPoint (location); int tx, ty; @@ -1874,21 +1737,25 @@ namespace MonoDevelop.SourceEditor return Document.GetTextBetween (min, max); } - public void SetCompletionText (CodeCompletionContext ctx, string partial_word, string complete_word) + public void SetCompletionText (CodeCompletionContext ctx, string partialWord, string completeWord) { - SetCompletionText (ctx, partial_word, complete_word, complete_word.Length); + if (ctx == null) + throw new ArgumentNullException ("ctx"); + if (completeWord == null) + throw new ArgumentNullException ("completeWord"); + SetCompletionText (ctx, partialWord, completeWord, completeWord.Length); } - public static void SetCompletionText (TextEditorData data, CodeCompletionContext ctx, string partial_word, string complete_word, int wordOffset) + public static void SetCompletionText (TextEditorData data, CodeCompletionContext ctx, string partialWord, string completeWord, int wordOffset) { if (data == null || data.Document == null) return; int triggerOffset = ctx.TriggerOffset; - int length = String.IsNullOrEmpty (partial_word) ? 0 : partial_word.Length; + int length = String.IsNullOrEmpty (partialWord) ? 0 : partialWord.Length; // for named arguments invoke(arg:<Expr>); - if (complete_word.EndsWith (":", StringComparison.Ordinal)) { + if (completeWord.EndsWith (":", StringComparison.Ordinal)) { if (data.GetCharAt (triggerOffset + length) == ':') length++; } @@ -1908,9 +1775,9 @@ namespace MonoDevelop.SourceEditor } // | in the completion text now marks the caret position - int idx = complete_word.IndexOf ('|'); + int idx = completeWord.IndexOf ('|'); if (idx >= 0) { - complete_word = complete_word.Remove (idx, 1); + completeWord = completeWord.Remove (idx, 1); } triggerOffset += data.EnsureCaretIsNotVirtual (); @@ -1925,11 +1792,11 @@ namespace MonoDevelop.SourceEditor if (lineSegment == null) continue; int offset = lineSegment.Offset + column; - data.Replace (offset, length, complete_word); + data.Replace (offset, length, completeWord); } - int minColumn = System.Math.Min (data.MainSelection.Anchor.Column, data.MainSelection.Lead.Column); + int minColumn = Math.Min (data.MainSelection.Anchor.Column, data.MainSelection.Lead.Column); data.MainSelection = data.MainSelection.WithRange ( - new DocumentLocation (data.Caret.Line == minLine ? maxLine : minLine, minColumn), + new Mono.TextEditor.DocumentLocation (data.Caret.Line == minLine ? maxLine : minLine, minColumn), data.Caret.Location ); @@ -1937,7 +1804,7 @@ namespace MonoDevelop.SourceEditor data.Caret.PreserveSelection = false; } } else { - data.Replace (triggerOffset, length, complete_word); + data.Replace (triggerOffset, length, completeWord); } data.Document.CommitLineUpdate (data.Caret.Line); @@ -1946,16 +1813,16 @@ namespace MonoDevelop.SourceEditor } - public void SetCompletionText (CodeCompletionContext ctx, string partial_word, string complete_word, int wordOffset) + public void SetCompletionText (CodeCompletionContext ctx, string partialWord, string completeWord, int wordOffset) { var data = GetTextEditorData (); if (data == null) return; using (var undo = data.OpenUndoGroup ()) { - SetCompletionText (data, ctx, partial_word, complete_word, wordOffset); + SetCompletionText (data, ctx, partialWord, completeWord, wordOffset); var formatter = CodeFormatterService.GetFormatter (data.MimeType); - if (formatter != null && complete_word.IndexOfAny (new [] {' ', '\t', '{', '}'}) > 0 && formatter.SupportsOnTheFlyFormatting) { - formatter.OnTheFlyFormat (WorkbenchWindow.Document, ctx.TriggerOffset, ctx.TriggerOffset + complete_word.Length); + if (formatter != null && completeWord.IndexOfAny (new [] {' ', '\t', '{', '}'}) > 0 && formatter.SupportsOnTheFlyFormatting) { + formatter.OnTheFlyFormat (WorkbenchWindow.Document, ctx.TriggerOffset, ctx.TriggerOffset + completeWord.Length); } } } @@ -1979,10 +1846,12 @@ namespace MonoDevelop.SourceEditor if (TextEditor.IsSomethingSelected) { expression = TextEditor.SelectedText; } else { - DomRegion region; + MonoDevelop.Ide.Editor.DocumentRegion region; var rr = TextEditor.GetLanguageItem (TextEditor.Caret.Offset, out region); - if (rr != null && !rr.IsError) - expression = TextEditor.GetTextBetween (region.Begin, region.End); + if (rr != null) + expression = TextEditor.GetTextBetween ( + region.BeginLine, region.BeginColumn, + region.EndLine, region.EndColumn); } DebuggingService.ShowExpressionEvaluator (expression); @@ -2051,18 +1920,18 @@ namespace MonoDevelop.SourceEditor { bool toggle = true; - foreach (FoldSegment segment in Document.FoldSegments) { - if (segment.FoldingType == FoldingType.TypeMember || segment.FoldingType == FoldingType.Comment) + foreach (var segment in Document.FoldSegments) { + if (segment.FoldingType == Mono.TextEditor.FoldingType.TypeMember || segment.FoldingType == Mono.TextEditor.FoldingType.Comment) if (segment.IsFolded) toggle = false; } - foreach (FoldSegment segment in Document.FoldSegments) { - if (segment.FoldingType == FoldingType.TypeDefinition) { + foreach (var segment in Document.FoldSegments) { + if (segment.FoldingType == Mono.TextEditor.FoldingType.TypeDefinition) { segment.IsFolded = false; } - if (segment.FoldingType == FoldingType.TypeMember || segment.FoldingType == FoldingType.Comment) + if (segment.FoldingType == Mono.TextEditor.FoldingType.TypeMember || segment.FoldingType == Mono.TextEditor.FoldingType.Comment) segment.IsFolded = toggle; } @@ -2148,7 +2017,7 @@ namespace MonoDevelop.SourceEditor item.Description += line; } item.Category = GettextCatalog.GetString ("Clipboard ring"); - item.Icon = DesktopService.GetIconForFile ("a.txt", Gtk.IconSize.Menu); + item.Icon = DesktopService.GetIconForFile ("a.txt", IconSize.Menu); item.Name = text.Length > 16 ? text.Substring (0, 16) + "..." : text; item.Name = item.Name.Replace ("\t", "\\t"); item.Name = item.Name.Replace ("\n", "\\n"); @@ -2159,6 +2028,7 @@ namespace MonoDevelop.SourceEditor if (ClipbardRingUpdated != null) ClipbardRingUpdated (null, EventArgs.Empty); }; + SyntaxModeLoader.Init (); } public void UpdateClipboardRing (object sender, EventArgs e) @@ -2195,16 +2065,16 @@ namespace MonoDevelop.SourceEditor { var tn = item as ITextToolboxNode; if (tn != null) { - tn.InsertAtCaret (base.WorkbenchWindow.Document); + tn.InsertAtCaret (WorkbenchWindow.Document); TextEditor.GrabFocus (); } } #region dnd - Gtk.Widget customSource; + Widget customSource; ItemToolboxNode dragItem; - void IToolboxConsumer.DragItem (ItemToolboxNode item, Gtk.Widget source, Gdk.DragContext ctx) + void IToolboxConsumer.DragItem (ItemToolboxNode item, Widget source, Gdk.DragContext ctx) { //FIXME: use the preview text string text = GetDragPreviewText (item); @@ -2242,7 +2112,7 @@ namespace MonoDevelop.SourceEditor LoggingService.LogWarning ("Cannot use non-ITextToolboxNode toolbox items in the text editor."); return null; } - return tn.GetDragPreview (base.WorkbenchWindow.Document); + return tn.GetDragPreview (WorkbenchWindow.Document); } System.ComponentModel.ToolboxItemFilterAttribute[] IToolboxConsumer.ToolboxFilterAttributes { @@ -2261,10 +2131,10 @@ namespace MonoDevelop.SourceEditor //int i = filename.LastIndexOf ('.'); //string ext = i < 0? null : filename.Substring (i + 1); - return textNode.IsCompatibleWith (base.WorkbenchWindow.Document); + return textNode.IsCompatibleWith (WorkbenchWindow.Document); } - public Gtk.TargetEntry[] DragTargets { + public TargetEntry[] DragTargets { get { return ClipboardActions.CopyOperation.TargetEntries; } @@ -2285,48 +2155,48 @@ namespace MonoDevelop.SourceEditor #region IZoomable bool IZoomable.EnableZoomIn { get { - return this.TextEditor.Options.CanZoomIn; + return TextEditor.Options.CanZoomIn; } } bool IZoomable.EnableZoomOut { get { - return this.TextEditor.Options.CanZoomOut; + return TextEditor.Options.CanZoomOut; } } bool IZoomable.EnableZoomReset { get { - return this.TextEditor.Options.CanResetZoom; + return TextEditor.Options.CanResetZoom; } } void IZoomable.ZoomIn () { - this.TextEditor.Options.ZoomIn (); + TextEditor.Options.ZoomIn (); } void IZoomable.ZoomOut () { - this.TextEditor.Options.ZoomOut (); + TextEditor.Options.ZoomOut (); } void IZoomable.ZoomReset () { - this.TextEditor.Options.ZoomReset (); + TextEditor.Options.ZoomReset (); } #region ITextEditorResolver implementation - public ResolveResult GetLanguageItem (int offset) + public Microsoft.CodeAnalysis.ISymbol GetLanguageItem (int offset) { - DomRegion region; - return this.SourceEditorWidget.TextEditor.GetLanguageItem (offset, out region); + MonoDevelop.Ide.Editor.DocumentRegion region; + return SourceEditorWidget.TextEditor.GetLanguageItem (offset, out region); } - public ResolveResult GetLanguageItem (int offset, string expression) + public Microsoft.CodeAnalysis.ISymbol GetLanguageItem (int offset, string expression) { - return this.SourceEditorWidget.TextEditor.GetLanguageItem (offset, expression); + return SourceEditorWidget.TextEditor.GetLanguageItem (offset, expression); } #endregion @@ -2346,27 +2216,24 @@ namespace MonoDevelop.SourceEditor #endregion #endregion - public Mono.TextEditor.TextEditorData GetTextEditorData () + public TextEditorData GetTextEditorData () { var editor = TextEditor; if (editor == null) return null; return editor.GetTextEditorData (); } - - public void InsertTemplate (CodeTemplate template, MonoDevelop.Ide.Gui.Document doc) - { - TextEditor.InsertTemplate (template, doc); - } - - [CommandHandler (TextEditorCommands.GotoMatchingBrace)] - protected void OnGotoMatchingBrace () + + public void InsertTemplate (CodeTemplate template, MonoDevelop.Ide.Editor.TextEditor editor, DocumentContext context) { - TextEditor.RunAction (MiscActions.GotoMatchingBracket); + TextEditor.InsertTemplate (template, editor, context); } - + void CorrectIndenting () { + var doc = ownerDocument.Editor; + if (doc == null) + return; var formatter = CodeFormatterService.GetFormatter (Document.MimeType); if (formatter == null || !formatter.SupportsCorrectingIndent) return; @@ -2380,52 +2247,22 @@ namespace MonoDevelop.SourceEditor var version = TextEditor.Document.Version; int max = selection.MaxLine; for (int i = TextEditor.MainSelection.MinLine; i <= max; i++) { - formatter.CorrectIndenting (policies, editorData, i); + formatter.CorrectIndenting (policies, doc, i); } editorData.SetSelection (version.MoveOffsetTo (editorData.Document.Version, anchor), version.MoveOffsetTo (editorData.Document.Version, lead)); } } else { - formatter.CorrectIndenting (policies, editorData, TextEditor.Caret.Line); + formatter.CorrectIndenting (policies, doc, TextEditor.Caret.Line); } } - [CommandUpdateHandler (TextEditorCommands.MoveBlockUp)] - [CommandUpdateHandler (TextEditorCommands.MoveBlockDown)] - void MoveBlockUpdateHandler (CommandInfo cinfo) + public override object GetContent (Type type) { - cinfo.Enabled = widget.EditorHasFocus; + if (type.Equals (typeof(TextEditorData))) + return TextEditor.GetTextEditorData (); + return base.GetContent (type); } - [CommandHandler (TextEditorCommands.MoveBlockUp)] - protected void OnMoveBlockUp () - { - using (var undo = TextEditor.OpenUndoGroup ()) { - TextEditor.RunAction (MiscActions.MoveBlockUp); - CorrectIndenting (); - } - } - - [CommandHandler (TextEditorCommands.MoveBlockDown)] - protected void OnMoveBlockDown () - { - using (var undo = TextEditor.OpenUndoGroup ()) { - TextEditor.RunAction (MiscActions.MoveBlockDown); - CorrectIndenting (); - } - } - - [CommandUpdateHandler (TextEditorCommands.ToggleBlockSelectionMode)] - protected void UpdateToggleBlockSelectionMode (CommandInfo cinfo) - { - cinfo.Enabled = TextEditor.IsSomethingSelected; - } - - [CommandHandler (TextEditorCommands.ToggleBlockSelectionMode)] - protected void OnToggleBlockSelectionMode () - { - TextEditor.SelectionMode = TextEditor.SelectionMode == Mono.TextEditor.SelectionMode.Normal ? Mono.TextEditor.SelectionMode.Block : Mono.TextEditor.SelectionMode.Normal; - TextEditor.QueueDraw (); - } #region widget command handlers [CommandHandler (SearchCommands.EmacsFindNext)] @@ -2524,57 +2361,805 @@ namespace MonoDevelop.SourceEditor { widget.MonodocResolverUpdate (cinfo); } - - [CommandUpdateHandler (EditCommands.ToggleCodeComment)] - internal void OnUpdateToggleComment (MonoDevelop.Components.Commands.CommandInfo info) + + [CommandHandler (SourceEditorCommands.NextIssue)] + void NextIssue () { - widget.OnUpdateToggleComment (info); + widget.NextIssue (); + } + + [CommandHandler (SourceEditorCommands.PrevIssue)] + void PrevIssue () + { + widget.PrevIssue (); + } + + [CommandHandler (SourceEditorCommands.NextIssueError)] + void NextIssueError () + { + widget.NextIssueError (); + } + + [CommandHandler (SourceEditorCommands.PrevIssueError)] + void PrevIssueError () + { + widget.PrevIssueError (); + } + #endregion + + TextDocumentWrapper wrapper; + IReadonlyTextDocument ITextEditorImpl.Document { + get { + if (wrapper == null) + wrapper = new TextDocumentWrapper (widget.TextEditor.Document); + return wrapper; + } + set { + wrapper = (TextDocumentWrapper)value; + widget.TextEditor.Document = wrapper.Document; + } + } + + event EventHandler ITextEditorImpl.SelectionChanged { + add { + TextEditor.SelectionChanged += value; + } + remove { + TextEditor.SelectionChanged -= value; + } + } + + event EventHandler ITextEditorImpl.BeginMouseHover { + add { + TextEditor.BeginHover += value; + } + remove { + TextEditor.BeginHover -= value; + } + } + + event EventHandler ITextEditorImpl.VAdjustmentChanged { + add { + TextEditor.VAdjustment.ValueChanged += value; + } + remove { + TextEditor.VAdjustment.ValueChanged -= value; + } + } + + event EventHandler ITextEditorImpl.HAdjustmentChanged { + add { + TextEditor.HAdjustment.ValueChanged += value; + } + remove { + TextEditor.HAdjustment.ValueChanged -= value; + } + } + + public event EventHandler CaretPositionChanged; + bool hasCaretPositionChanged; + protected virtual void OnCaretPositionChanged (EventArgs e) + { + if (widget.TextEditor.Document.IsInAtomicUndo) { + hasCaretPositionChanged = true; + return; + } + var handler = CaretPositionChanged; + if (handler != null) + handler (this, e); + } + + public event EventHandler BeginAtomicUndoOperation; + + protected virtual void OnBeginUndo (EventArgs e) + { + hasCaretPositionChanged = false; + var handler = BeginAtomicUndoOperation; + if (handler != null) + handler (this, e); + } + + public event EventHandler EndAtomicUndoOperation; + + protected virtual void OnEndUndo (EventArgs e) + { + var handler = EndAtomicUndoOperation; + if (handler != null) + handler (this, e); + if (hasCaretPositionChanged) { + OnCaretPositionChanged (e); + hasCaretPositionChanged = false; + } + } + + void ITextEditorImpl.SetSelection (int anchorOffset, int leadOffset) + { + TextEditor.SetSelection (anchorOffset, leadOffset); + } + + void ITextEditorImpl.ClearSelection () + { + TextEditor.ClearSelection (); + } + + void ITextEditorImpl.CenterToCaret () + { + TextEditor.CenterToCaret (); + } + + void ITextEditorImpl.StartCaretPulseAnimation () + { + TextEditor.StartCaretPulseAnimation (); + } + + int ITextEditorImpl.EnsureCaretIsNotVirtual () + { + return TextEditor.GetTextEditorData ().EnsureCaretIsNotVirtual (); + } + + void ITextEditorImpl.FixVirtualIndentation () + { + TextEditor.GetTextEditorData ().FixVirtualIndentation (); + } + + object ITextEditorImpl.CreateNativeControl () + { + return Control; } - [CommandHandler (EditCommands.ToggleCodeComment)] - public void ToggleCodeComment () + string ITextEditorImpl.FormatString (int offset, string code) { - widget.ToggleCodeComment (); + return TextEditor.GetTextEditorData ().FormatString (offset, code); } - [CommandUpdateHandler (EditCommands.AddCodeComment)] - internal void OnUpdateAddCodeComment (MonoDevelop.Components.Commands.CommandInfo info) + void ITextEditorImpl.StartInsertionMode (InsertionModeOptions insertionModeOptions) { - widget.OnUpdateToggleComment (info); + var mode = new InsertionCursorEditMode (TextEditor, insertionModeOptions.InsertionPoints.Select (ip => new Mono.TextEditor.InsertionPoint ( + new Mono.TextEditor.DocumentLocation (ip.Location.Line, ip.Location.Column), + (Mono.TextEditor.NewLineInsertion)ip.LineBefore, + (Mono.TextEditor.NewLineInsertion)ip.LineAfter + )).ToList ()); + if (mode.InsertionPoints.Count == 0) { + return; + } + var helpWindow = new Mono.TextEditor.PopupWindow.InsertionCursorLayoutModeHelpWindow (); + helpWindow.TitleText = insertionModeOptions.Operation; + mode.HelpWindow = helpWindow; + mode.CurIndex = insertionModeOptions.FirstSelectedInsertionPoint; + mode.StartMode (); + mode.Exited += delegate(object s, Mono.TextEditor.InsertionCursorEventArgs iCArgs) { + insertionModeOptions.ModeExitedAction (new MonoDevelop.Ide.Editor.InsertionCursorEventArgs (iCArgs.Success, + new MonoDevelop.Ide.Editor.InsertionPoint ( + new MonoDevelop.Ide.Editor.DocumentLocation (iCArgs.InsertionPoint.Location.Line, iCArgs.InsertionPoint.Location.Column), + (MonoDevelop.Ide.Editor.NewLineInsertion)iCArgs.InsertionPoint.LineBefore, + (MonoDevelop.Ide.Editor.NewLineInsertion)iCArgs.InsertionPoint.LineAfter + ) + )); + }; } - [CommandHandler (EditCommands.AddCodeComment)] - public void AddCodeComment () + void ITextEditorImpl.StartTextLinkMode (TextLinkModeOptions textLinkModeOptions) { - widget.AddCodeComment (); + var convertedLinks = new List<Mono.TextEditor.TextLink> (); + foreach (var link in textLinkModeOptions.Links) { + var convertedLink = new Mono.TextEditor.TextLink (link.Name); + convertedLink.IsEditable = link.IsEditable; + convertedLink.IsIdentifier = link.IsIdentifier; + var func = link.GetStringFunc; + if (func != null) { + convertedLink.GetStringFunc = delegate(Func<string, string> arg) { + return new ListDataProviderWrapper (func (arg)); + }; + } + foreach (var segment in link.Links) { + convertedLink.AddLink (new Mono.TextEditor.TextSegment (segment.Offset, segment.Length)); + } + convertedLinks.Add (convertedLink); + } + + var tle = new TextLinkEditMode (TextEditor, 0, convertedLinks); + tle.SetCaretPosition = false; + if (tle.ShouldStartTextLinkMode) { + tle.OldMode = TextEditor.CurrentMode; + if (textLinkModeOptions.ModeExitedAction != null) { + tle.Cancel += (sender, e) => textLinkModeOptions.ModeExitedAction (new TextLinkModeEventArgs (false)); + tle.Exited += (sender, e) => { + for (int i = 0; i < convertedLinks.Count; i++) { + textLinkModeOptions.Links[i].CurrentText = convertedLinks[i].CurrentText; + } + textLinkModeOptions.ModeExitedAction (new TextLinkModeEventArgs (true)); + + }; + } + tle.StartMode (); + TextEditor.CurrentMode = tle; + } } - [CommandUpdateHandler (EditCommands.RemoveCodeComment)] - internal void OnUpdateRemoveCodeComment (MonoDevelop.Components.Commands.CommandInfo info) + MonoDevelop.Ide.Editor.DocumentLocation ITextEditorImpl.PointToLocation (double xp, double yp, bool endAtEol) { - widget.OnUpdateToggleComment (info); + var pt = TextEditor.PointToLocation (xp, yp); + return new MonoDevelop.Ide.Editor.DocumentLocation (pt.Line, pt.Column); } - [CommandHandler (EditCommands.RemoveCodeComment)] - public void RemoveCodeComment () + Xwt.Point ITextEditorImpl.LocationToPoint (int line, int column) { - widget.RemoveCodeComment (); + var p = TextEditor.LocationToPoint (line, column); + return new Xwt.Point (p.X, p.Y); } - [CommandUpdateHandler (SourceEditorCommands.ToggleErrorTextMarker)] - public void OnUpdateToggleErrorTextMarker (CommandInfo info) + void ITextEditorImpl.AddMarker (IDocumentLine line, ITextLineMarker lineMarker) { - widget.OnUpdateToggleErrorTextMarker (info); + var textLineMarker = lineMarker as TextLineMarker; + if (textLineMarker == null) + throw new InvalidOperationException ("Tried to add an incompatible text marker. Use the MarkerHost to create compatible ones."); + + if (lineMarker is IUnitTestMarker) { + var actionMargin = TextEditor.ActionMargin; + if (actionMargin != null) { + actionMargin.IsVisible = true; + } + } + + TextEditor.Document.AddMarker (((DocumentLineWrapper)line).Line, textLineMarker); + } + + void ITextEditorImpl.RemoveMarker (ITextLineMarker lineMarker) + { + var textLineMarker = lineMarker as TextLineMarker; + if (textLineMarker == null) + throw new InvalidOperationException ("Tried to add an incompatible text marker."); + TextEditor.Document.RemoveMarker (textLineMarker); + } + + IEnumerable<ITextLineMarker> ITextEditorImpl.GetLineMarkers (IDocumentLine line) + { + return ((DocumentLineWrapper)line).Line.Markers.OfType<ITextLineMarker> (); + } + + IEnumerable<ITextSegmentMarker> ITextEditorImpl.GetTextSegmentMarkersAt (MonoDevelop.Core.Text.ISegment segment) + { + return TextEditor.Document.GetTextSegmentMarkersAt (new TextSegment (segment.Offset, segment.Length)).OfType<ITextSegmentMarker> (); + } + + IEnumerable<ITextSegmentMarker> ITextEditorImpl.GetTextSegmentMarkersAt (int offset) + { + return TextEditor.Document.GetTextSegmentMarkersAt (offset).OfType<ITextSegmentMarker> (); + } + + void ITextEditorImpl.AddMarker (ITextSegmentMarker marker) + { + var textSegmentMarker = marker as TextSegmentMarker; + if (textSegmentMarker == null) + throw new InvalidOperationException ("Tried to add an incompatible text marker. Use the MarkerHost to create compatible ones."); + TextEditor.Document.AddMarker (textSegmentMarker); + } + + bool ITextEditorImpl.RemoveMarker (ITextSegmentMarker marker) + { + var textSegmentMarker = marker as TextSegmentMarker; + if (textSegmentMarker == null) + throw new InvalidOperationException ("Tried to remove an incompatible text marker."); + return TextEditor.Document.RemoveMarker (textSegmentMarker); + } + + IFoldSegment ITextEditorImpl.CreateFoldSegment (int offset, int length, bool isFolded = false) + { + return new FoldSegmentWrapper (TextEditor.Document, "...", offset, length, Mono.TextEditor.FoldingType.None) { IsFolded = isFolded }; + } + + void ITextEditorImpl.SetFoldings (IEnumerable<IFoldSegment> foldings) + { + TextEditor.Document.UpdateFoldSegments (foldings.Cast<FoldSegment> ().ToList ()); + } + + IEnumerable<IFoldSegment> ITextEditorImpl.GetFoldingsContaining (int offset) + { + return TextEditor.Document.GetFoldingsFromOffset (offset).Cast<IFoldSegment> (); + } + + IEnumerable<IFoldSegment> ITextEditorImpl.GetFoldingsIn (int offset, int length) + { + return TextEditor.Document.GetFoldingContaining (offset, length).Cast<IFoldSegment> (); + } + + MonoDevelop.Ide.Editor.ITextEditorOptions ITextEditorImpl.Options { + get { + return((StyledSourceEditorOptions)TextEditor.Options).OptionsCore; + } + set { + ((StyledSourceEditorOptions)TextEditor.Options).OptionsCore = value; + } + } + + MonoDevelop.Ide.Editor.DocumentLocation ITextEditorImpl.CaretLocation { + get { + var loc = TextEditor.Caret.Location; + return new MonoDevelop.Ide.Editor.DocumentLocation (loc.Line, loc.Column); + } + set { + TextEditor.Caret.Location = new Mono.TextEditor.DocumentLocation (value.Line, value.Column); + TextEditor.ScrollToCaret (); + } + } + + bool ITextEditorImpl.IsSomethingSelected { + get { + return TextEditor.IsSomethingSelected; + } + } + + MonoDevelop.Ide.Editor.SelectionMode ITextEditorImpl.SelectionMode { + get { + return (MonoDevelop.Ide.Editor.SelectionMode)TextEditor.SelectionMode; + } + } + + MonoDevelop.Core.Text.ISegment ITextEditorImpl.SelectionRange { + get { + var range = TextEditor.SelectionRange; + return MonoDevelop.Core.Text.TextSegment.FromBounds (range.Offset, range.EndOffset); + } + set { + TextEditor.SelectionRange = new TextSegment (value.Offset, value.Length); + } } - [CommandHandler (SourceEditorCommands.ToggleErrorTextMarker)] - public void OnToggleErrorTextMarker () + int ITextEditorImpl.SelectionAnchorOffset { + get { + return TextEditor.SelectionAnchor; + } + set { + TextEditor.SelectionAnchor = value; + } + } + + int ITextEditorImpl.SelectionLeadOffset { + get { + return TextEditor.SelectionLead; + } + set { + TextEditor.SelectionLead = value; + } + } + + + + MonoDevelop.Ide.Editor.DocumentRegion ITextEditorImpl.SelectionRegion { + get { + return new MonoDevelop.Ide.Editor.DocumentRegion ( + TextEditor.MainSelection.Start.Line, + TextEditor.MainSelection.Start.Column, + TextEditor.MainSelection.End.Line, + TextEditor.MainSelection.End.Column + ); + } + set { + TextEditor.MainSelection = new Mono.TextEditor.Selection ( + value.BeginLine, + value.BeginColumn, + value.EndLine, + value.EndColumn + ); + } + } + + IEditorActionHost ITextEditorImpl.Actions { + get { + return this; + } + } + + double ITextEditorImpl.LineHeight { + get { + return TextEditor.GetTextEditorData ().LineHeight; + } + } + + ITextMarkerFactory ITextEditorImpl.TextMarkerFactory { + get { + return this; + } + } + + MonoDevelop.Ide.Editor.EditMode ITextEditorImpl.EditMode { + get { + if (TextEditor.CurrentMode is TextLinkEditMode) + return MonoDevelop.Ide.Editor.EditMode.TextLink; + if (TextEditor.CurrentMode is InsertionCursorEditMode) + return MonoDevelop.Ide.Editor.EditMode.CursorInsertion; + return MonoDevelop.Ide.Editor.EditMode.Edit; + } + } + + string ITextEditorImpl.GetVirtualIndentationString (int lineNumber) + { + if (!TextEditor.GetTextEditorData ().HasIndentationTracker) + return TextEditor.GetLineIndent (lineNumber); + return TextEditor.GetTextEditorData ().IndentationTracker.GetIndentationString (lineNumber, 1); + } + + void ITextEditorImpl.SetIndentationTracker (IndentationTracker indentationTracker) + { + TextEditor.GetTextEditorData ().IndentationTracker = indentationTracker != null ? new IndentationTrackerWrapper (TextEditor.GetTextEditorData (), wrapper, indentationTracker) : null; + } + + void ITextEditorImpl.SetSelectionSurroundingProvider (SelectionSurroundingProvider surroundingProvider) + { + TextEditor.GetTextEditorData ().SelectionSurroundingProvider = surroundingProvider != null ? new SelectionSurroundingProviderWrapper (surroundingProvider) : null; + } + + void ITextEditorImpl.SetTextPasteHandler (TextPasteHandler textPasteHandler) + { + if (textPasteHandler == null) { + TextEditor.GetTextEditorData ().TextPasteHandler = null; + return; + } + var data = TextEditor.GetTextEditorData (); + if (data.TextPasteHandler != null) + ((TextPasteHandlerWrapper)data.TextPasteHandler).Dispose (); + data.TextPasteHandler = new TextPasteHandlerWrapper (data, textPasteHandler); + } + + public IList<SkipChar> SkipChars { + get { + return TextEditor.GetTextEditorData ().SkipChars.Select (sk => new SkipChar (sk.Offset, sk.Char)).ToList (); + } + } + + public void AddSkipChar (int offset, char ch) + { + TextEditor.GetTextEditorData ().SetSkipChar (offset, ch); + } + + void ITextEditorImpl.ScrollTo (int offset) + { + TextEditor.ScrollTo (offset); + } + + void ITextEditorImpl.CenterTo (int offset) + { + TextEditor.CenterTo (offset); + } + + void ITextEditorImpl.ClearTooltipProviders () + { + TextEditor.ClearTooltipProviders (); + } + + IEnumerable<MonoDevelop.Ide.Editor.TooltipProvider> ITextEditorImpl.TooltipProvider { + get { + foreach (var p in GetTextEditorData ().TooltipProviders) { + var wrapper = p as TooltipProviderWrapper; + if (wrapper == null) + continue; + yield return wrapper.OriginalProvider; + } + } + } + + void ITextEditorImpl.AddTooltipProvider (MonoDevelop.Ide.Editor.TooltipProvider provider) + { + TextEditor.AddTooltipProvider (new TooltipProviderWrapper (provider)); + } + + void ITextEditorImpl.RemoveTooltipProvider (MonoDevelop.Ide.Editor.TooltipProvider provider) + { + foreach (var p in GetTextEditorData ().TooltipProviders) { + var wrapper = p as TooltipProviderWrapper; + if (wrapper == null) + continue; + if (wrapper.OriginalProvider == provider) { + TextEditor.RemoveTooltipProvider (p); + return; + } + } + } + + Xwt.Point ITextEditorImpl.GetEditorWindowOrigin () + { + int ox, oy; + TextEditor.GdkWindow.GetOrigin (out ox, out oy); + return new Xwt.Point (ox, oy); + } + + Xwt.Rectangle ITextEditorImpl.GetEditorAllocation () + { + var alloc = TextEditor.Allocation; + return new Xwt.Rectangle (alloc.X, alloc.Y, alloc.Width, alloc.Height); + } + + + TextEditorExtension ITextEditorImpl.EditorExtension { + get { + return TextEditor.EditorExtension; + } + set { + TextEditor.EditorExtension = value; + } + } + + + SemanticHighlighting ITextEditorImpl.SemanticHighlighting { + get { + return TextEditor.SemanticHighlighting; + } + set { + TextEditor.SemanticHighlighting = value; + } + } + + string ITextEditorImpl.GetPangoMarkup (int offset, int length) + { + return TextEditor.GetTextEditorData ().GetMarkup (offset, length, false); + } + + void ITextEditorImpl.SetUsageTaskProviders (IEnumerable<UsageProviderEditorExtension> providers) + { + widget.ClearUsageTaskProvider (); + foreach (var p in providers) { + widget.AddUsageTaskProvider (p); + } + } + + void ITextEditorImpl.SetQuickTaskProviders (IEnumerable<IQuickTaskProvider> providers) + { + widget.ClearQuickTaskProvider (); + foreach (var p in providers) { + widget.AddQuickTaskProvider (p); + } + } + + public event EventHandler<MonoDevelop.Ide.Editor.LineEventArgs> LineChanged; + + public event EventHandler<MonoDevelop.Ide.Editor.LineEventArgs> LineInserted; + + void HandleLineInserted (object sender, Mono.TextEditor.LineEventArgs e) + { + var handler = LineInserted; + if (handler != null) + handler (this, new MonoDevelop.Ide.Editor.LineEventArgs (new DocumentLineWrapper (e.Line))); + } + + public event EventHandler<MonoDevelop.Ide.Editor.LineEventArgs> LineRemoved; + + void HandleLineRemoved (object sender, Mono.TextEditor.LineEventArgs e) + { + var handler = LineRemoved; + if (handler != null) + handler (this, new MonoDevelop.Ide.Editor.LineEventArgs (new DocumentLineWrapper (e.Line))); + } + + public double ZoomLevel { + get { return TextEditor.Options.Zoom; } + set { TextEditor.Options.Zoom = value; } + } + event EventHandler ITextEditorImpl.ZoomLevelChanged { + add { + TextEditor.Options.ZoomChanged += value; + } + remove { + TextEditor.Options.ZoomChanged += value; + } + } + + public void AddOverlay (Control messageOverlayContent, Func<int> sizeFunc) + { + widget.AddOverlay (messageOverlayContent.GetNativeWidget<Widget> (), sizeFunc); + } + + public void RemoveOverlay (Control messageOverlayContent) + { + widget.RemoveOverlay (messageOverlayContent.GetNativeWidget<Widget> ()); + } + + #region IEditorActionHost implementation + + void IEditorActionHost.MoveCaretDown () + { + CaretMoveActions.Down (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.MoveCaretUp () + { + CaretMoveActions.Up (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.MoveCaretRight () + { + CaretMoveActions.Right (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.MoveCaretLeft () + { + CaretMoveActions.Left (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.MoveCaretToLineEnd () + { + CaretMoveActions.LineEnd (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.MoveCaretToLineStart () { - widget.OnToggleErrorTextMarker (); + CaretMoveActions.LineHome (TextEditor.GetTextEditorData ()); } - [CommandHandler (EditCommands.IndentSelection)] - public void IndentSelection () + void IEditorActionHost.MoveCaretToDocumentStart () + { + CaretMoveActions.ToDocumentStart (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.MoveCaretToDocumentEnd () + { + CaretMoveActions.ToDocumentEnd (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.Backspace () + { + DeleteActions.Backspace (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.ClipboardCopy () + { + ClipboardActions.Copy (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.ClipboardCut () + { + ClipboardActions.Cut (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.ClipboardPaste () + { + ClipboardActions.Paste (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.NewLine () + { + MiscActions.InsertNewLine (TextEditor.GetTextEditorData ()); + } + + void IEditorActionHost.SwitchCaretMode () + { + TextEditor.RunAction (MiscActions.SwitchCaretMode); + } + + void IEditorActionHost.InsertTab () + { + TextEditor.RunAction (MiscActions.InsertTab); + } + + void IEditorActionHost.RemoveTab () + { + TextEditor.RunAction (MiscActions.RemoveTab); + } + + void IEditorActionHost.InsertNewLine () + { + TextEditor.RunAction (MiscActions.InsertNewLine); + } + + void IEditorActionHost.DeletePreviousWord () + { + TextEditor.RunAction (DeleteActions.PreviousWord); + } + + void IEditorActionHost.DeleteNextWord () + { + TextEditor.RunAction (DeleteActions.NextWord); + } + + void IEditorActionHost.DeletePreviousSubword () + { + TextEditor.RunAction (DeleteActions.PreviousSubword); + } + + void IEditorActionHost.DeleteNextSubword () + { + TextEditor.RunAction (DeleteActions.NextSubword); + } + + void IEditorActionHost.StartCaretPulseAnimation () + { + TextEditor.StartCaretPulseAnimation (); + } + + void IEditorActionHost.RecenterEditor () + { + TextEditor.RunAction (MiscActions.RecenterEditor); + } + + void IEditorActionHost.JoinLines () + { + using (var undo = Document.OpenUndoGroup ()) { + TextEditor.RunAction (Mono.TextEditor.Vi.ViActions.Join); + } + } + + void IEditorActionHost.MoveNextSubWord () + { + TextEditor.RunAction (SelectionActions.MoveNextSubword); + } + + void IEditorActionHost.MovePrevSubWord () + { + TextEditor.RunAction (SelectionActions.MovePreviousSubword); + } + + void IEditorActionHost.MoveNextWord () + { + TextEditor.RunAction (CaretMoveActions.NextWord); + } + + void IEditorActionHost.MovePrevWord () + { + TextEditor.RunAction (CaretMoveActions.PreviousWord); + } + + void IEditorActionHost.PageUp () + { + TextEditor.RunAction (CaretMoveActions.PageUp); + } + + void IEditorActionHost.PageDown () + { + TextEditor.RunAction (CaretMoveActions.PageDown); + } + + void IEditorActionHost.DeleteCurrentLine () + { + TextEditor.RunAction (DeleteActions.CaretLine); + } + + void IEditorActionHost.DeleteCurrentLineToEnd () + { + TextEditor.RunAction (DeleteActions.CaretLineToEnd); + } + + void IEditorActionHost.ScrollLineUp () + { + TextEditor.RunAction (ScrollActions.Up); + } + + void IEditorActionHost.ScrollLineDown () + { + TextEditor.RunAction (ScrollActions.Down); + } + + void IEditorActionHost.ScrollPageUp () + { + TextEditor.RunAction (ScrollActions.PageUp); + } + + void IEditorActionHost.ScrollPageDown () + { + TextEditor.RunAction (ScrollActions.PageDown); + } + + void IEditorActionHost.MoveBlockUp () + { + using (var undo = TextEditor.OpenUndoGroup ()) { + TextEditor.RunAction (MiscActions.MoveBlockUp); + CorrectIndenting (); + } + } + + void IEditorActionHost.MoveBlockDown () + { + using (var undo = TextEditor.OpenUndoGroup ()) { + TextEditor.RunAction (MiscActions.MoveBlockDown); + CorrectIndenting (); + } + } + + void IEditorActionHost.ToggleBlockSelectionMode () + { + TextEditor.SelectionMode = TextEditor.SelectionMode == Mono.TextEditor.SelectionMode.Normal ? Mono.TextEditor.SelectionMode.Block : Mono.TextEditor.SelectionMode.Normal; + TextEditor.QueueDraw (); + } + + void IEditorActionHost.IndentSelection () { if (widget.TextEditor.IsSomethingSelected) { MiscActions.IndentSelection (widget.TextEditor.GetTextEditorData ()); @@ -2583,45 +3168,74 @@ namespace MonoDevelop.SourceEditor widget.TextEditor.Insert (offset, widget.TextEditor.Options.IndentationString); } } - - [CommandHandler (EditCommands.UnIndentSelection)] - public void UnIndentSelection () + + void IEditorActionHost.UnIndentSelection () { - Mono.TextEditor.MiscActions.RemoveTab (widget.TextEditor.GetTextEditorData ()); + MiscActions.RemoveTab (widget.TextEditor.GetTextEditorData ()); } - - [CommandHandler (EditCommands.InsertGuid)] - public void InsertGuid () + + #endregion + + + #region ISegmentMarkerHost implementation + + ITextSegmentMarker ITextMarkerFactory.CreateUsageMarker (MonoDevelop.Ide.Editor.TextEditor editor, Usage usage) { - TextEditor.InsertAtCaret (Guid.NewGuid ().ToString ()); + return new UsageSegmentMarker (usage); } - [CommandHandler (SourceEditorCommands.NextIssue)] - void NextIssue () + IUrlTextLineMarker ITextMarkerFactory.CreateUrlTextMarker (MonoDevelop.Ide.Editor.TextEditor editor, IDocumentLine line, string value, MonoDevelop.Ide.Editor.UrlType url, string syntax, int startCol, int endCol) { - widget.NextIssue (); - } + return new UrlTextLineMarker (TextEditor.Document, line, value, (Mono.TextEditor.UrlType)url, syntax, startCol, endCol); + } - [CommandHandler (SourceEditorCommands.PrevIssue)] - void PrevIssue () + ICurrentDebugLineTextMarker ITextMarkerFactory.CreateCurrentDebugLineTextMarker (MonoDevelop.Ide.Editor.TextEditor editor) { - widget.PrevIssue (); + return new CurrentDebugLineTextMarker (TextEditor); } - [CommandHandler (SourceEditorCommands.NextIssueError)] - void NextIssueError () + ITextLineMarker ITextMarkerFactory.CreateAsmLineMarker (MonoDevelop.Ide.Editor.TextEditor editor) { - widget.NextIssueError (); - } + return new AsmLineMarker (); + } - [CommandHandler (SourceEditorCommands.PrevIssueError)] - void PrevIssueError () + IUnitTestMarker ITextMarkerFactory.CreateUnitTestMarker (MonoDevelop.Ide.Editor.TextEditor editor, UnitTestMarkerHost host, UnitTestLocation unitTestLocation) { - widget.PrevIssueError (); + return new UnitTestMarker (TextEditor, host, unitTestLocation); + } + + IMessageBubbleLineMarker ITextMarkerFactory.CreateMessageBubbleLineMarker (MonoDevelop.Ide.Editor.TextEditor editor) + { + return new MessageBubbleTextMarker (messageBubbleCache); + } + + IGenericTextSegmentMarker ITextMarkerFactory.CreateGenericTextSegmentMarker (MonoDevelop.Ide.Editor.TextEditor editor, TextSegmentMarkerEffect effect, int offset, int length) + { + switch (effect) { + case TextSegmentMarkerEffect.DottedLine: + case TextSegmentMarkerEffect.WavedLine: + return new GenericUnderlineMarker (new TextSegment (offset, length), effect); + case TextSegmentMarkerEffect.GrayOut: + return new GrayOutMarker (new TextSegment (offset, length)); + default: + throw new ArgumentOutOfRangeException (); + } } + public ITextSegmentMarker CreateLinkMarker (MonoDevelop.Ide.Editor.TextEditor editor, int offset, int length, Action<LinkRequest> activateLink) + { + return new LinkMarker (offset, length, activateLink); + } + ISmartTagMarker ITextMarkerFactory.CreateSmartTagMarker (MonoDevelop.Ide.Editor.TextEditor editor, int offset, MonoDevelop.Ide.Editor.DocumentLocation realLocation) + { + return new SmartTagMarker (offset, realLocation); + } + IErrorMarker ITextMarkerFactory.CreateErrorMarker (MonoDevelop.Ide.Editor.TextEditor editor, MonoDevelop.Ide.TypeSystem.Error info, int offset, int length) + { + return new ErrorMarker (info, offset, length); + } #endregion diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorWidget.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorWidget.cs index 478144b7c9..e9dbb715cf 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorWidget.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SourceEditorWidget.cs @@ -45,12 +45,14 @@ using MonoDevelop.Ide.TypeSystem; using Mono.TextEditor.Highlighting; using MonoDevelop.SourceEditor.QuickTasks; using ICSharpCode.NRefactory.Semantics; -using ICSharpCode.NRefactory.Refactoring; using MonoDevelop.Ide.Tasks; +using MonoDevelop.Ide.Editor; +using MonoDevelop.Ide.Editor.Extension; +using Microsoft.CodeAnalysis; namespace MonoDevelop.SourceEditor { - class SourceEditorWidget : ITextEditorExtension, IQuickTaskProvider + class SourceEditorWidget : IServiceProvider { SourceEditorView view; DecoratedScrolledWindow mainsw; @@ -65,8 +67,9 @@ namespace MonoDevelop.SourceEditor // bool shouldShowclassBrowser; // bool canShowClassBrowser; - ISourceEditorOptions options { + Mono.TextEditor.ITextEditorOptions options { get { + return textEditor.Options; } } @@ -92,13 +95,6 @@ namespace MonoDevelop.SourceEditor } } - public Ambience Ambience { - get { - string fileName = view.IsUntitled ? view.UntitledName : view.ContentName; - return AmbienceService.GetAmbienceForFile (fileName); - } - } - List<IQuickTaskProvider> quickTaskProvider = new List<IQuickTaskProvider> (); public void AddQuickTaskProvider (IQuickTaskProvider provider) { @@ -108,6 +104,14 @@ namespace MonoDevelop.SourceEditor secondsw.AddQuickTaskProvider (provider); } + internal void ClearQuickTaskProvider () + { + foreach (var provider in quickTaskProvider.ToArray ()) { + RemoveQuickTaskProvider (provider); + } + quickTaskProvider = new List<IQuickTaskProvider> (); + } + public void RemoveQuickTaskProvider (IQuickTaskProvider provider) { quickTaskProvider.Remove (provider); @@ -117,44 +121,32 @@ namespace MonoDevelop.SourceEditor } - List<IUsageProvider> usageProvider = new List<IUsageProvider> (); - public void AddUsageTaskProvider (IUsageProvider provider) + List<UsageProviderEditorExtension> usageProvider = new List<UsageProviderEditorExtension> (); + + internal void ClearUsageTaskProvider() { - usageProvider.Add (provider); - mainsw.AddUsageProvider (provider); - if (secondsw != null) - secondsw.AddUsageProvider (provider); - } - - #region ITextEditorExtension - - ITextEditorExtension ITextEditorExtension.Next { - get { - return null; + foreach (var provider in usageProvider.ToArray ()) { + RemoveUsageTaskProvider (provider); } - } - - object ITextEditorExtension.GetExtensionCommandTarget () - { - return null; - } + usageProvider = new List<UsageProviderEditorExtension> (); - void ITextEditorExtension.TextChanged (int startIndex, int endIndex) - { } - void ITextEditorExtension.CursorPositionChanged () + public void AddUsageTaskProvider (UsageProviderEditorExtension provider) { + usageProvider.Add (provider); + mainsw.AddUsageProvider (provider); + if (secondsw != null) + secondsw.AddUsageProvider (provider); } - bool ITextEditorExtension.KeyPress (Gdk.Key key, char keyChar, Gdk.ModifierType modifier) + void RemoveUsageTaskProvider (UsageProviderEditorExtension provider) { - this.TextEditor.SimulateKeyPress (key, (uint)keyChar, modifier); - if (key == Gdk.Key.Escape) - return true; - return false; + usageProvider.Remove (provider); + mainsw.RemoveUsageProvider (provider); + if (secondsw != null) + secondsw.RemoveUsageProvider (provider); } - #endregion public bool HasMessageBar { get { return messageBar != null; } @@ -195,7 +187,7 @@ namespace MonoDevelop.SourceEditor return false; } - public class Border : Gtk.DrawingArea + class Border : Gtk.DrawingArea { protected override bool OnExposeEvent (Gdk.EventExpose evnt) { @@ -307,12 +299,21 @@ namespace MonoDevelop.SourceEditor provider.TasksUpdated -= HandleTasksUpdated; } + public void AddUsageProvider (UsageProviderEditorExtension p) + { + p.UsagesUpdated += HandleUsagesUpdated; + } - public void AddUsageProvider (IUsageProvider p) + public void RemoveUsageProvider (UsageProviderEditorExtension p) { - p.UsagesUpdated += (sender, e) => strip.Update (p); + p.UsagesUpdated -= HandleUsagesUpdated; + } + + void HandleUsagesUpdated (object sender, EventArgs e) + { + strip.Update ((UsageProviderEditorExtension)sender); } - + protected override void OnDestroyed () { if (scrolledWindow.Child != null) @@ -329,7 +330,7 @@ namespace MonoDevelop.SourceEditor args.RetVal = true; } - public void SetTextEditor (TextEditor container) + public void SetTextEditor (Mono.TextEditor.MonoTextEditor container) { scrolledWindow.Child = container; this.strip.TextEditor = container; @@ -341,14 +342,15 @@ namespace MonoDevelop.SourceEditor void OptionsChanged (object sender, EventArgs e) { - TextEditor editor = (TextEditor)sender; - scrolledWindow.ModifyBg (StateType.Normal, (Mono.TextEditor.HslColor)editor.ColorStyle.PlainText.Background); + var editor = (Mono.TextEditor.MonoTextEditor)sender; + scrolledWindow.ModifyBg (StateType.Normal, (HslColor)editor.ColorStyle.PlainText.Background); } void RemoveEvents () { - var container = scrolledWindow.Child as TextEditor; + var container = scrolledWindow.Child as Mono.TextEditor.MonoTextEditor; if (container == null) { + LoggingService.LogError ("can't remove events from text editor container."); return; } @@ -358,9 +360,9 @@ namespace MonoDevelop.SourceEditor container.SelectionChanged -= parent.UpdateLineColOnEventHandler; } - public TextEditor RemoveTextEditor () + public Mono.TextEditor.MonoTextEditor RemoveTextEditor () { - var child = scrolledWindow.Child as TextEditor; + var child = scrolledWindow.Child as Mono.TextEditor.MonoTextEditor; if (child == null) return null; RemoveEvents (); @@ -383,7 +385,8 @@ namespace MonoDevelop.SourceEditor if (this.splittedTextEditor == null || !splittedTextEditor.TextArea.HasFocus) OnLostFocus (); }; - IdeApp.FocusOut += (sender, e) => textEditor.TextArea.HideTooltip (false); + if (IdeApp.CommandService != null) + IdeApp.FocusOut += (sender, e) => textEditor.TextArea.HideTooltip (false); mainsw = new DecoratedScrolledWindow (this); mainsw.SetTextEditor (textEditor); @@ -405,13 +408,11 @@ namespace MonoDevelop.SourceEditor }; vbox.Destroyed += delegate { isDisposed = true; - RemoveErrorUndelinesResetTimerId (); StopParseInfoThread (); KillWidgets (); - foreach (var provider in quickTaskProvider.ToArray ()) { - RemoveQuickTaskProvider (provider); - } + ClearQuickTaskProvider (); + ClearUsageTaskProvider (); this.lastActiveEditor = null; this.splittedTextEditor = null; @@ -421,6 +422,7 @@ namespace MonoDevelop.SourceEditor // IdeApp.Workbench.StatusBar.ClearCaretState (); }; vbox.ShowAll (); + } void OnLostFocus () @@ -447,10 +449,9 @@ namespace MonoDevelop.SourceEditor public void Dispose () { - RemoveErrorUndelinesResetTimerId (); } - FoldSegment AddMarker (List<FoldSegment> foldSegments, string text, DomRegion region, FoldingType type) + Mono.TextEditor.FoldSegment AddMarker (List<Mono.TextEditor.FoldSegment> foldSegments, string text, DomRegion region, Mono.TextEditor.FoldingType type) { Document document = textEditorData.Document; if (document == null || region.BeginLine <= 0 || region.EndLine <= 0 || region.BeginLine > document.LineCount || region.EndLine > document.LineCount) @@ -459,110 +460,27 @@ namespace MonoDevelop.SourceEditor int startOffset = document.LocationToOffset (region.BeginLine, region.BeginColumn); int endOffset = document.LocationToOffset (region.EndLine, region.EndColumn ); - FoldSegment result = new FoldSegment (document, text, startOffset, endOffset - startOffset, type); + var result = new Mono.TextEditor.FoldSegment (document, text, startOffset, endOffset - startOffset, type); foldSegments.Add (result); return result; } - HashSet<string> symbols = new HashSet<string> (); bool reloadSettings; void HandleParseInformationUpdaterWorkerThreadDoWork (bool firstTime, ParsedDocument parsedDocument, CancellationToken token = default(CancellationToken)) { - var doc = Document; - if (doc == null || parsedDocument == null) - return; - UpdateErrorUndelines (parsedDocument); - if (!options.ShowFoldMargin) - return; - // don't update parsed documents that contain errors - the foldings from there may be invalid. - if (parsedDocument.HasErrors) - return; - try { - List<FoldSegment > foldSegments = new List<FoldSegment> (); - bool updateSymbols = parsedDocument.Defines.Count != symbols.Count; - if (!updateSymbols) { - foreach (PreProcessorDefine define in parsedDocument.Defines) { - if (token.IsCancellationRequested) - return; - if (!symbols.Contains (define.Define)) { - updateSymbols = true; - break; - } - } - } - - if (updateSymbols) { - symbols.Clear (); - foreach (PreProcessorDefine define in parsedDocument.Defines) { - symbols.Add (define.Define); - } - } - - foreach (FoldingRegion region in parsedDocument.Foldings) { - if (token.IsCancellationRequested) + + + if (reloadSettings) { + reloadSettings = false; + Application.Invoke (delegate { + if (isDisposed) return; - FoldingType type = FoldingType.None; - bool setFolded = false; - bool folded = false; - - //decide whether the regions should be folded by default - switch (region.Type) { - case FoldType.Member: - type = FoldingType.TypeMember; - break; - case FoldType.Type: - type = FoldingType.TypeDefinition; - break; - case FoldType.UserRegion: - type = FoldingType.Region; - setFolded = options.DefaultRegionsFolding; - folded = true; - break; - case FoldType.Comment: - type = FoldingType.Comment; - setFolded = options.DefaultCommentFolding; - folded = true; - break; - case FoldType.CommentInsideMember: - type = FoldingType.Comment; - setFolded = options.DefaultCommentFolding; - folded = false; - break; - case FoldType.Undefined: - setFolded = true; - folded = region.IsFoldedByDefault; - break; - } - - //add the region - FoldSegment marker = AddMarker (foldSegments, region.Name, - region.Region, type); - - //and, if necessary, set its fold state - if (marker != null && setFolded && firstTime) { - // only fold on document open, later added folds are NOT folded by default. - marker.IsFolded = folded; - continue; - } - if (marker != null && region.Region.IsInside (textEditorData.Caret.Line, textEditorData.Caret.Column)) - marker.IsFolded = false; - - } - doc.UpdateFoldSegments (foldSegments, false, true, token); - - if (reloadSettings) { - reloadSettings = false; - Application.Invoke (delegate { - if (isDisposed) - return; - view.LoadSettings (); - mainsw.QueueDraw (); - }); - } - } catch (Exception ex) { - LoggingService.LogError ("Unhandled exception in ParseInformationUpdaterWorkerThread", ex); + view.LoadSettings (); + mainsw.QueueDraw (); + }); } + } internal void UpdateParsedDocument (ParsedDocument document) @@ -608,77 +526,9 @@ namespace MonoDevelop.SourceEditor { this.lastActiveEditor = editor; } - - #region Error underlining - List<ErrorMarker> errors = new List<ErrorMarker> (); - uint resetTimerId; - - void RemoveErrorUndelinesResetTimerId () - { - if (resetTimerId > 0) { - GLib.Source.Remove (resetTimerId); - resetTimerId = 0; - } - } - - void UpdateErrorUndelines (ParsedDocument parsedDocument) - { - if (!options.UnderlineErrors || parsedDocument == null) { - Application.Invoke (delegate { - var doc = this.TextEditor != null ? this.TextEditor.Document : null; - if (doc == null) - return; - RemoveErrorUnderlines (doc); - UpdateQuickTasks (parsedDocument); - }); - return; - } - - Application.Invoke (delegate { - if (!quickTaskProvider.Contains (this)) - AddQuickTaskProvider (this); - RemoveErrorUndelinesResetTimerId (); - const uint timeout = 500; - resetTimerId = GLib.Timeout.Add (timeout, delegate { - if (!this.isDisposed) { - Document doc = this.TextEditor != null ? this.TextEditor.Document : null; - if (doc != null) { - RemoveErrorUnderlines (doc); - - // Else we underline the error - if (parsedDocument.Errors != null) { - foreach (var error in parsedDocument.Errors) - UnderLineError (doc, error); - } - } - } - resetTimerId = 0; - return false; - }); - UpdateQuickTasks (parsedDocument); - }); - } - - void RemoveErrorUnderlines (Document doc) - { - errors.ForEach (err => doc.RemoveMarker (err)); - errors.Clear (); - } - - void UnderLineError (Document doc, Error info) - { - var line = doc.GetLine (info.Region.BeginLine); - // If the line is already underlined - if (errors.Any (em => em.LineSegment == line)) - return; - ErrorMarker error = new ErrorMarker (textEditor.Document, info, line); - errors.Add (error); - doc.AddMarker (line, error); - } - #endregion - - - Gtk.Paned splitContainer = null; + + Gtk.Paned splitContainer; + public bool IsSplitted { get { return splitContainer != null; @@ -763,7 +613,7 @@ namespace MonoDevelop.SourceEditor if (!textEditor.TextArea.HasFocus) OnLostFocus (); }; - splittedTextEditor.Extension = textEditor.Extension; + splittedTextEditor.EditorExtension = textEditor.EditorExtension; if (textEditor.GetTextEditorData ().HasIndentationTracker) splittedTextEditor.GetTextEditorData ().IndentationTracker = textEditor.GetTextEditorData ().IndentationTracker; splittedTextEditor.Document.BracketMatcher = textEditor.Document.BracketMatcher; @@ -969,20 +819,38 @@ namespace MonoDevelop.SourceEditor return "Unknown"; } - OverlayMessageWindow messageOverlayWindow; + //TODO: Support multiple Overlays at once to display above each other + internal void AddOverlay (Widget messageOverlayContent, Func<int> sizeFunc = null) + { + var messageOverlayWindow = new OverlayMessageWindow (); + messageOverlayWindow.Child = messageOverlayContent; + messageOverlayWindow.SizeFunc = sizeFunc; + messageOverlayWindow.ShowOverlay (TextEditor); + messageOverlayWindows.Add (messageOverlayWindow); + } + + internal void RemoveOverlay (Widget messageOverlayContent) + { + var window = messageOverlayWindows.FirstOrDefault (w => w.Child == messageOverlayContent); + if (window == null) + return; + messageOverlayWindows.Remove (window); + window.Destroy (); + } + + List<OverlayMessageWindow> messageOverlayWindows = new List<OverlayMessageWindow> (); + HBox incorrectEolMessage; void ShowIncorrectEolMarkers (string fileName, bool multiple) { RemoveMessageBar (); - messageOverlayWindow = new OverlayMessageWindow (); - var hbox = new HBox (); hbox.Spacing = 8; var image = new HoverCloseButton (); hbox.PackStart (image, false, false, 0); var label = new Label (string.Format ("This file has line endings ({0}) which differ from the policy settings ({1}).", GetEolString (DetectedEolMarker), GetEolString (textEditor.Options.DefaultEolMarker))); - var color = (Mono.TextEditor.HslColor)textEditor.ColorStyle.NotificationText.Foreground; + var color = (HslColor)textEditor.ColorStyle.NotificationText.Foreground; label.ModifyFg (StateType.Normal, color); int w, h; @@ -1007,11 +875,9 @@ namespace MonoDevelop.SourceEditor var combo = new ComboBox (list.ToArray ()); combo.Active = 0; hbox.PackEnd (combo, false, false, 0); - var container = new HBox (); + incorrectEolMessage = new HBox (); const int containerPadding = 8; - container.PackStart (hbox, true, true, containerPadding); - messageOverlayWindow.Child = container; - messageOverlayWindow.ShowOverlay (this.TextEditor); + incorrectEolMessage.PackStart (hbox, true, true, containerPadding); // This is hacky, but it will ensure that our combo appears with with the correct size. GLib.Timeout.Add (100, delegate { @@ -1019,14 +885,15 @@ namespace MonoDevelop.SourceEditor return false; }); - messageOverlayWindow.SizeFunc = () => { + AddOverlay (incorrectEolMessage, () => { return okButton.SizeRequest ().Width + - combo.SizeRequest ().Width + - image.SizeRequest ().Width + - w + - hbox.Spacing * 4 + - containerPadding * 2; - }; + combo.SizeRequest ().Width + + image.SizeRequest ().Width + + w + + hbox.Spacing * 4 + + containerPadding * 2; + }); + image.Clicked += delegate { UseIncorrectMarkers = true; view.WorkbenchWindow.ShowNotification = false; @@ -1086,11 +953,10 @@ namespace MonoDevelop.SourceEditor b2.Image = ImageService.GetImage (Gtk.Stock.RevertToSaved, IconSize.Button); b2.Clicked += delegate { try { - string content = AutoSave.LoadAutoSave (fileName); - AutoSave.RemoveAutoSaveFile (fileName); + var content = AutoSave.LoadAndRemoveAutoSave (fileName); TextEditor.GrabFocus (); view.Load (fileName); - view.ReplaceContent (fileName, content, view.SourceEncoding); + view.ReplaceContent (fileName, content.Text, view.SourceEncoding); view.WorkbenchWindow.Document.ReparseDocument (); view.IsDirty = true; } catch (Exception ex) { @@ -1125,9 +991,9 @@ namespace MonoDevelop.SourceEditor } if (!TextEditor.Visible) TextEditor.Visible = true; - if (messageOverlayWindow != null) { - messageOverlayWindow.Destroy (); - messageOverlayWindow = null; + if (incorrectEolMessage != null) { + RemoveOverlay (incorrectEolMessage); + incorrectEolMessage = null; } } @@ -1420,20 +1286,8 @@ namespace MonoDevelop.SourceEditor #region Help internal void MonodocResolver () { - DomRegion region; + MonoDevelop.Ide.Editor.DocumentRegion region; var res = TextEditor.GetLanguageItem (TextEditor.Caret.Offset, out region); - if (res is UnknownIdentifierResolveResult) { - var uir = (UnknownIdentifierResolveResult)res; - IdeApp.HelpOperations.SearchHelpFor (uir.Identifier); - return; - } - - if (res is UnknownMemberResolveResult) { - var uir = (UnknownMemberResolveResult)res; - IdeApp.HelpOperations.SearchHelpFor (uir.MemberName); - return; - } - string url = HelpService.GetMonoDocHelpUrl (res); if (url != null) IdeApp.HelpOperations.ShowHelp (url); @@ -1441,135 +1295,16 @@ namespace MonoDevelop.SourceEditor internal void MonodocResolverUpdate (CommandInfo cinfo) { - DomRegion region; + MonoDevelop.Ide.Editor.DocumentRegion region; var res = TextEditor.GetLanguageItem (TextEditor.Caret.Offset, out region); - if (res == null || !IdeApp.HelpOperations.CanShowHelp (res) && !(res is UnknownIdentifierResolveResult || res is UnknownMemberResolveResult)) + if (HelpService.GetMonoDocHelpUrl (res) == null) cinfo.Bypass = true; } #endregion #region commenting and indentation - internal void OnUpdateToggleComment (MonoDevelop.Components.Commands.CommandInfo info) - { - var mode = Document.SyntaxMode as SyntaxMode; - if (mode == null) { - info.Visible = false; - return; - } - List<string> lineComments; - if (mode.Properties.TryGetValue ("LineComment", out lineComments)) { - info.Visible = lineComments.Count > 0; - } else { - List<string> blockStarts; - List<string> blockEnds; - if (mode.Properties.TryGetValue ("BlockCommentStart", out blockStarts) && mode.Properties.TryGetValue ("BlockCommentEnd", out blockEnds)) { - info.Visible = blockStarts.Count > 0 && blockEnds.Count > 0; - } - } - } - - void ToggleCodeCommentWithBlockComments () - { - var mode = Document.SyntaxMode as SyntaxMode; - if (mode == null) - return; - - List<string> blockStarts; - if (!mode.Properties.TryGetValue ("BlockCommentStart", out blockStarts) || blockStarts.Count == 0) - return; - - List<string> blockEnds; - if (!mode.Properties.TryGetValue ("BlockCommentEnd", out blockEnds) || blockEnds.Count == 0) - return; - - string blockStart = blockStarts[0]; - string blockEnd = blockEnds[0]; - - using (var undo = Document.OpenUndoGroup ()) { - DocumentLine startLine; - DocumentLine endLine; - if (TextEditor.IsSomethingSelected) { - startLine = Document.GetLineByOffset (textEditor.SelectionRange.Offset); - endLine = Document.GetLineByOffset (textEditor.SelectionRange.EndOffset); - } else { - startLine = endLine = Document.GetLine (textEditor.Caret.Line); - } - string startLineText = Document.GetTextAt (startLine.Offset, startLine.Length); - string endLineText = Document.GetTextAt (endLine.Offset, endLine.Length); - if (startLineText.StartsWith (blockStart) && endLineText.EndsWith (blockEnd, StringComparison.Ordinal)) { - textEditor.Remove (endLine.Offset + endLine.Length - blockEnd.Length, blockEnd.Length); - textEditor.Remove (startLine.Offset, blockStart.Length); - if (TextEditor.IsSomethingSelected) { - TextEditor.SelectionAnchor -= blockEnd.Length; - } - } else { - textEditor.Insert (endLine.Offset + endLine.Length, blockEnd); - textEditor.Insert (startLine.Offset, blockStart); - if (TextEditor.IsSomethingSelected) { - TextEditor.SelectionAnchor += blockEnd.Length; - } - - } - } - } - - bool TryGetLineCommentTag (out string commentTag) - { - var mode = Document.SyntaxMode as SyntaxMode; - List<string> lineComments; - if (mode == null || !mode.Properties.TryGetValue ("LineComment", out lineComments) || lineComments.Count == 0) { - commentTag = null; - return false; - } - commentTag = lineComments [0]; - return true; - } - - public void ToggleCodeComment () - { - string commentTag; - if (!TryGetLineCommentTag (out commentTag)) { - ToggleCodeCommentWithBlockComments (); - return; - } - - bool comment = false; - foreach (var line in textEditor.SelectedLines) { - if (line.GetIndentation (TextEditor.Document).Length == line.Length) - continue; - string text = Document.GetTextAt (line); - string trimmedText = text.TrimStart (); - if (!trimmedText.StartsWith (commentTag, StringComparison.Ordinal)) { - comment = true; - break; - } - } - - if (comment) { - CommentSelectedLines (commentTag); - } else { - UncommentSelectedLines (commentTag); - } - } - - public void AddCodeComment () - { - string commentTag; - if (!TryGetLineCommentTag (out commentTag)) - return; - CommentSelectedLines (commentTag); - } - - public void RemoveCodeComment () - { - string commentTag; - if (!TryGetLineCommentTag (out commentTag)) - return; - UncommentSelectedLines (commentTag); - } - public void OnUpdateToggleErrorTextMarker (CommandInfo info) { DocumentLine line = TextEditor.Document.GetLine (TextEditor.Caret.Line); @@ -1592,81 +1327,7 @@ namespace MonoDevelop.SourceEditor TextEditor.QueueDraw (); } } - - void CommentSelectedLines (string commentTag) - { - int startLineNr = TextEditor.IsSomethingSelected ? Document.OffsetToLineNumber (TextEditor.SelectionRange.Offset) : TextEditor.Caret.Line; - int endLineNr = TextEditor.IsSomethingSelected ? Document.OffsetToLineNumber (TextEditor.SelectionRange.EndOffset) : TextEditor.Caret.Line; - if (endLineNr < 0) - endLineNr = Document.LineCount; - - DocumentLine anchorLine = TextEditor.IsSomethingSelected ? TextEditor.Document.GetLineByOffset (TextEditor.SelectionAnchor) : null; - int anchorColumn = TextEditor.IsSomethingSelected ? TextEditor.SelectionAnchor - anchorLine.Offset : -1; - - using (var undo = Document.OpenUndoGroup ()) { - foreach (DocumentLine line in TextEditor.SelectedLines) { -// if (line.GetIndentation (TextEditor.Document).Length == line.EditableLength) -// continue; - TextEditor.Insert (line.Offset, commentTag); - } - if (TextEditor.IsSomethingSelected) { - if (TextEditor.SelectionAnchor < TextEditor.Caret.Offset) { - if (anchorColumn != 0) - TextEditor.SelectionAnchor = System.Math.Min (anchorLine.Offset + anchorLine.Length, System.Math.Max (anchorLine.Offset, TextEditor.SelectionAnchor + commentTag.Length)); - } else { - if (anchorColumn != 0) { - TextEditor.SelectionAnchor = System.Math.Min (anchorLine.Offset + anchorLine.Length, System.Math.Max (anchorLine.Offset, anchorLine.Offset + anchorColumn + commentTag.Length)); - } else { - // TextEditor.SelectionAnchor = anchorLine.Offset; - } - } - } - - if (TextEditor.IsSomethingSelected) - TextEditor.ExtendSelectionTo (TextEditor.Caret.Offset); - } - Document.CommitMultipleLineUpdate (startLineNr, endLineNr); - } - - void UncommentSelectedLines (string commentTag) - { - int startLineNr = TextEditor.IsSomethingSelected ? Document.OffsetToLineNumber (TextEditor.SelectionRange.Offset) : TextEditor.Caret.Line; - int endLineNr = TextEditor.IsSomethingSelected ? Document.OffsetToLineNumber (TextEditor.SelectionRange.EndOffset) : TextEditor.Caret.Line; - if (endLineNr < 0) - endLineNr = Document.LineCount; - DocumentLine anchorLine = TextEditor.IsSomethingSelected ? TextEditor.Document.GetLineByOffset (TextEditor.SelectionAnchor) : null; - int anchorColumn = TextEditor.IsSomethingSelected ? TextEditor.SelectionAnchor - anchorLine.Offset : -1; - - using (var undo = Document.OpenUndoGroup ()) { - int first = -1; - int last = 0; - foreach (DocumentLine line in TextEditor.SelectedLines) { - string text = Document.GetTextAt (line); - string trimmedText = text.TrimStart (); - int length = 0; - if (trimmedText.StartsWith (commentTag)) { - TextEditor.Remove (line.Offset + (text.Length - trimmedText.Length), commentTag.Length); - length = commentTag.Length; - } - last = length; - if (first < 0) - first = last; - } - - if (TextEditor.IsSomethingSelected) { - if (TextEditor.SelectionAnchor < TextEditor.Caret.Offset) { - TextEditor.SelectionAnchor = System.Math.Min (anchorLine.Offset + anchorLine.Length, System.Math.Max (anchorLine.Offset, TextEditor.SelectionAnchor - first)); - } else { - TextEditor.SelectionAnchor = System.Math.Min (anchorLine.Offset + anchorLine.Length, System.Math.Max (anchorLine.Offset, anchorLine.Offset + anchorColumn - last)); - } - } - - if (TextEditor.IsSomethingSelected) - TextEditor.ExtendSelectionTo (TextEditor.Caret.Offset); - } - Document.CommitMultipleLineUpdate (startLineNr, endLineNr); - } - + #endregion #region IQuickTaskProvider implementation @@ -1687,17 +1348,17 @@ namespace MonoDevelop.SourceEditor } } - void UpdateQuickTasks (ParsedDocument doc) + async void UpdateQuickTasks (ParsedDocument doc) { tasks.Clear (); if (doc != null) { - foreach (var cmt in doc.TagComments) { - var newTask = new QuickTask (cmt.Text, cmt.Region.Begin, Severity.Hint); + foreach (var cmt in await doc.GetTagCommentsAsync()) { + var newTask = new QuickTask (cmt.Text, textEditor.LocationToOffset (cmt.Region.Begin.Line, cmt.Region.Begin.Column), DiagnosticSeverity.Info); tasks.Add (newTask); } - foreach (var error in doc.Errors) { - var newTask = new QuickTask (error.Message, error.Region.Begin, error.ErrorType == ErrorType.Error ? Severity.Error : Severity.Warning); + foreach (var error in await doc.GetErrorsAsync()) { + var newTask = new QuickTask (error.Message, textEditor.LocationToOffset (error.Region.Begin.Line, error.Region.Begin.Column), error.ErrorType == MonoDevelop.Ide.TypeSystem.ErrorType.Error ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning); tasks.Add (newTask); } } @@ -1734,56 +1395,12 @@ namespace MonoDevelop.SourceEditor } - } - - class ErrorMarker : UnderlineMarker - { - public Error Info { get; private set; } - - public ErrorMarker (TextDocument doc, Error info, DocumentLine line) - { - Info = info; - LineSegment = line; - // may be null if no line is assigned to the error. - Wave = true; - - StartCol = Info.Region.BeginColumn; - if (line != null) { - var startOffset = line.Offset; - if (startOffset + StartCol - 1 >= 0) { - while (StartCol < line.Length) { - char ch = doc.GetCharAt (startOffset + StartCol - 1); - if (!char.IsWhiteSpace (ch)) - break; - StartCol++; - } - } - } - - if (Info.Region.EndColumn > StartCol) { - EndCol = Info.Region.EndColumn; - } else { - if (line == null) { - EndCol = StartCol + 1; - return; - } - var start = line.Offset + StartCol - 1; - int o = start + 1; - while (o < line.EndOffset) { - char ch = doc.GetCharAt (o); - if (!(char.IsLetterOrDigit (ch) || ch == '_')) - break; - o++; - } - EndCol = Info.Region.BeginColumn + o - start + 1; - } - } - - public override void Draw (TextEditor editor, Cairo.Context cr, double y, LineMetrics metrics) + #region IServiceProvider implementation + object IServiceProvider.GetService (Type serviceType) { - Color = Info.ErrorType == ErrorType.Warning ? editor.ColorStyle.UnderlineWarning.Color : editor.ColorStyle.UnderlineError.Color; - - base.Draw (editor, cr, y, metrics); + return view.GetContent (serviceType); } + #endregion } + } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/StyledSourceEditorOptions.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/StyledSourceEditorOptions.cs index 01d4f54f65..7e46cb6ac9 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/StyledSourceEditorOptions.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/StyledSourceEditorOptions.cs @@ -25,350 +25,302 @@ // THE SOFTWARE. using System; -using System.Collections.Generic; -using MonoDevelop.Projects; -using MonoDevelop.Projects.Policies; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Ide; using Mono.TextEditor; +using MonoDevelop.Ide.Editor; namespace MonoDevelop.SourceEditor { - - internal class StyledSourceEditorOptions : ISourceEditorOptions + class StyledSourceEditorOptions : TextEditorOptions { - PolicyContainer policyContainer; - EventHandler changed; - IEnumerable<string> mimeTypes; - TextStylePolicy currentPolicy; - string lastMimeType; + MonoDevelop.Ide.Editor.ITextEditorOptions optionsCore; - public StyledSourceEditorOptions (Project styleParent, string mimeType) - { - UpdateStyleParent (styleParent, mimeType); + public MonoDevelop.Ide.Editor.ITextEditorOptions OptionsCore { + get { + return optionsCore; + } + set { + optionsCore = value; + OnChanged (EventArgs.Empty); + } } - - TextStylePolicy CurrentPolicy { - get { return currentPolicy; } + + public StyledSourceEditorOptions (MonoDevelop.Ide.Editor.ITextEditorOptions optionsCore) + { + if (optionsCore == null) + throw new ArgumentNullException ("optionsCore"); + this.optionsCore = optionsCore; + DefaultSourceEditorOptions.Instance.Changed += HandleChanged; } - - public void UpdateStyleParent (Project styleParent, string mimeType) + public override void Dispose () { - if (styleParent != null && policyContainer == styleParent.Policies && mimeType == lastMimeType) - return; - lastMimeType = mimeType; - - if (policyContainer != null) - policyContainer.PolicyChanged -= HandlePolicyChanged; - - if (string.IsNullOrEmpty (mimeType)) - mimeType = "text/plain"; - this.mimeTypes = DesktopService.GetMimeTypeInheritanceChain (mimeType); - - if (styleParent != null) - policyContainer = styleParent.Policies; - else - policyContainer = MonoDevelop.Projects.Policies.PolicyService.DefaultPolicies; - currentPolicy = policyContainer.Get<TextStylePolicy> (mimeTypes); - - policyContainer.PolicyChanged += HandlePolicyChanged; - if (changed != null) - this.changed (this, EventArgs.Empty); + DefaultSourceEditorOptions.Instance.Changed -= HandleChanged; + + base.Dispose (); } - void HandlePolicyChanged (object sender, MonoDevelop.Projects.Policies.PolicyChangedEventArgs args) + void HandleChanged (object sender, EventArgs e) { - currentPolicy = policyContainer.Get<TextStylePolicy> (mimeTypes); - if (changed != null) - this.changed (this, EventArgs.Empty); + DisposeFont (); + OnChanged (EventArgs.Empty); } - public bool OverrideDocumentEolMarker { - get { return DefaultSourceEditorOptions.Instance.OverrideDocumentEolMarker; } + #region ITextEditorOptions implementation + static IWordFindStrategy monoDevelopWordFindStrategy = new EmacsWordFindStrategy (false); + static IWordFindStrategy emacsWordFindStrategy = new EmacsWordFindStrategy (true); + static IWordFindStrategy sharpDevelopWordFindStrategy = new SharpDevelopWordFindStrategy (); + static IWordFindStrategy viWordFindStrategy = new Mono.TextEditor.Vi.ViWordFindStrategy (); + + public override IWordFindStrategy WordFindStrategy { + get { + switch (DefaultSourceEditorOptions.Instance.WordFindStrategy) { + case MonoDevelop.Ide.Editor.WordFindStrategy.MonoDevelop: + return monoDevelopWordFindStrategy; + case MonoDevelop.Ide.Editor.WordFindStrategy.Emacs: + return emacsWordFindStrategy; + case MonoDevelop.Ide.Editor.WordFindStrategy.SharpDevelop: + return sharpDevelopWordFindStrategy; + case MonoDevelop.Ide.Editor.WordFindStrategy.Vim: + return viWordFindStrategy; + default: + throw new ArgumentOutOfRangeException (); + } + } set { - throw new NotSupportedException (); + throw new NotImplementedException (); } } - - public string DefaultEolMarker { - get { return TextStylePolicy.GetEolMarker (CurrentPolicy.EolMarker); } + + public override bool AllowTabsAfterNonTabs { + get { + return DefaultSourceEditorOptions.Instance.AllowTabsAfterNonTabs; + } set { throw new NotSupportedException (); } } - public int RulerColumn { - get { return CurrentPolicy.FileWidth; } + public override bool HighlightMatchingBracket { + get { + return DefaultSourceEditorOptions.Instance.HighlightMatchingBracket; + } set { throw new NotSupportedException (); } } - public int TabSize { - get { return CurrentPolicy.TabWidth; } + public override bool TabsToSpaces { + get { + return optionsCore.TabsToSpaces; + } set { throw new NotSupportedException (); } } - public bool TabsToSpaces { - get { return CurrentPolicy.TabsToSpaces; } + public override int IndentationSize { + get { + return optionsCore.IndentationSize; + } set { throw new NotSupportedException (); } } - public bool RemoveTrailingWhitespaces { - get { return CurrentPolicy.RemoveTrailingWhitespace; } + public override int TabSize { + get { + return optionsCore.TabSize; + } set { throw new NotSupportedException (); } } - public bool AllowTabsAfterNonTabs { - get { return !CurrentPolicy.NoTabsAfterNonTabs; } + + public override bool ShowIconMargin { + get { + return optionsCore.ShowIconMargin; + } set { throw new NotSupportedException (); } } - public int IndentationSize { - get { return CurrentPolicy.IndentWidth; } + public override bool ShowLineNumberMargin { + get { + return optionsCore.ShowLineNumberMargin; + } set { throw new NotSupportedException (); } } - public string IndentationString { - get { return this.TabsToSpaces ? new string (' ', this.TabSize) : "\t"; } - } - - #region ITextEditorOptions implementation - - public bool CanResetZoom { - get { return DefaultSourceEditorOptions.Instance.CanResetZoom; } - } - - public bool CanZoomIn { - get { return DefaultSourceEditorOptions.Instance.CanZoomIn; } - } - - public bool CanZoomOut { - get { return DefaultSourceEditorOptions.Instance.CanZoomOut; } - } - - public event EventHandler Changed { - add { - if (changed == null) - DefaultSourceEditorOptions.Instance.Changed += HandleDefaultsChanged; - changed += value; + public override bool ShowFoldMargin { + get { + return optionsCore.ShowFoldMargin; } - remove { - changed -= value; - if (changed == null) - DefaultSourceEditorOptions.Instance.Changed -= HandleDefaultsChanged; + set { + throw new NotSupportedException (); } } - void HandleDefaultsChanged (object sender, EventArgs e) - { - if (changed != null) - changed (this, EventArgs.Empty); - } - - public string ColorScheme { - get { return DefaultSourceEditorOptions.Instance.ColorScheme; } - set { throw new NotSupportedException (); } - } - - public bool EnableSyntaxHighlighting { - get { return DefaultSourceEditorOptions.Instance.EnableSyntaxHighlighting; } - set { throw new NotSupportedException (); } - } - - public Pango.FontDescription Font { - get { return DefaultSourceEditorOptions.Instance.Font; } - } - - public string FontName { - get { return DefaultSourceEditorOptions.Instance.FontName; } - set { throw new NotSupportedException (); } - } - - public Pango.FontDescription GutterFont { - get { return DefaultSourceEditorOptions.Instance.GutterFont; } - } - - public string GutterFontName { - get { return DefaultSourceEditorOptions.Instance.GutterFontName; } - set { throw new NotSupportedException (); } - } - - public Mono.TextEditor.Highlighting.ColorScheme GetColorStyle () - { - return DefaultSourceEditorOptions.Instance.GetColorStyle (); - } - - public bool HighlightCaretLine { - get { return DefaultSourceEditorOptions.Instance.HighlightCaretLine; } - set { throw new NotSupportedException (); } - } - - public bool HighlightMatchingBracket { - get { return DefaultSourceEditorOptions.Instance.HighlightMatchingBracket; } - set { throw new NotSupportedException (); } - } - - public bool ShowFoldMargin { - get { return DefaultSourceEditorOptions.Instance.ShowFoldMargin; } - set { throw new NotSupportedException (); } - } - - public bool ShowIconMargin { - get { return DefaultSourceEditorOptions.Instance.ShowIconMargin; } - set { throw new NotSupportedException (); } - } - - public bool ShowLineNumberMargin { - get { return DefaultSourceEditorOptions.Instance.ShowLineNumberMargin; } - set { throw new NotSupportedException (); } - } - - public bool ShowRuler { - get { return DefaultSourceEditorOptions.Instance.ShowRuler; } - set { throw new NotSupportedException (); } - } - - public bool EnableAnimations { - get { return DefaultSourceEditorOptions.Instance.EnableAnimations; } - set { throw new NotSupportedException (); } - } - - public Mono.TextEditor.IWordFindStrategy WordFindStrategy { - get { return DefaultSourceEditorOptions.Instance.WordFindStrategy; } - set { throw new NotSupportedException (); } - } - - public double Zoom { - get { return DefaultSourceEditorOptions.Instance.Zoom; } - set { DefaultSourceEditorOptions.Instance.Zoom = value; } - } - - public bool DrawIndentationMarkers { - get { return DefaultSourceEditorOptions.Instance.DrawIndentationMarkers; } - set { DefaultSourceEditorOptions.Instance.DrawIndentationMarkers = value; } - } - - public ShowWhitespaces ShowWhitespaces { - get { return DefaultSourceEditorOptions.Instance.ShowWhitespaces; } - set { DefaultSourceEditorOptions.Instance.ShowWhitespaces = value; } - } - - public IncludeWhitespaces IncludeWhitespaces { - get { return DefaultSourceEditorOptions.Instance.IncludeWhitespaces; } - set { DefaultSourceEditorOptions.Instance.IncludeWhitespaces = value; } - } - - public bool WrapLines { - get { return DefaultSourceEditorOptions.Instance.WrapLines; } - set { DefaultSourceEditorOptions.Instance.WrapLines = value; } + public override bool HighlightCaretLine { + get { + return optionsCore.HighlightCaretLine; + } + set { + throw new NotSupportedException (); + } } - public bool EnableQuickDiff { - get { return DefaultSourceEditorOptions.Instance.EnableQuickDiff; } - set { DefaultSourceEditorOptions.Instance.EnableQuickDiff = value; } + public override int RulerColumn { + get { + return optionsCore.RulerColumn; + } + set { + throw new NotSupportedException (); + } } - public bool GenerateFormattingUndoStep { - get { return DefaultSourceEditorOptions.Instance.GenerateFormattingUndoStep; } - set { DefaultSourceEditorOptions.Instance.GenerateFormattingUndoStep = value; } + public override bool ShowRuler { + get { + return optionsCore.ShowRuler; + } + set { + throw new NotSupportedException (); + } } - public void ZoomIn () - { - DefaultSourceEditorOptions.Instance.ZoomIn (); + public override Mono.TextEditor.IndentStyle IndentStyle { + get { + if (optionsCore.IndentStyle == MonoDevelop.Ide.Editor.IndentStyle.Smart && optionsCore.RemoveTrailingWhitespaces) + return Mono.TextEditor.IndentStyle.Virtual; + return (Mono.TextEditor.IndentStyle)optionsCore.IndentStyle; + } + set { + throw new NotSupportedException (); + } } - public void ZoomOut () - { - DefaultSourceEditorOptions.Instance.ZoomOut (); + public override bool OverrideDocumentEolMarker { + get { + return optionsCore.OverrideDocumentEolMarker; + } + set { + throw new NotSupportedException (); + } } - public void ZoomReset () - { - DefaultSourceEditorOptions.Instance.ZoomReset (); + public override bool EnableSyntaxHighlighting { + get { + return optionsCore.EnableSyntaxHighlighting; + } + set { + throw new NotSupportedException (); + } } - #endregion - - - #region ISourceEditorOptions implementation - - public bool AutoInsertMatchingBracket { - get { return DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket; } + public override bool EnableAnimations { + get { + return DefaultSourceEditorOptions.Instance.HighlightMatchingBracket; + } + set { + throw new NotSupportedException (); + } } - public bool DefaultCommentFolding { - get { return DefaultSourceEditorOptions.Instance.DefaultCommentFolding; } + public override bool EnableQuickDiff { + get { + return DefaultSourceEditorOptions.Instance.EnableQuickDiff; + } + set { + throw new NotSupportedException (); + } } - public bool DefaultRegionsFolding { - get { return DefaultSourceEditorOptions.Instance.DefaultRegionsFolding; } + public override bool DrawIndentationMarkers { + get { + return DefaultSourceEditorOptions.Instance.DrawIndentationMarkers; + } + set { + throw new NotSupportedException (); + } } - public EditorFontType EditorFontType { - get { return DefaultSourceEditorOptions.Instance.EditorFontType; } + public override bool WrapLines { + get { + return optionsCore.WrapLines; + } + set { + throw new NotSupportedException (); + } } - public bool EnableAutoCodeCompletion { - get { return DefaultSourceEditorOptions.Instance.EnableAutoCodeCompletion; } + public override string FontName { + get { + return optionsCore.FontName; + } + set { + throw new NotSupportedException (); + } } - public bool EnableSemanticHighlighting { - get { return DefaultSourceEditorOptions.Instance.EnableSemanticHighlighting; } + public override string GutterFontName { + get { + return optionsCore.GutterFontName; + } + set { + throw new NotSupportedException (); + } } - public IndentStyle IndentStyle { + public override string ColorScheme { get { - if ((DefaultSourceEditorOptions.Instance.IndentStyle == Mono.TextEditor.IndentStyle.Smart || - DefaultSourceEditorOptions.Instance.IndentStyle == Mono.TextEditor.IndentStyle.Auto) && CurrentPolicy.RemoveTrailingWhitespace) - return IndentStyle.Virtual; - return DefaultSourceEditorOptions.Instance.IndentStyle; + return optionsCore.ColorScheme; } set { - throw new NotSupportedException ("Use property 'IndentStyle' instead."); + throw new NotSupportedException (); } } - public bool TabIsReindent { - get { return DefaultSourceEditorOptions.Instance.TabIsReindent; } + public override string DefaultEolMarker { + get { + return optionsCore.DefaultEolMarker; + } + set { + throw new NotSupportedException (); + } } - public bool UnderlineErrors { - get { return DefaultSourceEditorOptions.Instance.UnderlineErrors; } + public override Mono.TextEditor.ShowWhitespaces ShowWhitespaces { + get { + return (Mono.TextEditor.ShowWhitespaces)optionsCore.ShowWhitespaces; + } + set { + throw new NotSupportedException (); + } } - public bool UseViModes { - get { return DefaultSourceEditorOptions.Instance.UseViModes; } + public override Mono.TextEditor.IncludeWhitespaces IncludeWhitespaces { + get { + return (Mono.TextEditor.IncludeWhitespaces)optionsCore.IncludeWhitespaces; + } + set { + throw new NotSupportedException (); + } } - public bool EnableSelectionWrappingKeys { - get { return DefaultSourceEditorOptions.Instance.AutoInsertMatchingBracket; } + public override bool GenerateFormattingUndoStep { + get { + return optionsCore.GenerateFormattingUndoStep; + } + set { + throw new NotSupportedException (); + } } - #endregion - public void Dispose () - { - mimeTypes = null; - if (policyContainer != null) - policyContainer.PolicyChanged -= HandlePolicyChanged; - if (changed != null) { - DefaultSourceEditorOptions.Instance.Changed -= HandleDefaultsChanged; - changed = null; - } - } + } } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SyntaxModeLoader.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SyntaxModeLoader.cs new file mode 100644 index 0000000000..2f2e1c8f73 --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SyntaxModeLoader.cs @@ -0,0 +1,68 @@ +// +// SyntaxModeLoader.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2015 Xamarin Inc. (http://xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System.IO; +using Mono.Addins; +using MonoDevelop.Ide.Editor.Highlighting; + +namespace MonoDevelop.SourceEditor +{ + static class SyntaxModeLoader + { + static bool initialized = false; + + public static void Init () + { + if (initialized) + return; + initialized = true; + AddinManager.AddExtensionNodeHandler ("/MonoDevelop/SourceEditor2/SyntaxModes", OnSyntaxModeExtensionChanged); + } + + static void OnSyntaxModeExtensionChanged (object s, ExtensionNodeEventArgs args) + { + TemplateCodon codon = (TemplateCodon)args.ExtensionNode; + if (args.Change == ExtensionChange.Add) { + Mono.TextEditor.Highlighting.SyntaxModeService.AddSyntaxMode (new StreamProviderWrapper(codon)); + } + } + + class StreamProviderWrapper : Mono.TextEditor.Highlighting.IStreamProvider + { + readonly TemplateCodon codon; + + public StreamProviderWrapper (TemplateCodon codon) + { + this.codon = codon; + } + + Stream Mono.TextEditor.Highlighting.IStreamProvider.Open () + { + return codon.Open (); + } + } + } +}
\ No newline at end of file diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SyntaxModeCodon.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/AsmLineMarker.cs index f7339614c3..cd743619e6 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/SyntaxModeCodon.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/AsmLineMarker.cs @@ -1,21 +1,21 @@ -// -// SyntaxModeCodon.cs -// +// +// AsmLineMarker.cs +// // Author: -// Mike Krüger <mkrueger@novell.com> +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) // -// Copyright (c) 2009 Novell, Inc (http://www.novell.com) -// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,30 +23,26 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. - -using System; +using Mono.TextEditor; +using MonoDevelop.SourceEditor.Wrappers; using Mono.TextEditor.Highlighting; -using Mono.Addins; - namespace MonoDevelop.SourceEditor { - [ExtensionNode (Description="A syntax mode. The specified class must be a valid syntax mode.")] - class SyntaxModeCodon : TypeExtensionNode + class AsmLineMarker: TextLineMarker, MonoDevelop.Ide.Editor.ITextLineMarker { - [NodeAttribute ("mimeTypes", true, "Mime types of the syntax mode.")] - string mimeTypes = null; - - public SyntaxMode SyntaxMode { - get { - return CreateInstance () as SyntaxMode; - } + public override ChunkStyle GetStyle (ChunkStyle baseStyle) + { + var st = new ChunkStyle (baseStyle); + st.Foreground = new Cairo.Color (125, 125, 125); + return st; } - public string MimeTypes { + MonoDevelop.Ide.Editor.IDocumentLine MonoDevelop.Ide.Editor.ITextLineMarker.Line { get { - return mimeTypes; + return new DocumentLineWrapper (LineSegment); } } } } + diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/DebugTextMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/DebugTextMarker.cs new file mode 100644 index 0000000000..d6e339ea03 --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/DebugTextMarker.cs @@ -0,0 +1,288 @@ +// DebugTextMarker.cs +// +// Authors: Lluis Sanchez Gual <lluis@novell.com> +// Jeffrey Stedfast <jeff@xamarin.com> +// +// Copyright (c) 2008 Novell, Inc (http://www.novell.com) +// Copyright (c) 2013 Xamarin Inc. (http://www.xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +// +// + +using System; +using System.Linq; +using Mono.TextEditor; +using Mono.TextEditor.Highlighting; +using MonoDevelop.SourceEditor.Wrappers; +using MonoDevelop.Components; + +using Xwt.Drawing; +using MonoDevelop.Debugger; + +namespace MonoDevelop.SourceEditor +{ + abstract class DebugTextMarker : MarginMarker + { + protected DebugTextMarker (MonoTextEditor editor) + { + Editor = editor; + } + + protected abstract Cairo.Color BackgroundColor { + get; + } + + protected abstract Cairo.Color BorderColor { + get; + } + + protected Cairo.Color GetBorderColor (AmbientColor color) + { + if (color.HasBorderColor) + return color.BorderColor; + return color.Color; + } + + protected MonoTextEditor Editor { + get; private set; + } + + public override bool CanDrawBackground (Margin margin) + { + return margin is TextViewMargin; + } + + public override bool CanDrawForeground (Margin margin) + { + return margin is IconMargin; + } + + public override bool DrawBackground (MonoTextEditor editor, Cairo.Context cr, LineMetrics metrics) + { + // check, if a message bubble is active in that line. + if (LineSegment != null && LineSegment.Markers.Any (m => m != this && (m is IExtendingTextLineMarker))) + return false; + + var sidePadding = 4; + var rounding = editor.LineHeight / 2 - 1; + var y = metrics.LineYRenderStartPosition; + var d = metrics.TextRenderEndPosition - metrics.TextRenderStartPosition; + if (d > 0) { + cr.LineWidth = 1; + cr.RoundedRectangle (metrics.TextRenderStartPosition, Math.Floor (y) + 0.5, d + sidePadding, metrics.LineHeight - 1, rounding); + cr.SetSourceColor (BackgroundColor); + cr.FillPreserve (); + cr.SetSourceColor (BorderColor); + cr.Stroke (); + } + + return base.DrawBackground (editor, cr, metrics); + } + + public override void DrawForeground (MonoTextEditor editor, Cairo.Context cr, MarginDrawMetrics metrics) + { + double size = metrics.Margin.Width; + double borderLineWidth = cr.LineWidth; + + double x = Math.Floor (metrics.Margin.XOffset - borderLineWidth / 2); + double y = Math.Floor (metrics.Y + (metrics.Height - size) / 2); + + DrawMarginIcon (cr, x, y, size); + } + + protected virtual void SetForegroundColor (ChunkStyle style) + { + } + + public override ChunkStyle GetStyle (ChunkStyle baseStyle) + { + if (baseStyle == null) + return null; + + var style = new ChunkStyle (baseStyle); + // style.Background = BackgroundColor; + SetForegroundColor (style); + + return style; + } + + protected void DrawImage (Cairo.Context cr, Image image, double x, double y, double size) + { + var deltaX = size / 2 - image.Width / 2 + 0.5f; + var deltaY = size / 2 - image.Height / 2 + 0.5f; + + cr.DrawImage (Editor, image, Math.Round (x + deltaX), Math.Round (y + deltaY)); + } + + protected virtual void DrawMarginIcon (Cairo.Context cr, double x, double y, double size) + { + } + } + + class BreakpointTextMarker : DebugTextMarker + { + static readonly Image breakpoint = Image.FromResource (typeof(BreakpointPad), "gutter-breakpoint-15.png"); + static readonly Image tracepoint = Image.FromResource (typeof(BreakpointPad), "gutter-tracepoint-15.png"); + + public BreakpointTextMarker (MonoTextEditor editor, bool tracepoint) : base (editor) + { + IsTracepoint = tracepoint; + } + + public bool IsTracepoint { + get; private set; + } + + protected override Cairo.Color BackgroundColor { + get { return Editor.ColorStyle.BreakpointMarker.Color; } + } + + protected override Cairo.Color BorderColor { + get { return GetBorderColor (Editor.ColorStyle.BreakpointMarker); } + } + + protected override void SetForegroundColor (ChunkStyle style) + { + style.Foreground = Editor.ColorStyle.BreakpointText.Foreground; + } + + protected override void DrawMarginIcon (Cairo.Context cr, double x, double y, double size) + { + DrawImage (cr, IsTracepoint ? tracepoint : breakpoint, x, y, size); + } + } + + class DisabledBreakpointTextMarker : DebugTextMarker + { + static readonly Image breakpoint = Image.FromResource (typeof(BreakpointPad), "gutter-breakpoint-disabled-15.png"); + static readonly Image tracepoint = Image.FromResource (typeof(BreakpointPad), "gutter-tracepoint-disabled-15.png"); + + public DisabledBreakpointTextMarker (MonoTextEditor editor, bool tracepoint) : base (editor) + { + IsTracepoint = tracepoint; + } + + public bool IsTracepoint { + get; private set; + } + + protected override Cairo.Color BackgroundColor { + get { return Editor.ColorStyle.BreakpointMarkerDisabled.Color; } + } + + protected override Cairo.Color BorderColor { + get { return GetBorderColor (Editor.ColorStyle.BreakpointMarkerDisabled); } + } + + protected override void DrawMarginIcon (Cairo.Context cr, double x, double y, double size) + { + DrawImage (cr, IsTracepoint ? tracepoint : breakpoint, x, y, size); + } + } + + class InvalidBreakpointTextMarker : DebugTextMarker + { + static readonly Image breakpoint = Image.FromResource (typeof(BreakpointPad), "gutter-breakpoint-invalid-15.png"); + static readonly Image tracepoint = Image.FromResource (typeof(BreakpointPad), "gutter-tracepoint-invalid-15.png"); + + public InvalidBreakpointTextMarker (MonoTextEditor editor, bool tracepoint) : base (editor) + { + IsTracepoint = tracepoint; + } + + public bool IsTracepoint { + get; private set; + } + + protected override Cairo.Color BackgroundColor { + get { return Editor.ColorStyle.BreakpointMarkerInvalid.Color; } + } + + protected override Cairo.Color BorderColor { + get { return GetBorderColor (Editor.ColorStyle.BreakpointMarkerInvalid); } + } + + protected override void DrawMarginIcon (Cairo.Context cr, double x, double y, double size) + { + DrawImage (cr, IsTracepoint ? tracepoint : breakpoint, x, y, size); + } + } + + class CurrentDebugLineTextMarker : DebugTextMarker, MonoDevelop.Ide.Editor.ICurrentDebugLineTextMarker + { + static readonly Image currentLine = Image.FromResource (typeof(BreakpointPad), "gutter-execution-15.png"); + + public CurrentDebugLineTextMarker (MonoTextEditor editor) : base (editor) + { + } + + protected override Cairo.Color BackgroundColor { + get { return Editor.ColorStyle.DebuggerCurrentLineMarker.Color; } + } + + protected override Cairo.Color BorderColor { + get { return GetBorderColor (Editor.ColorStyle.DebuggerCurrentLineMarker); } + } + + protected override void SetForegroundColor (ChunkStyle style) + { + style.Foreground = Editor.ColorStyle.DebuggerCurrentLine.Foreground; + } + + protected override void DrawMarginIcon (Cairo.Context cr, double x, double y, double size) + { + DrawImage (cr, currentLine, x, y, size); + } + + MonoDevelop.Ide.Editor.IDocumentLine MonoDevelop.Ide.Editor.ITextLineMarker.Line { + get { + return new DocumentLineWrapper (base.LineSegment); + } + } + } + + class DebugStackLineTextMarker : DebugTextMarker + { + static readonly Image stackLine = Image.FromResource (typeof(BreakpointPad), "gutter-stack-15.png"); + + public DebugStackLineTextMarker (MonoTextEditor editor) : base (editor) + { + } + + protected override Cairo.Color BackgroundColor { + get { return Editor.ColorStyle.DebuggerStackLineMarker.Color; } + } + + protected override Cairo.Color BorderColor { + get { return GetBorderColor (Editor.ColorStyle.DebuggerStackLineMarker); } + } + + protected override void SetForegroundColor (ChunkStyle style) + { + style.Foreground = Editor.ColorStyle.DebuggerStackLine.Foreground; + } + + protected override void DrawMarginIcon (Cairo.Context cr, double x, double y, double size) + { + DrawImage (cr, stackLine, x, y, size); + } + } + +} diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/ErrorMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/ErrorMarker.cs new file mode 100644 index 0000000000..19067b2026 --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/ErrorMarker.cs @@ -0,0 +1,81 @@ +// +// ErrorMarker.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using Mono.TextEditor; +using MonoDevelop.Ide.Editor; +using MonoDevelop.Ide.TypeSystem; + +namespace MonoDevelop.SourceEditor +{ + class ErrorMarker : UnderlineTextSegmentMarker, IErrorMarker + { + readonly static Cairo.Color defaultColor = new Cairo.Color(0, 0, 0); + + readonly Error info; + + public ErrorMarker (Error info, int offset, int length) : base (defaultColor, new TextSegment (offset, length)) + { + this.info = info; + this.Wave = true; + } + + public override void Draw (Mono.TextEditor.MonoTextEditor editor, Cairo.Context cr, LineMetrics metrics, int startOffset, int endOffset) + { + Color = info.ErrorType == ErrorType.Warning ? editor.ColorStyle.UnderlineWarning.Color : editor.ColorStyle.UnderlineError.Color; + base.Draw (editor, cr, metrics, startOffset, endOffset); + } + + event EventHandler<TextMarkerMouseEventArgs> ITextSegmentMarker.MousePressed { + add { + throw new NotImplementedException (); + } + remove { + throw new NotImplementedException (); + } + } + + event EventHandler<TextMarkerMouseEventArgs> ITextSegmentMarker.MouseHover { + add { + throw new NotImplementedException (); + } + remove { + throw new NotImplementedException (); + } + } + + object ITextSegmentMarker.Tag { + get; + set; + } + + public Error Error { + get { + return info; + } + } + } +} + diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/GrayOutMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/GrayOutMarker.cs new file mode 100644 index 0000000000..4e5dcd4d56 --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/GrayOutMarker.cs @@ -0,0 +1,123 @@ +// +// GrayOutMarker.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +using System; +using Mono.TextEditor; +using System.Collections.Generic; +using MonoDevelop.Components; + +namespace MonoDevelop.SourceEditor +{ + class GrayOutMarker : UnderlineTextSegmentMarker, IChunkMarker, MonoDevelop.Ide.Editor.IGenericTextSegmentMarker + { + public GrayOutMarker (TextSegment segment) : base ("", segment) + { + } + + public override void Draw (MonoTextEditor editor, Cairo.Context cr, LineMetrics metrics, int startOffset, int endOffset) + { + // nothing (is drawn using chunk marker) + } + + #region IChunkMarker implementation + + void IChunkMarker.TransformChunks (List<Chunk> chunks) + { + int markerStart = Segment.Offset; + int markerEnd = Segment.EndOffset; + for (int i = 0; i < chunks.Count; i++) { + var chunk = chunks [i]; + if (chunk.EndOffset < markerStart || markerEnd <= chunk.Offset) + continue; + if (chunk.Offset == markerStart && chunk.EndOffset == markerEnd) + return; + if (chunk.Offset < markerStart && chunk.EndOffset > markerEnd) { + var newChunk = new Chunk (chunk.Offset, markerStart - chunk.Offset, chunk.Style); + chunks.Insert (i, newChunk); + chunk.Offset += newChunk.Length; + chunk.Length -= newChunk.Length; + continue; + } + } + } + + void IChunkMarker.ChangeForeColor (MonoTextEditor editor, Chunk chunk, ref Cairo.Color color) + { + if (Debugger.DebuggingService.IsDebugging) + return; + int markerStart = Segment.Offset; + int markerEnd = Segment.EndOffset; + if (chunk.EndOffset <= markerStart || markerEnd <= chunk.Offset) + return; + var bgc = editor.ColorStyle.PlainText.Background; + double alpha = 0.6; + color = new Cairo.Color ( + color.R * alpha + bgc.R * (1.0 - alpha), + color.G * alpha + bgc.G * (1.0 - alpha), + color.B * alpha + bgc.B * (1.0 - alpha) + ); + } + #endregion + + event EventHandler<MonoDevelop.Ide.Editor.TextMarkerMouseEventArgs> MonoDevelop.Ide.Editor.ITextSegmentMarker.MousePressed { + add { + throw new NotSupportedException (); + } + remove { + throw new NotSupportedException (); + } + } + + event EventHandler<MonoDevelop.Ide.Editor.TextMarkerMouseEventArgs> MonoDevelop.Ide.Editor.ITextSegmentMarker.MouseHover { + add { + throw new NotSupportedException (); + } + remove { + throw new NotSupportedException (); + } + } + + object MonoDevelop.Ide.Editor.ITextSegmentMarker.Tag { + get; + set; + } + + MonoDevelop.Ide.Editor.TextSegmentMarkerEffect MonoDevelop.Ide.Editor.IGenericTextSegmentMarker.Effect { + get { + return MonoDevelop.Ide.Editor.TextSegmentMarkerEffect.GrayOut; + } + } + + HslColor MonoDevelop.Ide.Editor.IGenericTextSegmentMarker.Color { + get { + throw new NotSupportedException (); + } + set { + throw new NotSupportedException (); + } + } + } +} diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ISourceEditorOptions.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/LinkMarker.cs index db013b102d..93cbd06d87 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/ISourceEditorOptions.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/LinkMarker.cs @@ -1,21 +1,21 @@ +// +// LinkMarker.cs // -// ISourceEditorOptions.cs -// // Author: -// Michael Hutchinson <mhutchinson@novell.com> +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) // -// Copyright (c) 2009 Novell, Inc. (http://www.novell.com) -// // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: -// +// // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. -// +// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -23,46 +23,44 @@ // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. - using System; -using System.Collections.Generic; - -using Pango; - +using MonoDevelop.Ide.Editor; using Mono.TextEditor; -using Mono.TextEditor.Highlighting; - -using MonoDevelop.Core; -using MonoDevelop.Ide.Gui; -using MonoDevelop.Ide.Gui.Content; -using MonoDevelop.Projects; -using MonoDevelop.Ide.CodeCompletion; namespace MonoDevelop.SourceEditor { - public enum EditorFontType { - // Default Monospace font as set in the user's GNOME font properties - DefaultMonospace, - - // Default Sans font as set in the user's GNOME font properties - DefaultSans, - - // Custom font, will need to get the FontName property for more specifics - UserSpecified - } - - public interface ISourceEditorOptions : Mono.TextEditor.ITextEditorOptions + class LinkMarker : Mono.TextEditor.UnderlineTextSegmentMarker, ITextSegmentMarker { - - bool EnableAutoCodeCompletion {get; } - bool DefaultRegionsFolding {get; } - bool DefaultCommentFolding {get; } - bool EnableSemanticHighlighting {get; } - //public bool AutoInsertTemplates {get; } - bool TabIsReindent {get; } - bool AutoInsertMatchingBracket {get; } - bool UnderlineErrors {get; } - EditorFontType EditorFontType {get; } - bool UseViModes {get; } + static readonly Cairo.Color linkColor = new Cairo.Color (0, 0, 1.0); + Action<LinkRequest> activateLink; + + public LinkMarker (int offset, int length, Action<LinkRequest> activateLink) : base (linkColor, new TextSegment (offset, length)) + { + this.activateLink = activateLink; + this.Wave = false; + } + + event EventHandler<TextMarkerMouseEventArgs> ITextSegmentMarker.MousePressed { + add { + throw new NotImplementedException (); + } + remove { + throw new NotImplementedException (); + } + } + event EventHandler<TextMarkerMouseEventArgs> ITextSegmentMarker.MouseHover { + add { + throw new NotImplementedException (); + } + remove { + throw new NotImplementedException (); + } + } + + object ITextSegmentMarker.Tag { + get; + set; + } } } + diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/SmartTagMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/SmartTagMarker.cs new file mode 100644 index 0000000000..f327dc895d --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/SmartTagMarker.cs @@ -0,0 +1,150 @@ +// +// SmartTagMarker.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using Mono.TextEditor; +using MonoDevelop.Components; +using MonoDevelop.Ide.Editor; + +namespace MonoDevelop.SourceEditor +{ + class SmartTagMarker : TextSegmentMarker, IActionTextLineMarker, ISmartTagMarker + { + const double tagMarkerWidth = 8; + const double tagMarkerHeight = 2; + MonoDevelop.Ide.Editor.DocumentLocation loc; + Mono.TextEditor.MonoTextEditor editor; + + public SmartTagMarker (int offset, MonoDevelop.Ide.Editor.DocumentLocation realLocation) : base (offset, 0) + { + this.loc = realLocation; + } + + public override void Draw (Mono.TextEditor.MonoTextEditor editor, Cairo.Context cr, LineMetrics metrics, int startOffset, int endOffset) + { + this.editor = editor; + var line = editor.GetLine (loc.Line); + if (line == null) + return; + var x = editor.ColumnToX (line, loc.Column) - editor.HAdjustment.Value + editor.TextViewMargin.XOffset + editor.TextViewMargin.TextStartPosition; + + cr.Rectangle (Math.Floor (x) + 0.5, Math.Floor (metrics.LineYRenderStartPosition) + 0.5 + (line == editor.GetLineByOffset (startOffset) ? editor.LineHeight - tagMarkerHeight - 1 : 0), tagMarkerWidth * cr.LineWidth, tagMarkerHeight * cr.LineWidth); + + if (HslColor.Brightness (editor.ColorStyle.PlainText.Background) < 0.5) { + cr.SetSourceRGBA (0.8, 0.8, 1, 0.9); + } else { + cr.SetSourceRGBA (0.2, 0.2, 1, 0.9); + } + cr.Stroke (); + } + + #region IActionTextLineMarker implementation + class TextEventArgsWrapper : TextMarkerMouseEventArgs + { + readonly MarginMouseEventArgs args; + + public override double X { + get { + return args.X; + } + } + + public override double Y { + get { + return args.Y; + } + } + + public override object OverwriteCursor { + get; + set; + } + + public override string TooltipMarkup { + get; + set; + } + + public TextEventArgsWrapper (MarginMouseEventArgs args) + { + if (args == null) + throw new ArgumentNullException ("args"); + this.args = args; + } + + public override bool TriggersContextMenu () + { + return args.TriggersContextMenu (); + } + } + + bool IActionTextLineMarker.MousePressed (Mono.TextEditor.MonoTextEditor editor, MarginMouseEventArgs args) + { + var handler = MousePressed; + if (handler != null) + handler (this, new TextEventArgsWrapper (args)); + return false; + } + + void IActionTextLineMarker.MouseHover (Mono.TextEditor.MonoTextEditor editor, MarginMouseEventArgs args, TextLineMarkerHoverResult result) + { + if (args.Button != 0) + return; + var handler = MouseHover; + if (handler != null) + handler (this, new TextEventArgsWrapper (args)); + } + + #endregion + + bool ISmartTagMarker.IsInsideSmartTag (double x, double y) + { + if (editor == null) + return false; + var lin2 = editor.GetLine (loc.Line); + var x2 = editor.ColumnToX (lin2, loc.Column) - editor.HAdjustment.Value + editor.TextViewMargin.TextStartPosition; + var y2 = editor.LineToY (loc.Line + 1) - editor.VAdjustment.Value; + return x - x2 >= 0 * editor.Options.Zoom && + x - x2 < tagMarkerWidth * editor.Options.Zoom && + y - y2 < (editor.LineHeight / 2) * editor.Options.Zoom; + } + + bool ISmartTagMarker.IsInsideWindow (Gtk.MotionNotifyEventArgs args) + { + if (editor == null) + return false; + return args.Event.Window == editor.TextArea.GdkWindow; + } + + public event EventHandler<TextMarkerMouseEventArgs> MousePressed; + public event EventHandler<TextMarkerMouseEventArgs> MouseHover; + + object ITextSegmentMarker.Tag { + get; + set; + } + } +} + diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UnitTestMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UnitTestMarker.cs new file mode 100644 index 0000000000..49c242cde9 --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UnitTestMarker.cs @@ -0,0 +1,136 @@ +using System; +using MonoDevelop.Ide.Editor; +using Mono.TextEditor; +using MonoDevelop.Core; +using MonoDevelop.Components; +using MonoDevelop.SourceEditor.Wrappers; + +namespace MonoDevelop.SourceEditor +{ + class UnitTestMarker : MarginMarker, IUnitTestMarker + { + IDocumentLine ITextLineMarker.Line { + get { + return new DocumentLineWrapper (LineSegment); + } + } + + readonly UnitTestMarkerHost host; + readonly UnitTestLocation unitTest; + readonly ExtensibleTextEditor textEditor; + + UnitTestLocation IUnitTestMarker.UnitTest { + get { + return unitTest; + } + } + + void IUnitTestMarker.UpdateState () + { + var line = LineSegment; + if (line == null) + return; + textEditor.RedrawMarginLine (textEditor.ActionMargin, line.LineNumber); + } + + public UnitTestMarker (ExtensibleTextEditor textEditor, UnitTestMarkerHost host, UnitTestLocation unitTest) + { + if (textEditor == null) + throw new ArgumentNullException ("textEditor"); + if (host == null) + throw new ArgumentNullException ("host"); + this.textEditor = textEditor; + this.host = host; + this.unitTest = unitTest; + } + + public override bool CanDrawForeground (Margin margin) + { + return margin is ActionMargin; + } + + public override void InformMouseHover (Mono.TextEditor.MonoTextEditor editor, Margin margin, MarginMouseEventArgs args) + { + if (!(margin is ActionMargin)) + return; + string toolTip; + if (unitTest.IsFixture) { + if (isFailed) { + toolTip = GettextCatalog.GetString ("NUnit Fixture failed (click to run)"); + if (!string.IsNullOrEmpty (failMessage)) + toolTip += Environment.NewLine + failMessage.TrimEnd (); + } else { + toolTip = GettextCatalog.GetString ("NUnit Fixture (click to run)"); + } + } else { + if (isFailed) { + toolTip = GettextCatalog.GetString ("NUnit Test failed (click to run)"); + if (!string.IsNullOrEmpty (failMessage)) + toolTip += Environment.NewLine + failMessage.TrimEnd (); + foreach (var id in unitTest.TestCases) { + if (host.IsFailure (unitTest.UnitTestIdentifier, id)) { + var msg = host.GetMessage (unitTest.UnitTestIdentifier, id); + if (!string.IsNullOrEmpty (msg)) { + toolTip += Environment.NewLine + "Test" + id + ":"; + toolTip += Environment.NewLine + msg.TrimEnd (); + } + } + } + } else { + toolTip = GettextCatalog.GetString ("NUnit Test (click to run)"); + } + + } + editor.TooltipText = toolTip; + } + +// static Menu menu; + + public override void InformMousePress (Mono.TextEditor.MonoTextEditor editor, Margin margin, MarginMouseEventArgs args) + { + if (!(margin is ActionMargin)) + return; + host.PopupContextMenu (unitTest, (int)args.X, (int)args.Y); + editor.TextArea.ResetMouseState (); + } + + bool isFailed; + string failMessage; + + public override void DrawForeground (Mono.TextEditor.MonoTextEditor editor, Cairo.Context cr, MarginDrawMetrics metrics) + { + isFailed = false; + bool searchCases = false; + + Xwt.Drawing.Image icon = host.GetStatusIcon (unitTest.UnitTestIdentifier); + if (icon != null) { + if (host.HasResult (unitTest.UnitTestIdentifier)) { + searchCases = true; + } else if (host.IsFailure (unitTest.UnitTestIdentifier)) { + failMessage = host.GetMessage (unitTest.UnitTestIdentifier); + isFailed = true; + } + } else { + searchCases = true; + } + + if (searchCases) { + foreach (var caseId in unitTest.TestCases) { + icon = host.GetStatusIcon (unitTest.UnitTestIdentifier, caseId); + if (host.IsFailure (unitTest.UnitTestIdentifier, caseId)) { + failMessage = host.GetMessage (unitTest.UnitTestIdentifier, caseId); + isFailed = true; + break; + } + } + } + + if (icon != null) { + if (icon.Width > metrics.Width || icon.Height > metrics.Height) + icon = icon.WithBoxSize (metrics.Width, metrics.Height); + cr.DrawImage (editor, icon, Math.Truncate (metrics.X + metrics.Width / 2 - icon.Width / 2), Math.Truncate (metrics.Y + metrics.Height / 2 - icon.Height / 2)); + } + } + } +} + diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UrlTextLineMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UrlTextLineMarker.cs new file mode 100644 index 0000000000..00e8ccfed0 --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UrlTextLineMarker.cs @@ -0,0 +1,56 @@ +// +// UrlTextLineMarker.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using Mono.TextEditor; +using MonoDevelop.Ide.Editor; + +namespace MonoDevelop.SourceEditor +{ + class UrlTextLineMarker : UrlMarker, IUrlTextLineMarker + { + readonly IDocumentLine line; + + public UrlTextLineMarker (TextDocument doc, IDocumentLine line, string url, Mono.TextEditor.UrlType urlType, string style, int startColumn, int endColumn) : base (doc, doc.GetLine (line.LineNumber), url, urlType, style, startColumn, endColumn) + { + if (doc == null) + throw new ArgumentNullException ("doc"); + this.line = line; + } + + MonoDevelop.Ide.Editor.UrlType IUrlTextLineMarker.UrlType { + get { + return (MonoDevelop.Ide.Editor.UrlType)UrlType; + } + } + + IDocumentLine ITextLineMarker.Line { + get { + return line; + } + } + } +} + diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UsageSegmentMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UsageSegmentMarker.cs new file mode 100644 index 0000000000..bdd4c7c59d --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/UsageSegmentMarker.cs @@ -0,0 +1,102 @@ +using System; +using Mono.TextEditor; +using MonoDevelop.Ide.Editor; +using MonoDevelop.Ide.FindInFiles; +using Cairo; +using MonoDevelop.Components; +using MonoDevelop.Ide.Editor.Extension; + +namespace MonoDevelop.SourceEditor +{ + class UsageSegmentMarker : TextSegmentMarker, ITextSegmentMarker + { + readonly Usage usage; + + public Usage Usage { + get { + return usage; + } + } + + public UsageSegmentMarker (Usage usage) : base (usage.Offset, usage.Length) + { + this.usage = usage; + } + + event EventHandler<TextMarkerMouseEventArgs> ITextSegmentMarker.MousePressed { + add { + } + remove { + } + } + + event EventHandler<TextMarkerMouseEventArgs> ITextSegmentMarker.MouseHover { + add { + } + remove { + } + } + + object ITextSegmentMarker.Tag { + get; + set; + } + + public override void DrawBackground (Mono.TextEditor.MonoTextEditor editor, Context cr, LineMetrics metrics, int startOffset, int endOffset) + { + int markerStart = usage.Offset; + int markerEnd = usage.EndOffset; + + if (markerEnd < startOffset || markerStart > endOffset) + return; + + double @from; + double to; + var startXPos = metrics.TextRenderStartPosition; + var endXPos = metrics.TextRenderEndPosition; + var y = metrics.LineYRenderStartPosition; + if (markerStart < startOffset && endOffset < markerEnd) { + @from = startXPos; + to = endXPos; + } else { + int start = startOffset < markerStart ? markerStart : startOffset; + int end = endOffset < markerEnd ? endOffset : markerEnd; + + uint curIndex = 0, byteIndex = 0; + TextViewMargin.TranslateToUTF8Index (metrics.Layout.LineChars, (uint)(start - startOffset), ref curIndex, ref byteIndex); + + int x_pos = metrics.Layout.Layout.IndexToPos ((int)byteIndex).X; + + @from = startXPos + (int)(x_pos / Pango.Scale.PangoScale); + + TextViewMargin.TranslateToUTF8Index (metrics.Layout.LineChars, (uint)(end - startOffset), ref curIndex, ref byteIndex); + x_pos = metrics.Layout.Layout.IndexToPos ((int)byteIndex).X; + + to = startXPos + (int)(x_pos / Pango.Scale.PangoScale); + } + + @from = Math.Max (@from, editor.TextViewMargin.XOffset); + to = Math.Max (to, editor.TextViewMargin.XOffset); + if (@from < to) { + Mono.TextEditor.Highlighting.AmbientColor colorStyle; + if ((usage.UsageType & ReferenceUsageType.Write) == ReferenceUsageType.Write || + (usage.UsageType & ReferenceUsageType.Declariton) == ReferenceUsageType.Declariton) { + colorStyle = editor.ColorStyle.ChangingUsagesRectangle; + } else { + colorStyle = editor.ColorStyle.UsagesRectangle; + } + + using (var lg = new LinearGradient (@from + 1, y + 1, to , y + editor.LineHeight)) { + lg.AddColorStop (0, colorStyle.Color); + lg.AddColorStop (1, colorStyle.SecondColor); + cr.SetSource (lg); + cr.RoundedRectangle (@from + 0.5, y + 1.5, to - @from - 1, editor.LineHeight - 2, editor.LineHeight / 4); + cr.FillPreserve (); + } + + cr.SetSourceColor (colorStyle.BorderColor); + cr.Stroke (); + } + } + } +}
\ No newline at end of file diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/WavedLineMarker.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/WavedLineMarker.cs new file mode 100644 index 0000000000..fdd11c9729 --- /dev/null +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor/TextMarker/WavedLineMarker.cs @@ -0,0 +1,133 @@ +// +// WavedLineMarker.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2014 Xamarin Inc. (http://xamarin.com) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. +using System; +using Mono.TextEditor; +using MonoDevelop.Components; +using MonoDevelop.Debugger; +using Pango; + +namespace MonoDevelop.SourceEditor +{ + class GenericUnderlineMarker : UnderlineTextSegmentMarker, MonoDevelop.Ide.Editor.IGenericTextSegmentMarker + { + HslColor color; + + HslColor MonoDevelop.Ide.Editor.IGenericTextSegmentMarker.Color { + get { + return color; + } + set { + color = value; + } + } + + public GenericUnderlineMarker (TextSegment segment, MonoDevelop.Ide.Editor.TextSegmentMarkerEffect effect) : base ("", segment) + { + this.effect = effect; + } + + public override void Draw (MonoTextEditor editor, Cairo.Context cr, LineMetrics layout, int startOffset, int endOffset) + { + if (DebuggingService.IsDebugging) + return; + int markerStart = Segment.Offset; + int markerEnd = Segment.EndOffset; + if (markerEnd < startOffset || markerStart > endOffset) + return; + + double drawFrom; + double drawTo; + double y = layout.LineYRenderStartPosition; + double startXPos = layout.TextRenderStartPosition; + double endXPos = layout.TextRenderEndPosition; + + if (markerStart < startOffset && endOffset < markerEnd) { + drawTo = endXPos; + var line = editor.GetLineByOffset (startOffset); + int offset = line.GetIndentation (editor.Document).Length; + drawFrom = startXPos + (layout.Layout.Layout.IndexToPos (offset).X / Pango.Scale.PangoScale); + } else { + int start; + if (startOffset < markerStart) { + start = markerStart; + } else { + var line = editor.GetLineByOffset (startOffset); + int offset = line.GetIndentation (editor.Document).Length; + start = startOffset + offset; + } + int end = endOffset < markerEnd ? endOffset : markerEnd; + int x_pos; + + x_pos = layout.Layout.Layout.IndexToPos (start - startOffset).X; + drawFrom = startXPos + (int)(x_pos / Pango.Scale.PangoScale); + x_pos = layout.Layout.Layout.IndexToPos (end - startOffset).X; + + drawTo = startXPos + (int)(x_pos / Pango.Scale.PangoScale); + } + + drawFrom = Math.Max (drawFrom, editor.TextViewMargin.XOffset); + drawTo = Math.Max (drawTo, editor.TextViewMargin.XOffset); + if (drawFrom >= drawTo) + return; + + double height = editor.LineHeight / 5; + cr.SetSourceColor (color); + if (effect == MonoDevelop.Ide.Editor.TextSegmentMarkerEffect.WavedLine) { + Pango.CairoHelper.ShowErrorUnderline (cr, drawFrom, y + editor.LineHeight - height, drawTo - drawFrom, height); + } else if (effect == MonoDevelop.Ide.Editor.TextSegmentMarkerEffect.DottedLine) { + cr.Save (); + cr.LineWidth = 1; + cr.MoveTo (drawFrom + 1, y + editor.LineHeight - 1 + 0.5); + cr.RelLineTo (Math.Min (drawTo - drawFrom, 4 * 3), 0); + cr.SetDash (new double[] { 2, 2 }, 0); + cr.Stroke (); + cr.Restore (); + } else { + cr.MoveTo (drawFrom, y + editor.LineHeight - 1); + cr.LineTo (drawTo, y + editor.LineHeight - 1); + cr.Stroke (); + } + } + + public event EventHandler<MonoDevelop.Ide.Editor.TextMarkerMouseEventArgs> MousePressed; + + public event EventHandler<MonoDevelop.Ide.Editor.TextMarkerMouseEventArgs> MouseHover; + + object MonoDevelop.Ide.Editor.ITextSegmentMarker.Tag { + get; + set; + } + + MonoDevelop.Ide.Editor.TextSegmentMarkerEffect effect; + MonoDevelop.Ide.Editor.TextSegmentMarkerEffect MonoDevelop.Ide.Editor.IGenericTextSegmentMarker.Effect { + get { + return effect; + } + } + + } +} + |