-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathRecentItemList.cs
More file actions
623 lines (532 loc) · 15 KB
/
RecentItemList.cs
File metadata and controls
623 lines (532 loc) · 15 KB
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
namespace Menees.Windows.Forms
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
#endregion
/// <summary>
/// Used to manage a list of recent items (e.g., files, projects, directories).
/// </summary>
[DefaultEvent(nameof(ItemClick))]
[ToolboxBitmap(typeof(RecentItemList), "Images.RecentItemList.bmp")]
public partial class RecentItemList : Component
{
#region Private Data Members
private const string DefaultSettingsNodeName = "Recent Items";
private readonly List<string> items = [];
private readonly Dictionary<string, IEnumerable<string>?> itemToValuesMap =
new(StringComparer.OrdinalIgnoreCase);
private int maxItems = 10;
private FormSaver? formSaver;
private string settingsNodeName = DefaultSettingsNodeName;
private ToolStripMenuItem? menuItem;
private ContextMenuStrip? contextMenu;
private EventHandler<SettingsEventArgs>? loadHandler;
private EventHandler<SettingsEventArgs>? saveHandler;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance.
/// </summary>
public RecentItemList()
{
this.InitializeComponent();
}
/// <summary>
/// Creates a new instance for the specified container.
/// </summary>
public RecentItemList(IContainer container)
{
container.Add(this);
this.InitializeComponent();
}
#endregion
#region Public Events
/// <summary>
/// Called when a "recent item" menu item is clicked.
/// </summary>
[Browsable(true)]
[Category("Action")]
[Description("Called when a \"recent item\" menu item is clicked.")]
public event EventHandler<RecentItemClickEventArgs>? ItemClick;
#endregion
#region Public Properties
/// <summary>
/// Gets or sets the maximum number of recent items to manage.
/// </summary>
[Browsable(true)]
[DefaultValue(10)]
[Category("Behavior")]
[Description("The maximum number of recent items to manage.")]
public int MaxItemCount
{
get
{
return this.maxItems;
}
set
{
this.maxItems = Math.Max(0, value);
this.CropItemsAndUpdate(false);
}
}
/// <summary>
/// Gets or sets the node name where recent item settings should be saved. This must be non-empty.
/// </summary>
[Browsable(true)]
[DefaultValue(DefaultSettingsNodeName)]
[Category("Behavior")]
[Description("The node name where recent item settings should be saved. This must be non-empty.")]
public string SettingsNodeName
{
get
{
return this.settingsNodeName;
}
set
{
// The section name must be non-empty because Save needs to delete the
// recent items SettingsNode, and we don't want it to delete the base key instead.
Conditions.RequireString(value, nameof(value));
this.settingsNodeName = value.Trim();
}
}
/// <summary>
/// Gets or sets the <see cref="FormSaver"/> object used to save and load settings.
/// </summary>
[Browsable(true)]
[DefaultValue(null)]
[Category("Helper Objects")]
[Description("The FormSaver object used to save and load settings.")]
public FormSaver? FormSaver
{
get
{
return this.formSaver;
}
set
{
if (this.formSaver != value)
{
// Detach from old events
if (this.formSaver != null)
{
this.formSaver.InternalLoadSettings -= this.loadHandler;
this.formSaver.InternalSaveSettings -= this.saveHandler;
}
this.formSaver = value;
// Attach to new events
if (this.formSaver != null)
{
// Create event handlers
this.loadHandler ??= new EventHandler<SettingsEventArgs>(this.OnLoadSettings);
this.saveHandler ??= new EventHandler<SettingsEventArgs>(this.OnSaveSettings);
// Attach to the internal events so we're assured of getting
// called before the public events. This ensures that normal
// MainForm.FormSaver_LoadSettings event handlers fire after
// the recent items have been loaded, which forms sometimes
// need to check if they want to reload the last item used.
this.formSaver.InternalLoadSettings += this.loadHandler;
this.formSaver.InternalSaveSettings += this.saveHandler;
}
}
}
}
/// <summary>
/// Gets or sets the menu item that should contain the recent items.
/// </summary>
[Browsable(true)]
[DefaultValue(null)]
[Category("Helper Objects")]
[Description("The menu item that should contain the recent items.")]
public ToolStripMenuItem? MenuItem
{
get
{
return this.menuItem;
}
set
{
if (this.menuItem != value)
{
// Delete any menu items on the old menu
this.DeleteMenuItems();
this.menuItem = value;
// Build the new menu
this.UpdateMenu();
}
}
}
/// <summary>
/// Gets or sets the context menu that should contain the recent items.
/// </summary>
[Browsable(true)]
[DefaultValue(null)]
[Category("Helper Objects")]
[Description("The context menu that should contain the recent items.")]
public ContextMenuStrip? ContextMenuStrip
{
get
{
return this.contextMenu;
}
set
{
if (this.contextMenu != value)
{
this.DeleteMenuItems();
this.contextMenu = value;
this.UpdateMenu();
}
}
}
/// <summary>
/// Gets the current number of items.
/// </summary>
[Browsable(false)]
[Description("The current number of items.")]
public int Count => this.items.Count;
/// <summary>
/// Gets or sets the list of items as a collection of strings.
/// </summary>
[Browsable(false)]
[Description("Gets or sets the list of items as a collection of strings.")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public IEnumerable<string> Items
{
get
{
// Return a copy, so the caller can't muck with our internal list.
string[] result = [.. this.items];
return result;
}
set
{
// Get rid of the old menu items and item data.
this.DeleteMenuItems();
this.items.Clear();
this.itemToValuesMap.Clear();
// Add the new items.
if (value != null)
{
this.items.AddRange(value.Where(s => !string.IsNullOrWhiteSpace(s)));
}
// Rebuild the menu
this.CropItemsAndUpdate(true);
}
}
/// <summary>
/// Gets the item for the specified index.
/// </summary>
/// <param name="index">The 0-based index of an item.</param>
/// <returns>The requested item.</returns>
[Browsable(false)]
[Description("Gets the item for the specified index.")]
public string this[int index] => this.items[index];
#endregion
#region Public Methods
/// <summary>
/// Gets whether the specified menu item is a dummy "<None>" menu item.
/// </summary>
/// <remarks>
/// This is useful in advanced scenarios where a parent form needs to disable
/// a menu recursively (e.g., if it's switching from one "editor" to another)
/// and then re-enable it later. The "None" menu items should never be enabled.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static bool IsNoneMenuItem(ToolStripMenuItem menuItem)
{
Conditions.RequireReference(menuItem, nameof(menuItem));
bool result = menuItem is NoneMenuItem;
return result;
}
/// <summary>
/// Adds an item to the list.
/// </summary>
/// <param name="item">The item to add.</param>
public void Add(string item)
{
this.Add(item, null);
}
/// <summary>
/// Adds an item to the list along with associated values.
/// </summary>
/// <param name="item">The item to add.</param>
/// <param name="values">An optional array of values to associate with the item.</param>
public void Add(string item, IEnumerable<string>? values)
{
Conditions.RequireString(item, nameof(item));
item = item.Trim();
if (item.Length > 0)
{
this.Remove(item);
this.items.Insert(0, item);
this.itemToValuesMap[item] = values;
this.CropItemsAndUpdate(true);
}
}
/// <summary>
/// Removes an item from the list.
/// </summary>
/// <param name="item">The item to remove.</param>
/// <returns>True if the item was found and removed.</returns>
public bool Remove(string item)
{
Conditions.RequireString(item, nameof(item));
bool result = false;
item = item.Trim();
int index = this.IndexOf(item);
if (index >= 0)
{
this.items.RemoveAt(index);
this.itemToValuesMap.Remove(item);
result = true;
this.UpdateMenu();
}
return result;
}
/// <summary>
/// Gets the 0-based index of an item.
/// </summary>
/// <param name="item">An item to lookup.</param>
/// <returns>The 0-based index of an item, or -1 if the item isn't found.</returns>
public int IndexOf(string item)
{
int result = -1;
// Note: We can't use this.items.IndexOf() because it is case-sensitive.
int count = this.items.Count;
for (int i = 0; i < count; i++)
{
if (string.Compare(item, this.items[i], StringComparison.OrdinalIgnoreCase) == 0)
{
result = i;
break;
}
}
return result;
}
/// <summary>
/// Removes all items from the list.
/// </summary>
public void Clear()
{
this.items.Clear();
this.itemToValuesMap.Clear();
this.UpdateMenu();
}
/// <summary>
/// Loads the recent item settings.
/// </summary>
/// <param name="baseNode">The base settings node to look for <see cref="SettingsNodeName"/> under.</param>
public void Load(ISettingsNode baseNode)
{
Conditions.RequireReference(baseNode, nameof(baseNode));
ISettingsNode? settingsNode = baseNode.TryGetSubNode(this.SettingsNodeName);
if (settingsNode != null)
{
int itemIndex = 0;
while (true)
{
string? item = settingsNode.GetValue(itemIndex.ToString(), string.Empty);
if (item.IsEmpty())
{
break;
}
this.items.Add(item);
// Load any custom values if they exist.
ISettingsNode? valuesNode = settingsNode.TryGetSubNode(itemIndex + "_Values");
if (valuesNode != null)
{
int count = valuesNode.GetValue(nameof(this.Count), 0);
string[] values = new string[count];
for (int stringIndex = 0; stringIndex < count; stringIndex++)
{
values[stringIndex] = valuesNode.GetValue(stringIndex.ToString(), string.Empty) ?? string.Empty;
}
this.itemToValuesMap[item] = values;
}
itemIndex++;
}
}
this.UpdateMenu();
}
/// <summary>
/// Saves the recent item settings.
/// </summary>
/// <param name="baseNode">The base settings node to look for <see cref="SettingsNodeName"/> under.</param>
public void Save(ISettingsNode baseNode)
{
Conditions.RequireReference(baseNode, nameof(baseNode));
// Clear out any old settings.
ISettingsNode? settingsNode = baseNode.TryGetSubNode(this.SettingsNodeName);
if (settingsNode != null)
{
baseNode.DeleteSubNode(this.SettingsNodeName);
}
// (Re)Create the section key.
settingsNode = baseNode.GetSubNode(this.SettingsNodeName);
if (settingsNode != null)
{
int numItems = this.items.Count;
for (int itemIndex = 0; itemIndex < numItems; itemIndex++)
{
string item = this.items[itemIndex];
settingsNode.SetValue(itemIndex.ToString(), item);
// If they attached custom values to the item, then save those too.
this.itemToValuesMap.TryGetValue(item, out IEnumerable<string>? values);
if (values != null)
{
ISettingsNode valuesNode = settingsNode.GetSubNode(itemIndex + "_Values")!;
int count = values.Count();
valuesNode.SetValue(nameof(this.Count), count);
int stringIndex = 0;
foreach (string value in values)
{
valuesNode.SetValue(stringIndex.ToString(), value);
stringIndex++;
}
}
}
}
}
/// <summary>
/// Gets the values associated with an item.
/// </summary>
/// <param name="item">An item to lookup.</param>
/// <returns>The values associated with the item. This can be null.</returns>
public IEnumerable<string>? GetItemValues(string item)
{
this.itemToValuesMap.TryGetValue(item, out IEnumerable<string>? result);
return result;
}
#endregion
#region Private Methods
private void CropItemsAndUpdate(bool update)
{
while (this.items.Count > this.maxItems && this.items.Count > 0)
{
update = true;
string item = this.items[this.items.Count - 1];
this.items.RemoveAt(this.items.Count - 1);
this.itemToValuesMap.Remove(item);
}
if (update)
{
this.UpdateMenu();
}
}
private void AddMenuItems()
{
if (this.menuItem != null)
{
this.AddMenuItems(this.menuItem.DropDownItems);
}
if (this.contextMenu != null)
{
this.AddMenuItems(this.contextMenu.Items);
}
}
private void AddMenuItems(ToolStripItemCollection menuItems)
{
if (!this.DesignMode && menuItems != null)
{
int numItems = this.items.Count;
if (numItems > 0)
{
for (int i = 0; i < numItems; i++)
{
string item = this.items[i];
const int MaxSingleDigitNumber = 9;
string menuText = string.Format("{0}{1}: {2}", (i < MaxSingleDigitNumber) ? "&" : string.Empty, i + 1, item);
this.itemToValuesMap.TryGetValue(item, out IEnumerable<string>? values);
ToolStripMenuItem menuItem = new RecentItemMenuItem(menuText, new EventHandler(this.OnMenuItemClick), item, values);
menuItems.Add(menuItem);
}
}
else
{
// Add a disabled dummy item with no Click handler.
menuItems.Add(new NoneMenuItem());
}
}
}
private void DeleteMenuItems()
{
if (this.menuItem != null)
{
this.DeleteMenuItems(this.menuItem.DropDownItems);
}
if (this.contextMenu != null)
{
this.DeleteMenuItems(this.contextMenu.Items);
}
}
private void DeleteMenuItems(ToolStripItemCollection menuItems)
{
if (!this.DesignMode && menuItems != null)
{
menuItems.Clear();
}
}
private void UpdateMenu()
{
this.DeleteMenuItems();
this.AddMenuItems();
}
private void OnMenuItemClick(object? sender, EventArgs e)
{
if (this.ItemClick != null && sender is RecentItemMenuItem menuItem)
{
this.ItemClick(this, new RecentItemClickEventArgs(menuItem.Item, menuItem.Values));
}
}
private void OnLoadSettings(object? sender, SettingsEventArgs e)
{
if (!this.DesignMode)
{
this.Load(e.SettingsNode);
}
}
private void OnSaveSettings(object? sender, SettingsEventArgs e)
{
if (!this.DesignMode)
{
this.Save(e.SettingsNode);
}
}
#endregion
#region Private Types
private sealed class RecentItemMenuItem : ToolStripMenuItem
{
#region Constructors
public RecentItemMenuItem(string text, EventHandler eh, string item, IEnumerable<string>? values)
: base(text, null, eh)
{
this.Item = item;
this.Values = values;
}
#endregion
#region Public Properties
public string Item { get; }
public IEnumerable<string>? Values { get; }
#endregion
}
private sealed class NoneMenuItem : ToolStripMenuItem
{
#region Constructors
public NoneMenuItem()
{
this.Text = "<None>";
this.Enabled = false;
}
#endregion
}
#endregion
}
}