-
Notifications
You must be signed in to change notification settings - Fork 0
/
AutocompleteMenu.cs
736 lines (643 loc) · 23.2 KB
/
AutocompleteMenu.cs
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
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;
namespace secl
{
/// <summary>
/// Popup menu for autocomplete
/// </summary>
[Browsable(false)]
public class AutocompleteMenu : ToolStripDropDown, IDisposable
{
AutocompleteListView listView;
public ToolStripControlHost host;
public Range Fragment { get; internal set; }
/// <summary>
/// Regex pattern for serach fragment around caret
/// </summary>
public string SearchPattern { get; set; }
/// <summary>
/// Minimum fragment length for popup
/// </summary>
public int MinFragmentLength { get; set; }
/// <summary>
/// User selects item
/// </summary>
public event EventHandler<SelectingEventArgs> Selecting;
/// <summary>
/// It fires after item inserting
/// </summary>
public event EventHandler<SelectedEventArgs> Selected;
/// <summary>
/// Occurs when popup menu is opening
/// </summary>
public new event EventHandler<CancelEventArgs> Opening;
/// <summary>
/// Allow TAB for select menu item
/// </summary>
public bool AllowTabKey { get { return listView.AllowTabKey; } set { listView.AllowTabKey = value; } }
/// <summary>
/// Interval of menu appear (ms)
/// </summary>
public int AppearInterval { get { return listView.AppearInterval; } set { listView.AppearInterval = value; } }
/// <summary>
/// Back color of selected item
/// </summary>
[DefaultValue(typeof(Color), "Orange")]
public Color SelectedColor
{
get { return listView.SelectedColor; }
set { listView.SelectedColor = value; }
}
/// <summary>
/// Border color of hovered item
/// </summary>
[DefaultValue(typeof(Color), "Red")]
public Color HoveredColor
{
get { return listView.HoveredColor; }
set { listView.HoveredColor = value; }
}
public AutocompleteMenu(SharpControl tb)
{
// create a new popup and add the list view to it
AutoClose = false;
AutoSize = false;
Margin = Padding.Empty;
Padding = Padding.Empty;
BackColor = Color.White;
listView = new AutocompleteListView(tb);
host = new ToolStripControlHost(listView);
host.Margin = new Padding(2, 2, 2, 2);
host.Padding = Padding.Empty;
host.AutoSize = false;
host.AutoToolTip = false;
CalcSize();
base.Items.Add(host);
listView.Parent = this;
SearchPattern = @"[\w\.]";
MinFragmentLength = 2;
}
public new Font Font
{
get { return listView.Font; }
set { listView.Font = value; }
}
new internal void OnOpening(CancelEventArgs args)
{
if (Opening != null)
Opening(this, args);
}
public new void Close()
{
listView.toolTip.Hide(listView);
base.Close();
}
internal void CalcSize()
{
host.Size = listView.Size;
Size = new System.Drawing.Size(listView.Size.Width + 4, listView.Size.Height + 4);
}
public virtual void OnSelecting()
{
listView.OnSelecting();
}
public void SelectNext(int shift)
{
listView.SelectNext(shift);
}
internal void OnSelecting(SelectingEventArgs args)
{
if (Selecting != null)
Selecting(this, args);
}
public void OnSelected(SelectedEventArgs args)
{
if (Selected != null)
Selected(this, args);
}
public new AutocompleteListView Items
{
get { return listView; }
}
/// <summary>
/// Shows popup menu immediately
/// </summary>
/// <param name="forced">If True - MinFragmentLength will be ignored</param>
public void Show(bool forced)
{
Items.DoAutocomplete(forced);
}
/// <summary>
/// Minimal size of menu
/// </summary>
public new Size MinimumSize
{
get { return Items.MinimumSize; }
set { Items.MinimumSize = value; }
}
/// <summary>
/// Image list of menu
/// </summary>
public new ImageList ImageList
{
get { return Items.ImageList; }
set { Items.ImageList = value; }
}
/// <summary>
/// Tooltip duration (ms)
/// </summary>
public int ToolTipDuration
{
get { return Items.ToolTipDuration; }
set { Items.ToolTipDuration = value; }
}
/// <summary>
/// Tooltip
/// </summary>
public ToolTip ToolTip
{
get { return Items.toolTip; }
set { Items.toolTip = value; }
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (listView != null && !listView.IsDisposed)
listView.Dispose();
}
}
[System.ComponentModel.ToolboxItem(false)]
public class AutocompleteListView : UserControl
{
public event EventHandler FocussedItemIndexChanged;
internal List<AutocompleteItem> visibleItems;
IEnumerable<AutocompleteItem> sourceItems = new List<AutocompleteItem>();
int focussedItemIndex = 0;
int hoveredItemIndex = -1;
private int ItemHeight
{
get { return Font.Height + 2; }
}
AutocompleteMenu Menu { get { return Parent as AutocompleteMenu; } }
int oldItemCount = 0;
SharpControl tb;
internal ToolTip toolTip = new ToolTip();
System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();
internal bool AllowTabKey { get; set; }
public ImageList ImageList { get; set; }
internal int AppearInterval { get { return timer.Interval; } set { timer.Interval = value; } }
internal int ToolTipDuration { get; set; }
public Color SelectedColor { get; set; }
public Color HoveredColor { get; set; }
public int FocussedItemIndex
{
get { return focussedItemIndex; }
set
{
if (focussedItemIndex != value)
{
focussedItemIndex = value;
if (FocussedItemIndexChanged != null)
FocussedItemIndexChanged(this, EventArgs.Empty);
}
}
}
public AutocompleteItem FocussedItem
{
get
{
if (FocussedItemIndex >= 0 && focussedItemIndex < visibleItems.Count)
return visibleItems[focussedItemIndex];
return null;
}
set
{
FocussedItemIndex = visibleItems.IndexOf(value);
}
}
internal AutocompleteListView(SharpControl tb)
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.UserPaint, true);
base.Font = new Font(FontFamily.GenericSansSerif, 9);
visibleItems = new List<AutocompleteItem>();
VerticalScroll.SmallChange = ItemHeight;
MaximumSize = new Size(Size.Width, 180);
toolTip.ShowAlways = false;
AppearInterval = 500;
timer.Tick += new EventHandler(timer_Tick);
SelectedColor = Color.Orange;
HoveredColor = Color.Red;
ToolTipDuration = 3000;
this.tb = tb;
tb.KeyDown += new KeyEventHandler(tb_KeyDown);
tb.SelectionChanged += new EventHandler(tb_SelectionChanged);
tb.KeyPressed += new KeyPressEventHandler(tb_KeyPressed);
Form form = tb.FindForm();
if (form != null)
{
form.LocationChanged += delegate { SafetyClose(); };
form.ResizeBegin += delegate { SafetyClose(); };
form.FormClosing += delegate { SafetyClose(); };
form.LostFocus += delegate { SafetyClose(); };
}
tb.LostFocus += (o, e) =>
{
if (Menu != null && !Menu.IsDisposed)
if (!Menu.Focused)
SafetyClose();
};
tb.Scroll += delegate { SafetyClose(); };
this.VisibleChanged += (o, e) =>
{
if (this.Visible)
DoSelectedVisible();
};
}
void SafetyClose()
{
if (Menu != null && !Menu.IsDisposed)
Menu.Close();
}
void tb_KeyPressed(object sender, KeyPressEventArgs e)
{
bool backspaceORdel = e.KeyChar == '\b' || e.KeyChar == 0xff;
/*
if (backspaceORdel)
prevSelection = tb.Selection.Start;*/
if (Menu.Visible && !backspaceORdel)
DoAutocomplete(true);
else
ResetTimer(timer);
}
void timer_Tick(object sender, EventArgs e)
{
timer.Stop();
DoAutocomplete(true);
}
void ResetTimer(System.Windows.Forms.Timer timer)
{
timer.Stop();
timer.Start();
}
internal void DoAutocomplete()
{
DoAutocomplete(true);
}
internal void DoAutocomplete(bool forced)
{
if (!Menu.Enabled)
{
Menu.Close();
return;
}
visibleItems.Clear();
FocussedItemIndex = 0;
VerticalScroll.Value = 0;
//some magic for update scrolls
AutoScrollMinSize -= new Size(1, 0);
AutoScrollMinSize += new Size(1, 0);
//get fragment around caret
Range fragment = tb.Selection.GetFragment(Menu.SearchPattern);
string text = fragment.Text;
//calc screen point for popup menu
Point point = tb.PlaceToPoint(fragment.End);
point.Offset(2, tb.CharHeight);
//
if (forced || (text.Length >= Menu.MinFragmentLength
&& tb.Selection.IsEmpty /*pops up only if selected range is empty*/
&& (tb.Selection.Start > fragment.Start || text.Length == 0/*pops up only if caret is after first letter*/)))
{
Menu.Fragment = fragment;
bool foundSelected = false;
//build popup menu
foreach (var item in sourceItems)
{
item.Parent = Menu;
CompareResult res = item.Compare(text);
if(res != CompareResult.Hidden)
visibleItems.Add(item);
if (res == CompareResult.VisibleAndSelected && !foundSelected)
{
foundSelected = true;
FocussedItemIndex = visibleItems.Count - 1;
}
}
if (foundSelected)
{
AdjustScroll();
DoSelectedVisible();
}
}
//show popup menu
if (Count > 0)
{
if (!Menu.Visible)
{
CancelEventArgs args = new CancelEventArgs();
Menu.OnOpening(args);
if(!args.Cancel)
Menu.Show(tb, point);
}
else
Invalidate();
}
else
Menu.Close();
}
void tb_SelectionChanged(object sender, EventArgs e)
{
/*
SharpControl tb = sender as SharpControl;
if (Math.Abs(prevSelection.iChar - tb.Selection.Start.iChar) > 1 ||
prevSelection.iLine != tb.Selection.Start.iLine)
Menu.Close();
prevSelection = tb.Selection.Start;*/
if (Menu.Visible)
{
bool needClose = false;
if (!tb.Selection.IsEmpty)
needClose = true;
else
if (!Menu.Fragment.Contains(tb.Selection.Start))
{
if (tb.Selection.Start.iLine == Menu.Fragment.End.iLine && tb.Selection.Start.iChar == Menu.Fragment.End.iChar + 1)
{
//user press key at end of fragment
char c = tb.Selection.CharBeforeStart;
if (!Regex.IsMatch(c.ToString(), Menu.SearchPattern))//check char
needClose = true;
}
else
needClose = true;
}
if (needClose)
Menu.Close();
}
}
void tb_KeyDown(object sender, KeyEventArgs e)
{
var tb = sender as SharpControl;
if (Menu.Visible)
if (ProcessKey(e.KeyCode, e.Modifiers))
e.Handled = true;
if (!Menu.Visible)
{
if (tb.HotkeysMapping.ContainsKey(e.KeyData) && tb.HotkeysMapping[e.KeyData] == FCTBAction.AutocompleteMenu)
{
DoAutocomplete();
e.Handled = true;
}
else
{
if (e.KeyCode == Keys.Escape && timer.Enabled)
timer.Stop();
}
}
}
void AdjustScroll()
{
if (oldItemCount == visibleItems.Count)
return;
int needHeight = ItemHeight * visibleItems.Count + 1;
Height = Math.Min(needHeight, MaximumSize.Height);
Menu.CalcSize();
AutoScrollMinSize = new Size(0, needHeight);
oldItemCount = visibleItems.Count;
}
protected override void OnPaint(PaintEventArgs e)
{
AdjustScroll();
var itemHeight = ItemHeight;
int startI = VerticalScroll.Value / itemHeight - 1;
int finishI = (VerticalScroll.Value + ClientSize.Height) / itemHeight + 1;
startI = Math.Max(startI, 0);
finishI = Math.Min(finishI, visibleItems.Count);
int y = 0;
int leftPadding = 18;
for (int i = startI; i < finishI; i++)
{
y = i * itemHeight - VerticalScroll.Value;
var item = visibleItems[i];
using ( var brush = new SolidBrush(Color.White) )
{
e.Graphics.FillRectangle(brush, 1, y, ClientSize.Width - 1 - 1, itemHeight - 1);
}
if (i == FocussedItemIndex)
using (var selectedBrush = new LinearGradientBrush(new Point(0, y - 3), new Point(0, y + itemHeight), Color.Transparent, SelectedColor))
using (var pen = new Pen(SelectedColor))
{
e.Graphics.FillRectangle(new SolidBrush(ColorTranslator.FromHtml("#EAEAEA")), 0, y, ClientSize.Width - 1, itemHeight - 1);
e.Graphics.DrawRectangle(new Pen(ColorTranslator.FromHtml("#EFEFEF")), 0, y, ClientSize.Width - 1, itemHeight - 1);
}
if (i == hoveredItemIndex)
using(var pen = new Pen(HoveredColor))
e.Graphics.DrawRectangle(new Pen(ColorTranslator.FromHtml("#EFEFEF")), 0, y, ClientSize.Width - 1, itemHeight - 1);
using (var brush = new SolidBrush(item.ForeColor != Color.Transparent ? item.ForeColor : ForeColor))
e.Graphics.DrawString(item.ToString(), Font, brush, 0, y);
}
}
protected override void OnScroll(ScrollEventArgs se)
{
base.OnScroll(se);
Invalidate();
}
protected override void OnMouseClick(MouseEventArgs e)
{
base.OnMouseClick(e);
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
FocussedItemIndex = PointToItemIndex(e.Location);
DoSelectedVisible();
Invalidate();
}
}
protected override void OnMouseDoubleClick(MouseEventArgs e)
{
base.OnMouseDoubleClick(e);
FocussedItemIndex = PointToItemIndex(e.Location);
Invalidate();
OnSelecting();
}
internal virtual void OnSelecting()
{
if (FocussedItemIndex < 0 || FocussedItemIndex >= visibleItems.Count)
return;
tb.TextSource.Manager.BeginAutoUndoCommands();
try
{
AutocompleteItem item = FocussedItem;
SelectingEventArgs args = new SelectingEventArgs()
{
Item = item,
SelectedIndex = FocussedItemIndex
};
Menu.OnSelecting(args);
if (args.Cancel)
{
FocussedItemIndex = args.SelectedIndex;
Invalidate();
return;
}
if (!args.Handled)
{
var fragment = Menu.Fragment;
DoAutocomplete(item, fragment);
}
Menu.Close();
//
SelectedEventArgs args2 = new SelectedEventArgs()
{
Item = item,
Tb = Menu.Fragment.tb
};
item.OnSelected(Menu, args2);
Menu.OnSelected(args2);
}
finally
{
tb.TextSource.Manager.EndAutoUndoCommands();
}
}
private void DoAutocomplete(AutocompleteItem item, Range fragment)
{
string newText = item.GetTextForReplace();
//replace text of fragment
var tb = fragment.tb;
tb.BeginAutoUndo();
tb.TextSource.Manager.ExecuteCommand(new SelectCommand(tb.TextSource));
if (tb.Selection.ColumnSelectionMode)
{
var start = tb.Selection.Start;
var end = tb.Selection.End;
start.iChar = fragment.Start.iChar;
end.iChar = fragment.End.iChar;
tb.Selection.Start = start;
tb.Selection.End = end;
}
else
{
tb.Selection.Start = fragment.Start;
tb.Selection.End = fragment.End;
}
tb.InsertText(newText);
tb.TextSource.Manager.ExecuteCommand(new SelectCommand(tb.TextSource));
tb.EndAutoUndo();
tb.Focus();
}
int PointToItemIndex(Point p)
{
return (p.Y + VerticalScroll.Value) / ItemHeight;
}
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
ProcessKey(keyData, Keys.None);
return base.ProcessCmdKey(ref msg, keyData);
}
private bool ProcessKey(Keys keyData, Keys keyModifiers)
{
if (keyModifiers == Keys.None)
switch (keyData)
{
case Keys.Down:
SelectNext(+1);
return true;
case Keys.PageDown:
SelectNext(+10);
return true;
case Keys.Up:
SelectNext(-1);
return true;
case Keys.PageUp:
SelectNext(-10);
return true;
case Keys.Enter:
OnSelecting();
return true;
case Keys.Tab:
if (!AllowTabKey)
break;
OnSelecting();
return true;
case Keys.Escape:
Menu.Close();
return true;
}
return false;
}
public void SelectNext(int shift)
{
FocussedItemIndex = Math.Max(0, Math.Min(FocussedItemIndex + shift, visibleItems.Count - 1));
DoSelectedVisible();
//
Invalidate();
}
private void DoSelectedVisible()
{
if (FocussedItem != null)
SetToolTip(FocussedItem);
var y = FocussedItemIndex * ItemHeight - VerticalScroll.Value;
if (y < 0)
VerticalScroll.Value = FocussedItemIndex * ItemHeight;
if (y > ClientSize.Height - ItemHeight)
VerticalScroll.Value = Math.Min(VerticalScroll.Maximum, FocussedItemIndex * ItemHeight - ClientSize.Height + ItemHeight);
//some magic for update scrolls
AutoScrollMinSize -= new Size(1, 0);
AutoScrollMinSize += new Size(1, 0);
}
private void SetToolTip(AutocompleteItem autocompleteItem)
{
var title = autocompleteItem.ToolTipTitle;
var text = autocompleteItem.ToolTipText;
if (string.IsNullOrEmpty(title))
{
toolTip.ToolTipTitle = null;
toolTip.SetToolTip(this, null);
return;
}
IWin32Window window = this.Parent ?? this;
Point location = new Point((window == this ? Width : Right) + 3, 0);
if (string.IsNullOrEmpty(text))
{
toolTip.ToolTipTitle = null;
toolTip.Show(title, window, location.X, location.Y, ToolTipDuration);
}
else
{
toolTip.ToolTipTitle = title;
toolTip.Show(text, window, location.X, location.Y, ToolTipDuration);
}
}
public int Count
{
get { return visibleItems.Count; }
}
public void SetAutocompleteItems(ICollection<string> items)
{
List<AutocompleteItem> list = new List<AutocompleteItem>(items.Count);
foreach (var item in items)
list.Add(new AutocompleteItem(item));
SetAutocompleteItems(list);
}
public void SetAutocompleteItems(IEnumerable<AutocompleteItem> items)
{
sourceItems = items;
}
}
public class SelectingEventArgs : EventArgs
{
public AutocompleteItem Item { get; internal set; }
public bool Cancel {get;set;}
public int SelectedIndex{get;set;}
public bool Handled { get; set; }
}
public class SelectedEventArgs : EventArgs
{
public AutocompleteItem Item { get; internal set; }
public SharpControl Tb { get; set; }
}
}