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
|
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using System.Linq;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Rendering;
using ICSharpCode.AvalonEdit.Utils;
namespace ICSharpCode.AvalonEdit.CodeCompletion
{
/// <summary>
/// Base class for completion windows. Handles positioning the window at the caret.
/// </summary>
public class CompletionWindowBase : Window
{
static CompletionWindowBase()
{
WindowStyleProperty.OverrideMetadata(typeof(CompletionWindowBase), new FrameworkPropertyMetadata(WindowStyle.None));
ShowActivatedProperty.OverrideMetadata(typeof(CompletionWindowBase), new FrameworkPropertyMetadata(Boxes.False));
ShowInTaskbarProperty.OverrideMetadata(typeof(CompletionWindowBase), new FrameworkPropertyMetadata(Boxes.False));
}
/// <summary>
/// Gets the parent TextArea.
/// </summary>
public TextArea TextArea { get; private set; }
Window parentWindow;
TextDocument document;
/// <summary>
/// Gets/Sets the start of the text range in which the completion window stays open.
/// This text portion is used to determine the text used to select an entry in the completion list by typing.
/// </summary>
public int StartOffset { get; set; }
/// <summary>
/// Gets/Sets the end of the text range in which the completion window stays open.
/// This text portion is used to determine the text used to select an entry in the completion list by typing.
/// </summary>
public int EndOffset { get; set; }
/// <summary>
/// Gets whether the window was opened above the current line.
/// </summary>
protected bool IsUp { get; private set; }
/// <summary>
/// Creates a new CompletionWindowBase.
/// </summary>
public CompletionWindowBase(TextArea textArea)
{
if (textArea == null)
throw new ArgumentNullException("textArea");
this.TextArea = textArea;
parentWindow = Window.GetWindow(textArea);
this.Owner = parentWindow;
this.AddHandler(MouseUpEvent, new MouseButtonEventHandler(OnMouseUp), true);
StartOffset = EndOffset = this.TextArea.Caret.Offset;
AttachEvents();
}
#region Event Handlers
void AttachEvents()
{
document = this.TextArea.Document;
if (document != null) {
document.Changing += textArea_Document_Changing;
}
// LostKeyboardFocus seems to be more reliable than PreviewLostKeyboardFocus - see SD-1729
this.TextArea.LostKeyboardFocus += TextAreaLostFocus;
this.TextArea.TextView.ScrollOffsetChanged += TextViewScrollOffsetChanged;
this.TextArea.DocumentChanged += TextAreaDocumentChanged;
if (parentWindow != null) {
parentWindow.LocationChanged += parentWindow_LocationChanged;
}
// close previous completion windows of same type
foreach (InputHandler x in this.TextArea.StackedInputHandlers.OfType<InputHandler>()) {
if (x.window.GetType() == this.GetType())
this.TextArea.PopStackedInputHandler(x);
}
myInputHandler = new InputHandler(this);
this.TextArea.PushStackedInputHandler(myInputHandler);
}
/// <summary>
/// Detaches events from the text area.
/// </summary>
protected virtual void DetachEvents()
{
if (document != null) {
document.Changing -= textArea_Document_Changing;
}
this.TextArea.LostKeyboardFocus -= TextAreaLostFocus;
this.TextArea.TextView.ScrollOffsetChanged -= TextViewScrollOffsetChanged;
this.TextArea.DocumentChanged -= TextAreaDocumentChanged;
if (parentWindow != null) {
parentWindow.LocationChanged -= parentWindow_LocationChanged;
}
this.TextArea.PopStackedInputHandler(myInputHandler);
}
#region InputHandler
InputHandler myInputHandler;
/// <summary>
/// A dummy input handler (that justs invokes the default input handler).
/// This is used to ensure the completion window closes when any other input handler
/// becomes active.
/// </summary>
sealed class InputHandler : TextAreaStackedInputHandler
{
internal readonly CompletionWindowBase window;
public InputHandler(CompletionWindowBase window)
: base(window.TextArea)
{
Debug.Assert(window != null);
this.window = window;
}
public override void Detach()
{
base.Detach();
window.Close();
}
const Key KeyDeadCharProcessed = (Key)0xac; // Key.DeadCharProcessed; // new in .NET 4
public override void OnPreviewKeyDown(KeyEventArgs e)
{
// prevents crash when typing deadchar while CC window is open
if (e.Key == KeyDeadCharProcessed)
return;
e.Handled = RaiseEventPair(window, PreviewKeyDownEvent, KeyDownEvent,
new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, e.Key));
}
public override void OnPreviewKeyUp(KeyEventArgs e)
{
if (e.Key == KeyDeadCharProcessed)
return;
e.Handled = RaiseEventPair(window, PreviewKeyUpEvent, KeyUpEvent,
new KeyEventArgs(e.KeyboardDevice, e.InputSource, e.Timestamp, e.Key));
}
}
#endregion
void TextViewScrollOffsetChanged(object sender, EventArgs e)
{
// Workaround for crash #1580 (reproduction steps unknown):
// NullReferenceException in System.Windows.Window.CreateSourceWindow()
if (!sourceIsInitialized)
return;
IScrollInfo scrollInfo = this.TextArea.TextView;
Rect visibleRect = new Rect(scrollInfo.HorizontalOffset, scrollInfo.VerticalOffset, scrollInfo.ViewportWidth, scrollInfo.ViewportHeight);
// close completion window when the user scrolls so far that the anchor position is leaving the visible area
if (visibleRect.Contains(visualLocation) || visibleRect.Contains(visualLocationTop))
UpdatePosition();
else
Close();
}
void TextAreaDocumentChanged(object sender, EventArgs e)
{
Close();
}
void TextAreaLostFocus(object sender, RoutedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(CloseIfFocusLost), DispatcherPriority.Background);
}
void parentWindow_LocationChanged(object sender, EventArgs e)
{
UpdatePosition();
}
/// <inheritdoc/>
protected override void OnDeactivated(EventArgs e)
{
base.OnDeactivated(e);
Dispatcher.BeginInvoke(new Action(CloseIfFocusLost), DispatcherPriority.Background);
}
#endregion
/// <summary>
/// Raises a tunnel/bubble event pair for a WPF control.
/// </summary>
/// <param name="target">The WPF control for which the event should be raised.</param>
/// <param name="previewEvent">The tunneling event.</param>
/// <param name="event">The bubbling event.</param>
/// <param name="args">The event args to use.</param>
/// <returns>The <see cref="RoutedEventArgs.Handled"/> value of the event args.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")]
protected static bool RaiseEventPair(UIElement target, RoutedEvent previewEvent, RoutedEvent @event, RoutedEventArgs args)
{
if (target == null)
throw new ArgumentNullException("target");
if (previewEvent == null)
throw new ArgumentNullException("previewEvent");
if (@event == null)
throw new ArgumentNullException("event");
if (args == null)
throw new ArgumentNullException("args");
args.RoutedEvent = previewEvent;
target.RaiseEvent(args);
args.RoutedEvent = @event;
target.RaiseEvent(args);
return args.Handled;
}
// Special handler: handledEventsToo
void OnMouseUp(object sender, MouseButtonEventArgs e)
{
ActivateParentWindow();
}
/// <summary>
/// Activates the parent window.
/// </summary>
protected virtual void ActivateParentWindow()
{
if (parentWindow != null)
parentWindow.Activate();
}
void CloseIfFocusLost()
{
if (CloseOnFocusLost) {
Debug.WriteLine("CloseIfFocusLost: this.IsActive=" + this.IsActive + " IsTextAreaFocused=" + IsTextAreaFocused);
if (!this.IsActive && !IsTextAreaFocused) {
Close();
}
}
}
/// <summary>
/// Gets whether the completion window should automatically close when the text editor looses focus.
/// </summary>
protected virtual bool CloseOnFocusLost {
get { return true; }
}
bool IsTextAreaFocused {
get {
if (parentWindow != null && !parentWindow.IsActive)
return false;
return this.TextArea.IsKeyboardFocused;
}
}
bool sourceIsInitialized;
/// <inheritdoc/>
protected override void OnSourceInitialized(EventArgs e)
{
base.OnSourceInitialized(e);
if (document != null && this.StartOffset != this.TextArea.Caret.Offset) {
SetPosition(new TextViewPosition(document.GetLocation(this.StartOffset)));
} else {
SetPosition(this.TextArea.Caret.Position);
}
sourceIsInitialized = true;
}
/// <inheritdoc/>
protected override void OnClosed(EventArgs e)
{
base.OnClosed(e);
DetachEvents();
}
/// <inheritdoc/>
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (!e.Handled && e.Key == Key.Escape) {
e.Handled = true;
Close();
}
}
Point visualLocation, visualLocationTop;
/// <summary>
/// Positions the completion window at the specified position.
/// </summary>
protected void SetPosition(TextViewPosition position)
{
TextView textView = this.TextArea.TextView;
visualLocation = textView.GetVisualPosition(position, VisualYPosition.LineBottom);
visualLocationTop = textView.GetVisualPosition(position, VisualYPosition.LineTop);
UpdatePosition();
}
/// <summary>
/// Updates the position of the CompletionWindow based on the parent TextView position and the screen working area.
/// It ensures that the CompletionWindow is completely visible on the screen.
/// </summary>
protected void UpdatePosition()
{
TextView textView = this.TextArea.TextView;
// PointToScreen returns device dependent units (physical pixels)
Point location = textView.PointToScreen(visualLocation - textView.ScrollOffset);
Point locationTop = textView.PointToScreen(visualLocationTop - textView.ScrollOffset);
// Let's use device dependent units for everything
Size completionWindowSize = new Size(this.ActualWidth, this.ActualHeight).TransformToDevice(textView);
Rect bounds = new Rect(location, completionWindowSize);
Rect workingScreen = System.Windows.Forms.Screen.GetWorkingArea(location.ToSystemDrawing()).ToWpf();
if (!workingScreen.Contains(bounds)) {
if (bounds.Left < workingScreen.Left) {
bounds.X = workingScreen.Left;
} else if (bounds.Right > workingScreen.Right) {
bounds.X = workingScreen.Right - bounds.Width;
}
if (bounds.Bottom > workingScreen.Bottom) {
bounds.Y = locationTop.Y - bounds.Height;
IsUp = true;
} else {
IsUp = false;
}
if (bounds.Y < workingScreen.Top) {
bounds.Y = workingScreen.Top;
}
}
// Convert the window bounds to device independent units
bounds = bounds.TransformFromDevice(textView);
this.Left = bounds.X;
this.Top = bounds.Y;
}
/// <inheritdoc/>
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
if (sizeInfo.HeightChanged && IsUp) {
this.Top += sizeInfo.PreviousSize.Height - sizeInfo.NewSize.Height;
}
}
/// <summary>
/// Gets/sets whether the completion window should expect text insertion at the start offset,
/// which not go into the completion region, but before it.
/// </summary>
/// <remarks>This property allows only a single insertion, it is reset to false
/// when that insertion has occurred.</remarks>
public bool ExpectInsertionBeforeStart { get; set; }
void textArea_Document_Changing(object sender, DocumentChangeEventArgs e)
{
if (e.Offset + e.RemovalLength == this.StartOffset && e.RemovalLength > 0) {
Close(); // removal immediately in front of completion segment: close the window
// this is necessary when pressing backspace after dot-completion
}
if (e.Offset == StartOffset && e.RemovalLength == 0 && ExpectInsertionBeforeStart) {
StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.AfterInsertion);
this.ExpectInsertionBeforeStart = false;
} else {
StartOffset = e.GetNewOffset(StartOffset, AnchorMovementType.BeforeInsertion);
}
EndOffset = e.GetNewOffset(EndOffset, AnchorMovementType.AfterInsertion);
}
}
}
|