-
Notifications
You must be signed in to change notification settings - Fork 450
Expand file tree
/
Copy pathControlExtensions.cs
More file actions
433 lines (371 loc) · 12.7 KB
/
ControlExtensions.cs
File metadata and controls
433 lines (371 loc) · 12.7 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
#nullable enable
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using BizHawk.Bizware.Graphics;
using BizHawk.Client.Common;
using BizHawk.Common;
using BizHawk.Common.CollectionExtensions;
using BizHawk.Common.ReflectionExtensions;
using BizHawk.Emulation.Common;
using static BizHawk.Common.CommctrlImports;
namespace BizHawk.Client.EmuHawk
{
public static class ControlExtensions
{
private const int WM_SETREDRAW = 0x000B;
/// <exception cref="ArgumentException"><typeparamref name="T"/> does not inherit <see cref="Enum"/></exception>
public static void PopulateFromEnum<T>(this ComboBox box, T enumVal)
where T : Enum
{
box.ReplaceItems(items: typeof(T).GetEnumDescriptions());
box.SelectedItem = enumVal.GetDescription();
}
public static ToolStripMenuItem ToColumnsMenu(this InputRoll inputRoll, Action changeCallback)
{
var menu = new ToolStripMenuItem
{
Name = "GeneratedColumnsSubMenu",
Text = "Columns",
};
var columns = inputRoll.AllColumns;
foreach (var column in columns)
{
var menuItem = new ToolStripMenuItem
{
Name = column.Name,
Text = $"{column.Text} ({column.Name})",
Checked = column.Visible,
CheckOnClick = true,
Tag = column.Name,
};
menuItem.CheckedChanged += (o, ev) =>
{
var sender = (ToolStripMenuItem)o;
columns.Find(c => c.Name == (string)sender.Tag).Visible = sender.Checked;
columns.ColumnsChanged();
changeCallback();
inputRoll.Refresh();
};
menu.DropDownItems.Add(menuItem);
}
return menu;
}
public static Point ChildPointToScreen(this Control control, Control child)
{
return control.PointToScreen(new Point(child.Location.X, child.Location.Y));
}
public static void FollowMousePointer(this Form form)
{
var point = Cursor.Position;
point.Offset(form.Width / -2, form.Height / -2);
form.StartPosition = FormStartPosition.Manual;
form.Location = point;
}
public static DialogResult ShowDialogOnScreen(this Form form)
{
var topLeft = new Point(
Math.Max(0, form.Location.X),
Math.Max(0, form.Location.Y));
var screen = DrawingExtensions.BoundsOfDisplayContaining(topLeft)
?? default; //TODO is zeroed the correct fallback value? --yoshi
var w = screen.Right - form.Bounds.Right;
var h = screen.Bottom - form.Bounds.Bottom;
if (h < 0) topLeft.Y += h;
if (w < 0) topLeft.X += w;
form.SetDesktopLocation(topLeft.X, topLeft.Y);
return form.ShowDialog();
}
public static Color Add(this Color color, int val)
{
var col = color.ToArgb();
col += val;
return Color.FromArgb(col);
}
/// <remarks>
/// Due to the way this is written, using it in a foreach (as is done in SNESGraphicsDebugger)
/// passes <c>Control</c> as the type parameter, meaning only properties on <see cref="Control"/> (and <see cref="Component"/>, etc.)
/// will be processed. Why is there even a type param at all? I certainly don't know. --yoshi
/// </remarks>
public static T Clone<T>(this T controlToClone)
where T : Control
{
PropertyInfo[] controlProperties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
Type t = controlToClone.GetType();
var instance = (T) Activator.CreateInstance(t);
t.GetProperty("AutoSize")?.SetMethod?.Invoke(instance, new object[] {false});
for (int i = 0; i < 3; i++) // why 3 passes of this? --yoshi
{
foreach (var propInfo in controlProperties)
{
if (!propInfo.CanWrite)
{
continue;
}
if (propInfo.Name != "AutoSize" && propInfo.Name != "WindowTarget")
{
propInfo.SetValue(instance, propInfo.GetValue(controlToClone, null), null);
}
}
}
if (controlToClone is RetainedViewportPanel rvpToClone && instance is RetainedViewportPanel rvpCloned)
{
rvpCloned.SetBitmap((Bitmap) rvpToClone.GetBitmap().Clone());
}
return instance;
}
/// <summary>
/// Converts the outdated IEnumerable Controls property to an <see cref="IEnumerable{T}"/> like .NET should have done a long time ago
/// </summary>
public static IEnumerable<Control> Controls(this Control control)
=> control.Controls.Cast<Control>();
public static IEnumerable<TabPage> TabPages(this TabControl tabControl)
{
return tabControl.TabPages.Cast<TabPage>();
}
public static Control? InnermostControlAt(this Form form, Point pos, GetChildAtPointSkip flags = GetChildAtPointSkip.None)
{
Control? top = form;
Control? found;
do
{
found = top!.GetChildAtPoint(top.PointToClient(pos), flags);
top = found;
} while (found is { HasChildren: true });
return found;
}
#pragma warning disable CS0618 // WinForms doesn't use generics ofc
public static bool InsertAfter(this ToolStripItemCollection items, ToolStripItem needle, ToolStripItem insert)
=> ((IList) items).InsertAfter(needle, insert: insert);
public static bool InsertAfterLast(this ToolStripItemCollection items, ToolStripItem needle, ToolStripItem insert)
=> ((IList) items).InsertAfterLast(needle, insert: insert);
public static bool InsertBefore(this ToolStripItemCollection items, ToolStripItem needle, ToolStripItem insert)
=> ((IList) items).InsertBefore(needle, insert: insert);
public static bool InsertBeforeLast(this ToolStripItemCollection items, ToolStripItem needle, ToolStripItem insert)
=> ((IList) items).InsertBeforeLast(needle, insert: insert);
#pragma warning restore CS0618
public static void ReplaceDropDownItems(this ToolStripDropDownItem menu, params ToolStripItem[] items)
{
menu.DropDownItems.Clear();
menu.DropDownItems.AddRange(items);
}
public static void ReplaceItems(this ComboBox dropdown, params object[] items)
{
dropdown.Items.Clear();
dropdown.Items.AddRange(items);
}
public static void ReplaceItems(this ComboBox dropdown, IEnumerable<object> items)
=> dropdown.ReplaceItems(items: items.ToArray());
public static CheckState ToCheckState(this bool? tristate)
=> tristate switch
{
true => CheckState.Checked,
false => CheckState.Unchecked,
null => CheckState.Indeterminate,
};
public static void SuspendDrawing(this Control control)
{
if (!OSTailoredCode.IsUnixHost)
{
WmImports.SendMessageW(control.Handle, WM_SETREDRAW, (IntPtr) 0, IntPtr.Zero);
}
}
public static void ResumeDrawing(this Control control)
{
if (!OSTailoredCode.IsUnixHost)
{
WmImports.SendMessageW(control.Handle, WM_SETREDRAW, (IntPtr) 1, IntPtr.Zero);
}
}
}
public static class ListViewExtensions
{
/// <summary>
/// Dumps the contents of the ListView into a tab separated list of lines
/// </summary>
public static string CopyItemsAsText(this ListView listViewControl)
{
var indexes = listViewControl.SelectedIndices;
if (indexes.Count <= 0)
{
return "";
}
var sb = new StringBuilder();
// walk over each selected item and subitem within it to generate a string from it
foreach (int index in indexes)
{
foreach (ListViewItem.ListViewSubItem item in listViewControl.Items[index].SubItems)
{
if (!string.IsNullOrWhiteSpace(item.Text))
{
sb.Append(item.Text).Append('\t');
}
}
// remove the last tab
sb.Remove(sb.Length - 1, 1);
sb.Append("\r\n");
}
// remove last newline
sb.Length -= 2;
return sb.ToString();
}
/// <exception cref="Win32Exception">unmanaged call failed</exception>
public static void SetSortIcon(this ListView listViewControl, int columnIndex, SortOrder order)
{
if (OSTailoredCode.IsUnixHost)
{
return;
}
var columnHeader = WmImports.SendMessageW(listViewControl.Handle, LVM_GETHEADER, IntPtr.Zero, IntPtr.Zero);
for (int columnNumber = 0, l = listViewControl.Columns.Count; columnNumber < l; columnNumber++)
{
var columnPtr = new IntPtr(columnNumber);
var item = new HDITEMW { mask = HDITEMW.Mask.Format };
if (SendMessageW(columnHeader, HDM_GETITEMW, columnPtr, ref item) == IntPtr.Zero)
{
throw new Win32Exception();
}
if (columnNumber != columnIndex || order == SortOrder.None)
{
item.fmt &= ~HDITEMW.Format.SortDown & ~HDITEMW.Format.SortUp;
}
// ReSharper disable once SwitchStatementMissingSomeEnumCasesNoDefault
else switch (order)
{
case SortOrder.Ascending:
item.fmt &= ~HDITEMW.Format.SortDown;
item.fmt |= HDITEMW.Format.SortUp;
break;
case SortOrder.Descending:
item.fmt &= ~HDITEMW.Format.SortUp;
item.fmt |= HDITEMW.Format.SortDown;
break;
}
if (SendMessageW(columnHeader, HDM_SETITEMW, columnPtr, ref item) == IntPtr.Zero)
{
throw new Win32Exception();
}
}
}
public static bool IsOk(this DialogResult dialogResult)
{
return dialogResult == DialogResult.OK;
}
/// <summary>
/// Sets the desired effect if data is present, else None
/// </summary>
public static void Set(this DragEventArgs e, DragDropEffects effect)
{
e.Effect = e.Data.GetDataPresent(DataFormats.FileDrop)
? effect
: DragDropEffects.None;
}
public static Bitmap ToBitMap(this Control control)
{
var b = BitmapBuffer.CreateBitmapObject(control.Size);
var rect = new Rectangle(new Point(0, 0), control.Size);
control.DrawToBitmap(b, rect);
return b;
}
public static void ToClipBoard(this Bitmap bitmap)
{
using var img = bitmap;
Clipboard.SetImage(img);
}
public static void SaveAsFile(this Bitmap bitmap, IGameInfo game, string suffix, string systemId, PathEntryCollection paths, IDialogParent parent)
{
var result = parent.ShowFileSaveDialog(
discardCWDChange: true,
filter: FilesystemFilterSet.Screenshots,
initDir: paths.ScreenshotAbsolutePathFor(systemId),
initFileName: $"{game.FilesystemSafeName()}-{suffix}");
if (result is null) return;
FileInfo file = new(result);
string extension = file.Extension.ToUpperInvariant();
ImageFormat i = extension switch
{
".BMP" => ImageFormat.Bmp,
_ => ImageFormat.Png,
};
bitmap.Save(file.FullName, i);
}
public static void SetDistanceOrDefault(this SplitContainer splitter, int distance, int defaultDistance)
{
if (distance > 0)
{
try
{
splitter.SplitterDistance = distance;
}
catch (Exception)
{
splitter.SplitterDistance = defaultDistance;
}
}
}
public static bool IsPressed(this KeyEventArgs e, Keys key)
=> !e.Alt && !e.Control && !e.Shift && e.KeyCode == key;
public static bool IsShift(this KeyEventArgs e, Keys key)
=> !e.Alt && !e.Control && e.Shift && e.KeyCode == key;
public static bool IsCtrl(this KeyEventArgs e, Keys key)
=> !e.Alt && e.Control && !e.Shift && e.KeyCode == key;
public static bool IsAlt(this KeyEventArgs e, Keys key)
=> e.Alt && !e.Control && !e.Shift && e.KeyCode == key;
public static bool IsCtrlShift(this KeyEventArgs e, Keys key)
=> !e.Alt && e.Control && e.Shift && e.KeyCode == key;
/// <summary>
/// Changes the description height area to match the rows needed for the largest description in the list
/// </summary>
public static void AdjustDescriptionHeightToFit(this PropertyGrid grid)
{
try
{
int maxLength = 0;
string desc = "";
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(grid.SelectedObject))
{
var s = property.Description;
if (s != null && s.Length > maxLength)
{
maxLength = s.Length;
desc = s;
}
}
foreach (Control control in grid.Controls)
{
if (control.GetType().Name == "DocComment")
{
var fi = control.GetType().GetField("userSized", BindingFlags.Instance | BindingFlags.NonPublic);
fi?.SetValue(control, true);
using var label = new Label();
var maxSize = new Size(grid.Width - 9, 999999);
control.Height = label.Height + TextRenderer.MeasureText(desc, control.Font, maxSize, TextFormatFlags.WordBreak).Height;
return;
}
}
}
catch
{
// Eat it
}
}
public static void EnableCategoriesIfUsed(this PropertyGrid grid)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(grid.SelectedObject))
{
if (property.Category is not null)
{
grid.PropertySort = PropertySort.Categorized;
return;
}
}
}
}
}