1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
|
//
// QuickFixEditorExtension.cs
//
// Author:
// Mike Krüger <mkrueger@novell.com>
//
// Copyright (c) 2011 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.Gui.Content;
using Gtk;
using Mono.TextEditor;
using System.Collections.Generic;
using MonoDevelop.Components.Commands;
using MonoDevelop.SourceEditor.QuickTasks;
using System.Linq;
using MonoDevelop.Refactoring;
using ICSharpCode.NRefactory;
using System.Threading;
using MonoDevelop.Core;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.Semantics;
using MonoDevelop.AnalysisCore.Fixes;
using ICSharpCode.NRefactory.Refactoring;
using MonoDevelop.Ide.Gui;
namespace MonoDevelop.CodeActions
{
class CodeActionEditorExtension : TextEditorExtension
{
uint quickFixTimeout;
const int menuTimeout = 250;
uint smartTagPopupTimeoutId;
uint menuCloseTimeoutId;
FixMenuDescriptor codeActionMenu;
public IEnumerable<CodeAction> Fixes {
get;
private set;
}
static CodeActionEditorExtension ()
{
var usages = PropertyService.Get<Properties> ("CodeActionUsages", new Properties ());
foreach (var key in usages.Keys) {
CodeActionUsages [key] = usages.Get<int> (key);
}
}
void CancelSmartTagPopupTimeout ()
{
if (smartTagPopupTimeoutId != 0) {
GLib.Source.Remove (smartTagPopupTimeoutId);
smartTagPopupTimeoutId = 0;
}
}
void CancelMenuCloseTimer ()
{
if (menuCloseTimeoutId != 0) {
GLib.Source.Remove (menuCloseTimeoutId);
menuCloseTimeoutId = 0;
}
}
void RemoveWidget ()
{
if (currentSmartTag != null) {
document.Editor.Document.RemoveMarker (currentSmartTag);
currentSmartTag = null;
currentSmartTagBegin = DocumentLocation.Empty;
}
CancelSmartTagPopupTimeout ();
}
public override void Dispose ()
{
CancelMenuCloseTimer ();
CancelQuickFixTimer ();
document.Editor.SelectionChanged -= HandleSelectionChanged;
document.DocumentParsed -= HandleDocumentDocumentParsed;
document.Editor.Parent.BeginHover -= HandleBeginHover;
RemoveWidget ();
Fixes = null;
base.Dispose ();
}
static readonly Dictionary<string, int> CodeActionUsages = new Dictionary<string, int> ();
static void ConfirmUsage (string id)
{
if (!CodeActionUsages.ContainsKey (id)) {
CodeActionUsages [id] = 1;
} else {
CodeActionUsages [id]++;
}
var usages = PropertyService.Get<Properties> ("CodeActionUsages", new Properties ());
usages.Set (id, CodeActionUsages [id]);
}
internal static int GetUsage (string id)
{
int result;
if (!CodeActionUsages.TryGetValue (id, out result))
return 0;
return result;
}
public void CancelQuickFixTimer ()
{
if (quickFixCancellationTokenSource != null)
quickFixCancellationTokenSource.Cancel ();
if (quickFixTimeout != 0) {
GLib.Source.Remove (quickFixTimeout);
quickFixTimeout = 0;
}
}
CancellationTokenSource quickFixCancellationTokenSource;
public override void CursorPositionChanged ()
{
CancelQuickFixTimer ();
if (QuickTaskStrip.EnableFancyFeatures && Document.ParsedDocument != null && !Debugger.DebuggingService.IsDebugging) {
quickFixCancellationTokenSource = new CancellationTokenSource ();
var token = quickFixCancellationTokenSource.Token;
quickFixTimeout = GLib.Timeout.Add (100, delegate {
var loc = Document.Editor.Caret.Location;
RefactoringService.QueueQuickFixAnalysis (Document, loc, token, delegate(List<CodeAction> fixes) {
if (!fixes.Any ()) {
ICSharpCode.NRefactory.Semantics.ResolveResult resolveResult;
AstNode node;
if (ResolveCommandHandler.ResolveAt (document, out resolveResult, out node, token)) {
var possibleNamespaces = ResolveCommandHandler.GetPossibleNamespaces (document, node, ref resolveResult);
if (!possibleNamespaces.Any ()) {
if (currentSmartTag != null)
Application.Invoke (delegate { RemoveWidget (); });
return;
}
} else {
if (currentSmartTag != null)
Application.Invoke (delegate { RemoveWidget (); });
return;
}
}
Application.Invoke (delegate {
if (token.IsCancellationRequested)
return;
CreateSmartTag (fixes, loc);
});
});
quickFixTimeout = 0;
return false;
});
} else {
RemoveWidget ();
}
base.CursorPositionChanged ();
}
internal static bool IsAnalysisOrErrorFix (CodeAction act)
{
return act is AnalysisContextActionProvider.AnalysisCodeAction || act.Severity == Severity.Error;
}
class FixMenuEntry
{
public static readonly FixMenuEntry Separator = new FixMenuEntry ("-", null);
public readonly string Label;
public readonly System.Action Action;
public FixMenuEntry (string label, System.Action action)
{
this.Label = label;
this.Action = action;
}
}
class FixMenuDescriptor : FixMenuEntry
{
readonly List<FixMenuEntry> items = new List<FixMenuEntry> ();
public IReadOnlyList<FixMenuEntry> Items {
get {
return items;
}
}
public FixMenuDescriptor () : base (null, null)
{
}
public FixMenuDescriptor (string label) : base (label, null)
{
}
public void Add (FixMenuEntry entry)
{
items.Add (entry);
}
public object MotionNotifyEvent {
get;
set;
}
}
void PopupQuickFixMenu (Gdk.EventButton evt, Action<FixMenuDescriptor> menuAction)
{
FixMenuDescriptor menu = new FixMenuDescriptor ();
var fixMenu = menu;
ResolveResult resolveResult;
ICSharpCode.NRefactory.CSharp.AstNode node;
int items = 0;
if (ResolveCommandHandler.ResolveAt (document, out resolveResult, out node)) {
var possibleNamespaces = MonoDevelop.Refactoring.ResolveCommandHandler.GetPossibleNamespaces (
document,
node,
ref resolveResult
);
foreach (var t in possibleNamespaces.Where (tp => tp.OnlyAddReference)) {
menu.Add (new FixMenuEntry (t.GetImportText (), delegate {
new ResolveCommandHandler.AddImport (document, resolveResult, null, t.Reference, true, node).Run ();
}));
items++;
}
bool addUsing = !(resolveResult is AmbiguousTypeResolveResult);
if (addUsing) {
foreach (var t in possibleNamespaces.Where (tp => tp.IsAccessibleWithGlobalUsing)) {
string ns = t.Namespace;
var reference = t.Reference;
menu.Add (new FixMenuEntry (t.GetImportText (),
delegate {
new ResolveCommandHandler.AddImport (document, resolveResult, ns, reference, true, node).Run ();
})
);
items++;
}
}
bool resolveDirect = !(resolveResult is UnknownMemberResolveResult);
if (resolveDirect) {
foreach (var t in possibleNamespaces) {
string ns = t.Namespace;
var reference = t.Reference;
menu.Add (new FixMenuEntry (t.GetInsertNamespaceText (document.Editor.GetTextBetween (node.StartLocation, node.EndLocation)),
delegate {
new ResolveCommandHandler.AddImport (document, resolveResult, ns, reference, false, node).Run ();
}));
items++;
}
}
if (menu.Items.Any () && Fixes.Any ()) {
fixMenu = new FixMenuDescriptor (GettextCatalog.GetString ("Quick Fixes"));
menu.Add (fixMenu);
items++;
}
}
PopulateFixes (fixMenu, ref items);
if (items == 0) {
return;
}
document.Editor.SuppressTooltips = true;
document.Editor.Parent.HideTooltip ();
if (menuAction != null)
menuAction (menu);
var container = document.Editor.Parent;
var p = container.LocationToPoint (currentSmartTagBegin);
var rect = new Gdk.Rectangle (
p.X + container.Allocation.X ,
p.Y + (int)document.Editor.LineHeight + container.Allocation.Y, 0, 0);
ShowFixesMenu (document.Editor.Parent, rect, menu);
}
bool ShowFixesMenu (Gtk.Widget parent, Gdk.Rectangle evt, FixMenuDescriptor entrySet)
{
#if MAC
parent.GrabFocus ();
int x, y;
x = (int)evt.X;
y = (int)evt.Y;
Gtk.Application.Invoke (delegate {
// Explicitly release the grab because the menu is shown on the mouse position, and the widget doesn't get the mouse release event
Gdk.Pointer.Ungrab (Gtk.Global.CurrentEventTime);
var menu = CreateNSMenu (entrySet);
var nsview = MonoDevelop.Components.Mac.GtkMacInterop.GetNSView (parent);
var toplevel = parent.Toplevel as Gtk.Window;
int trans_x, trans_y;
parent.TranslateCoordinates (toplevel, (int)x, (int)y, out trans_x, out trans_y);
// Window coordinates in gtk are the same for cocoa, with the exception of the Y coordinate, that has to be flipped.
var pt = new CoreGraphics.CGPoint ((float)trans_x, (float)trans_y);
int w,h;
toplevel.GetSize (out w, out h);
pt.Y = h - pt.Y;
var tmp_event = AppKit.NSEvent.MouseEvent (AppKit.NSEventType.LeftMouseDown,
pt,
0, 0,
MonoDevelop.Components.Mac.GtkMacInterop.GetNSWindow (toplevel).WindowNumber,
null, 0, 0, 0);
AppKit.NSMenu.PopUpContextMenu (menu, tmp_event, nsview);
});
#else
var menu = CreateGtkMenu (entrySet);
menu.Events |= Gdk.EventMask.AllEventsMask;
menu.SelectFirst (true);
menu.Hidden += delegate {
document.Editor.SuppressTooltips = false;
};
menu.ShowAll ();
menu.MotionNotifyEvent += (o, args) => {
if (args.Event.Window == Editor.Parent.TextArea.GdkWindow) {
StartMenuCloseTimer ();
} else {
CancelMenuCloseTimer ();
}
};
GtkWorkarounds.ShowContextMenu (menu, parent, null, evt);
#endif
return true;
}
#if MAC
AppKit.NSMenu CreateNSMenu (FixMenuDescriptor entrySet)
{
var menu = new AppKit.NSMenu ();
foreach (var item in entrySet.Items) {
if (item == FixMenuEntry.Separator) {
menu.AddItem (AppKit.NSMenuItem.SeparatorItem);
continue;
}
var subMenu = item as FixMenuDescriptor;
if (subMenu != null) {
var gtkSubMenu = new AppKit.NSMenuItem (item.Label.Replace ("_", ""));
gtkSubMenu.Submenu = CreateNSMenu (subMenu);
menu.AddItem (gtkSubMenu);
continue;
}
var menuItem = new AppKit.NSMenuItem (item.Label.Replace ("_", ""));
menuItem.Activated += delegate {
item.Action ();
};
menu.AddItem (menuItem);
}
return menu;
}
#endif
static Menu CreateGtkMenu (FixMenuDescriptor entrySet)
{
var menu = new Menu ();
foreach (var item in entrySet.Items) {
if (item == FixMenuEntry.Separator) {
menu.Add (new SeparatorMenuItem ());
continue;
}
var subMenu = item as FixMenuDescriptor;
if (subMenu != null) {
var gtkSubMenu = new Gtk.MenuItem (item.Label);
gtkSubMenu.Submenu = CreateGtkMenu (subMenu);
menu.Add (gtkSubMenu);
continue;
}
var menuItem = new Gtk.MenuItem (item.Label);
menuItem.Activated += delegate {
item.Action ();
};
menu.Add (menuItem);
}
return menu;
}
void PopulateFixes (FixMenuDescriptor menu, ref int items)
{
int mnemonic = 1;
bool gotImportantFix = false, addedSeparator = false;
var fixesAdded = new List<string> ();
foreach (var fix_ in Fixes.OrderByDescending (i => Tuple.Create (IsAnalysisOrErrorFix(i), (int)i.Severity, GetUsage (i.IdString)))) {
// filter out code actions that are already resolutions of a code issue
if (fixesAdded.Any (f => fix_.IdString.IndexOf (f, StringComparison.Ordinal) >= 0))
continue;
fixesAdded.Add (fix_.IdString);
if (IsAnalysisOrErrorFix (fix_))
gotImportantFix = true;
if (!addedSeparator && gotImportantFix && !IsAnalysisOrErrorFix(fix_)) {
menu.Add (FixMenuEntry.Separator);
addedSeparator = true;
}
var fix = fix_;
var escapedLabel = fix.Title.Replace ("_", "__");
var label = (mnemonic <= 10)
? "_" + (mnemonic++ % 10).ToString () + " " + escapedLabel
: " " + escapedLabel;
var thisInstanceMenuItem = new FixMenuEntry (label, delegate {
new ContextActionRunner (fix, document, currentSmartTagBegin).Run (null, EventArgs.Empty);
ConfirmUsage (fix.IdString);
});
menu.Add (thisInstanceMenuItem);
items++;
}
bool first = true;
var settingsMenuFixes = Fixes
.OfType<AnalysisContextActionProvider.AnalysisCodeAction> ()
.Where (f => f.Result is InspectorResults)
.GroupBy (f => ((InspectorResults)f.Result).Inspector);
foreach (var analysisFixGroup_ in settingsMenuFixes) {
var analysisFixGroup = analysisFixGroup_;
var arbitraryFixInGroup = analysisFixGroup.First ();
var ir = (InspectorResults)arbitraryFixInGroup.Result;
if (first) {
menu.Add (FixMenuEntry.Separator);
first = false;
}
var subMenu = new FixMenuDescriptor ();
foreach (var analysisFix_ in analysisFixGroup) {
var analysisFix = analysisFix_;
if (analysisFix.SupportsBatchRunning) {
var batchRunMenuItem = new FixMenuEntry (
string.Format (GettextCatalog.GetString ("Apply in file: {0}"), analysisFix.Title),
delegate {
ConfirmUsage (analysisFix.IdString);
new ContextActionRunner (analysisFix, document, this.currentSmartTagBegin).BatchRun (null, EventArgs.Empty);
}
);
subMenu.Add (batchRunMenuItem);
subMenu.Add (FixMenuEntry.Separator);
}
}
var inspector = ir.Inspector;
if (inspector.CanSuppressWithAttribute) {
var menuItem = new FixMenuEntry (GettextCatalog.GetString ("_Suppress with attribute"),
delegate {
inspector.SuppressWithAttribute (document, arbitraryFixInGroup.DocumentRegion);
});
subMenu.Add (menuItem);
}
if (inspector.CanDisableWithPragma) {
var menuItem = new FixMenuEntry (GettextCatalog.GetString ("_Suppress with #pragma"),
delegate {
inspector.DisableWithPragma (document, arbitraryFixInGroup.DocumentRegion);
});
subMenu.Add (menuItem);
}
if (inspector.CanDisableOnce) {
var menuItem = new FixMenuEntry (GettextCatalog.GetString ("_Disable Once"),
delegate {
inspector.DisableOnce (document, arbitraryFixInGroup.DocumentRegion);
});
subMenu.Add (menuItem);
}
if (inspector.CanDisableAndRestore) {
var menuItem = new FixMenuEntry (GettextCatalog.GetString ("Disable _and Restore"),
delegate {
inspector.DisableAndRestore (document, arbitraryFixInGroup.DocumentRegion);
});
subMenu.Add (menuItem);
}
var label = GettextCatalog.GetString ("_Options for \"{0}\"", InspectorResults.GetTitle (ir.Inspector));
var subMenuItem = new FixMenuDescriptor (label);
var optionsMenuItem = new FixMenuEntry (GettextCatalog.GetString ("_Configure Rule"),
delegate {
arbitraryFixInGroup.ShowOptions (null, EventArgs.Empty);
});
subMenuItem.Add (optionsMenuItem);
menu.Add (subMenuItem);
items++;
}
}
class ContextActionRunner
{
CodeAction act;
Document document;
TextLocation loc;
public ContextActionRunner (MonoDevelop.CodeActions.CodeAction act, MonoDevelop.Ide.Gui.Document document, ICSharpCode.NRefactory.TextLocation loc)
{
this.act = act;
this.document = document;
this.loc = loc;
}
public void Run (object sender, EventArgs e)
{
var context = document.ParsedDocument.CreateRefactoringContext (document, CancellationToken.None);
RefactoringService.ApplyFix (act, context);
}
public void BatchRun (object sender, EventArgs e)
{
act.BatchRun (document, loc);
}
}
class SmartTagMarker : TextSegmentMarker, IActionTextLineMarker
{
CodeActionEditorExtension codeActionEditorExtension;
internal List<CodeAction> fixes;
DocumentLocation loc;
public SmartTagMarker (int offset, CodeActionEditorExtension codeActionEditorExtension, List<CodeAction> fixes, DocumentLocation loc) : base (offset, 0)
{
this.codeActionEditorExtension = codeActionEditorExtension;
this.fixes = fixes;
this.loc = loc;
}
public SmartTagMarker (int offset) : base (offset, 0)
{
}
const double tagMarkerWidth = 8;
const double tagMarkerHeight = 2;
public override void Draw (TextEditor editor, Cairo.Context cr, Pango.Layout layout, bool selected, int startOffset, int endOffset, double y, double startXPos, double endXPos)
{
var line = editor.GetLine (loc.Line);
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 (y) + 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
bool IActionTextLineMarker.MousePressed (TextEditor editor, MarginMouseEventArgs args)
{
return false;
}
void IActionTextLineMarker.MouseHover (TextEditor editor, MarginMouseEventArgs args, TextLineMarkerHoverResult result)
{
if (args.Button != 0)
return;
var line = editor.GetLine (loc.Line);
if (line == null)
return;
var x = editor.ColumnToX (line, loc.Column) - editor.HAdjustment.Value + editor.TextViewMargin.TextStartPosition;
var y = editor.LineToY (line.LineNumber + 1) - editor.VAdjustment.Value;
const double xAdditionalSpace = tagMarkerWidth;
if (args.X - x >= -xAdditionalSpace * editor.Options.Zoom &&
args.X - x < (tagMarkerWidth + xAdditionalSpace) * editor.Options.Zoom /*&&
args.Y - y < (editor.LineHeight / 2) * editor.Options.Zoom*/) {
result.Cursor = null;
Popup ();
} else {
codeActionEditorExtension.CancelSmartTagPopupTimeout ();
}
}
public void Popup ()
{
codeActionEditorExtension.smartTagPopupTimeoutId = GLib.Timeout.Add (menuTimeout, delegate {
codeActionEditorExtension.PopupQuickFixMenu (null, menu => {
codeActionEditorExtension.codeActionMenu = menu;
});
codeActionEditorExtension.smartTagPopupTimeoutId = 0;
return false;
});
}
#endregion
}
SmartTagMarker currentSmartTag;
DocumentLocation currentSmartTagBegin;
void CreateSmartTag (List<CodeAction> fixes, DocumentLocation loc)
{
Fixes = fixes;
if (!QuickTaskStrip.EnableFancyFeatures) {
RemoveWidget ();
return;
}
var editor = document.Editor;
if (editor == null || editor.Parent == null || !editor.Parent.IsRealized) {
RemoveWidget ();
return;
}
if (document.ParsedDocument == null || document.ParsedDocument.IsInvalid) {
RemoveWidget ();
return;
}
var container = editor.Parent;
if (container == null) {
RemoveWidget ();
return;
}
bool first = true;
DocumentLocation smartTagLocBegin = loc;
foreach (var fix in fixes) {
if (fix.DocumentRegion.IsEmpty)
continue;
if (first || loc < fix.DocumentRegion.Begin) {
smartTagLocBegin = fix.DocumentRegion.Begin;
}
first = false;
}
if (smartTagLocBegin.Line != loc.Line)
smartTagLocBegin = new DocumentLocation (loc.Line, 1);
// got no fix location -> try to search word start
if (first) {
int offset = document.Editor.LocationToOffset (smartTagLocBegin);
while (offset > 0) {
char ch = document.Editor.GetCharAt (offset - 1);
if (!char.IsLetterOrDigit (ch) && ch != '_')
break;
offset--;
}
smartTagLocBegin = document.Editor.OffsetToLocation (offset);
}
if (currentSmartTag != null && currentSmartTagBegin == smartTagLocBegin) {
currentSmartTag.fixes = fixes;
return;
}
RemoveWidget ();
currentSmartTagBegin = smartTagLocBegin;
var line = document.Editor.GetLine (smartTagLocBegin.Line);
currentSmartTag = new SmartTagMarker ((line.NextLine ?? line).Offset, this, fixes, smartTagLocBegin);
document.Editor.Document.AddMarker (currentSmartTag);
}
public override void Initialize ()
{
base.Initialize ();
document.DocumentParsed += HandleDocumentDocumentParsed;
document.Editor.SelectionChanged += HandleSelectionChanged;
document.Editor.Parent.BeginHover += HandleBeginHover;
}
void HandleBeginHover (object sender, EventArgs e)
{
CancelSmartTagPopupTimeout ();
CancelMenuCloseTimer ();
}
void StartMenuCloseTimer ()
{
CancelMenuCloseTimer ();
menuCloseTimeoutId = GLib.Timeout.Add (menuTimeout, delegate {
/*if (codeActionMenu != null) {
codeActionMenu.Destroy ();
codeActionMenu = null;
}*/
menuCloseTimeoutId = 0;
return false;
});
}
void HandleSelectionChanged (object sender, EventArgs e)
{
CursorPositionChanged ();
}
void HandleDocumentDocumentParsed (object sender, EventArgs e)
{
CursorPositionChanged ();
}
[CommandUpdateHandler(RefactoryCommands.QuickFix)]
public void UpdateQuickFixCommand (CommandInfo ci)
{
if (QuickTaskStrip.EnableFancyFeatures) {
ci.Enabled = currentSmartTag != null;
} else {
ci.Enabled = true;
}
}
[CommandHandler(RefactoryCommands.QuickFix)]
void OnQuickFixCommand ()
{
if (!QuickTaskStrip.EnableFancyFeatures) {
Fixes = RefactoringService.GetValidActions (Document, Document.Editor.Caret.Location).Result;
currentSmartTagBegin = Document.Editor.Caret.Location;
PopupQuickFixMenu (null, null);
return;
}
if (currentSmartTag == null)
return;
currentSmartTag.Popup ();
}
static readonly List<CodeAction> emptyList = new List<CodeAction> ();
internal List<CodeAction> GetCurrentFixes ()
{
return currentSmartTag == null ? emptyList : currentSmartTag.fixes;
}
}
}
|