Repository navigation
Expand file tree
/
Copy pathScriptOptionsBag.cs
More file actions
361 lines (312 loc) · 15.6 KB
/
Copy pathScriptOptionsBag.cs
File metadata and controls
361 lines (312 loc) · 15.6 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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace SharpTagManager
{
/// <summary>
/// Wraps a set of ScriptOptionDef values so they can be displayed in a PropertyGrid.
/// Implements ICustomTypeDescriptor so the properties are built dynamically at runtime.
/// </summary>
class ScriptOptionsBag : CustomTypeDescriptor
{
public readonly Dictionary<string, object> Values = new Dictionary<string, object>();
private readonly ScriptOptionDef[] _options;
// Cached so the PropertyGrid always receives the same descriptor instances.
// The grid calls AddValueChanged() on descriptors to watch for refreshes; if
// GetProperties() returns new instances each time, those subscriptions are lost
// and OnValueChanged() never triggers a display update after SetValue().
private PropertyDescriptorCollection _cachedProps;
public ScriptOptionsBag(ScriptOptionDef[] options, Dictionary<string, object> initialValues = null)
{
_options = options ?? new ScriptOptionDef[0];
foreach (ScriptOptionDef opt in _options)
Values[opt.arg] = GetDefault(opt);
if (initialValues != null)
foreach (var kvp in initialValues)
if (Values.ContainsKey(kvp.Key))
Values[kvp.Key] = kvp.Value;
}
public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
if (_cachedProps == null)
_cachedProps = new PropertyDescriptorCollection(
_options.Select(o => new ScriptOptionDescriptor(o, Values)).ToArray<PropertyDescriptor>());
return _cachedProps;
}
public override PropertyDescriptorCollection GetProperties() => GetProperties(null);
// CustomTypeDescriptor.GetPropertyOwner() returns null unless overridden (it just forwards
// to a "parent" descriptor we never set). The PropertyGrid uses this method's return value —
// not SelectedObject directly — as the "component" argument to GetValue/SetValue. Leaving it
// null meant every edit silently committed against a null owner and the grid just redrew the
// unchanged stored value, which is why picking a new dropdown item never appeared to stick.
public override object GetPropertyOwner(PropertyDescriptor pd) => this;
/// <summary>
/// Produces the CLI argument strings to append to the process launch command.
/// e.g. ["--device cuda", "--timeout 120"]
/// Bool options emit only the flag name when true; other types emit "--flag value".
/// </summary>
public IEnumerable<string> BuildArgStrings()
{
foreach (ScriptOptionDef opt in _options)
{
if (!Values.TryGetValue(opt.arg, out object val)) continue;
if (string.Equals(opt.type, "bool", StringComparison.OrdinalIgnoreCase))
{
if (Convert.ToBoolean(val))
yield return opt.arg;
}
else
{
// Invariant culture so floats emit "0.5" regardless of the OS locale.
string s = val is IFormattable f ? f.ToString(null, CultureInfo.InvariantCulture)
: val?.ToString() ?? "";
// "path-enum" stores just the file name (that's what the dropdown shows) — turn
// it into a real path the script can open, unless it's already rooted (the user
// typed/pasted a full path instead of picking from the list).
if (string.Equals(opt.type, "path-enum", StringComparison.OrdinalIgnoreCase)
&& !string.IsNullOrEmpty(s) && !string.IsNullOrEmpty(opt.directory) && !Path.IsPathRooted(s))
s = Path.Combine(opt.directory, s);
if (!string.IsNullOrEmpty(s))
{
string quoted = (s.Contains(' ') || s.Contains('\n')) ? $"\"{s}\"" : s;
yield return $"{opt.arg} {quoted}";
}
}
}
}
internal static object GetDefault(ScriptOptionDef opt)
{
if (opt.@default != null) return opt.@default;
switch (opt.type?.ToLower())
{
case "bool": return false;
case "integer": return 0;
case "float": return 0.0;
default: return "";
}
}
}
/// <summary>
/// A dynamic PropertyDescriptor for a single ScriptOptionDef.
/// Tells the PropertyGrid what type to use, which editor/converter to show,
/// and where to read/write the current value.
/// </summary>
class ScriptOptionDescriptor : PropertyDescriptor
{
private readonly ScriptOptionDef _opt;
private readonly Dictionary<string, object> _values;
public ScriptOptionDescriptor(ScriptOptionDef opt, Dictionary<string, object> values)
: base(opt.label ?? opt.arg, BuildAttributes(opt))
{
_opt = opt;
_values = values;
}
private static Attribute[] BuildAttributes(ScriptOptionDef opt)
{
var attrs = new List<Attribute> { new CategoryAttribute("Options") };
if (!string.IsNullOrEmpty(opt.description))
attrs.Add(new DescriptionAttribute(opt.description));
return attrs.ToArray();
}
public override Type ComponentType => typeof(ScriptOptionsBag);
public override bool IsReadOnly => false;
public override Type PropertyType
{
get
{
switch (_opt.type?.ToLower())
{
case "bool": return typeof(bool);
case "integer": return typeof(int);
case "float": return typeof(double);
default: return typeof(string);
}
}
}
public override TypeConverter Converter
{
get
{
if (string.Equals(_opt.type, "enum", StringComparison.OrdinalIgnoreCase) && _opt.values != null)
return new EnumStringConverter(_opt.values);
if (string.Equals(_opt.type, "path-enum", StringComparison.OrdinalIgnoreCase))
return new PathEnumConverter(_opt.directory);
return base.Converter;
}
}
public override object GetEditor(Type editorBaseType)
{
if (editorBaseType == typeof(UITypeEditor))
{
if (string.Equals(_opt.type, "folder", StringComparison.OrdinalIgnoreCase))
return new FolderPickerEditor();
if (string.Equals(_opt.type, "file", StringComparison.OrdinalIgnoreCase))
return new FilePickerEditor(_opt.directory);
if (string.Equals(_opt.type, "multiline", StringComparison.OrdinalIgnoreCase))
return new MultilineTextEditor();
}
return base.GetEditor(editorBaseType);
}
public override object GetValue(object component) =>
Coerce(_values.TryGetValue(_opt.arg, out object v) ? v : ScriptOptionsBag.GetDefault(_opt));
public override void SetValue(object component, object value)
{
// Coerce on write so clamping applies to the stored value BuildArgStrings reads.
_values[_opt.arg] = Coerce(value);
OnValueChanged(component, EventArgs.Empty);
}
public override void ResetValue(object component) => _values[_opt.arg] = ScriptOptionsBag.GetDefault(_opt);
public override bool CanResetValue(object component) => true;
public override bool ShouldSerializeValue(object component) => false;
private object Coerce(object raw)
{
try
{
switch (_opt.type?.ToLower())
{
case "bool": return Convert.ToBoolean(raw, CultureInfo.InvariantCulture);
case "integer": return (int)Clamp(Convert.ToInt32(raw, CultureInfo.InvariantCulture));
case "float": return Clamp(Convert.ToDouble(raw, CultureInfo.InvariantCulture));
default: return raw?.ToString() ?? "";
}
}
catch { return ScriptOptionsBag.GetDefault(_opt); }
}
private double Clamp(double v)
{
if (_opt.min.HasValue && v < _opt.min.Value) v = _opt.min.Value;
if (_opt.max.HasValue && v > _opt.max.Value) v = _opt.max.Value;
return v;
}
}
/// <summary>TypeConverter that offers a fixed set of suggestions in the PropertyGrid dropdown
/// while still allowing free-typed custom values (non-exclusive).</summary>
class EnumStringConverter : TypeConverter
{
private readonly string[] _values;
public EnumStringConverter(string[] values) { _values = values; }
public override bool GetStandardValuesSupported(ITypeDescriptorContext ctx) => true;
public override bool GetStandardValuesExclusive(ITypeDescriptorContext ctx) => false;
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext ctx) =>
new StandardValuesCollection(_values);
public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type src) =>
src == typeof(string) || base.CanConvertFrom(ctx, src);
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo culture, object value) =>
value?.ToString() ?? "";
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo culture, object value, Type dest) =>
dest == typeof(string) ? value?.ToString() ?? "" : base.ConvertTo(ctx, culture, value, dest);
}
/// <summary>TypeConverter for "path-enum": lists the file names found in a directory as the
/// PropertyGrid dropdown's suggestions, scanning fresh every time the dropdown opens (so a
/// file dropped into the folder while the app is running shows up without a restart). Still
/// freely editable, same as EnumStringConverter, since a script may accept a hand-typed path
/// outside the listed folder too.</summary>
class PathEnumConverter : TypeConverter
{
private readonly string _directory;
public PathEnumConverter(string directory) { _directory = directory; }
public override bool GetStandardValuesSupported(ITypeDescriptorContext ctx) => true;
public override bool GetStandardValuesExclusive(ITypeDescriptorContext ctx) => false;
public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext ctx)
{
string[] names = new string[0];
try
{
if (!string.IsNullOrEmpty(_directory) && Directory.Exists(_directory))
names = Directory.GetFiles(_directory)
.Select(Path.GetFileName)
.OrderBy(n => n, StringComparer.OrdinalIgnoreCase)
.ToArray();
}
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return new StandardValuesCollection(names);
}
public override bool CanConvertFrom(ITypeDescriptorContext ctx, Type src) =>
src == typeof(string) || base.CanConvertFrom(ctx, src);
public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo culture, object value) =>
value?.ToString() ?? "";
public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo culture, object value, Type dest) =>
dest == typeof(string) ? value?.ToString() ?? "" : base.ConvertTo(ctx, culture, value, dest);
}
/// <summary>UITypeEditor that opens a FolderBrowserDialog for "folder" option type.</summary>
class FolderPickerEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext ctx) =>
UITypeEditorEditStyle.Modal;
public override object EditValue(ITypeDescriptorContext ctx, IServiceProvider provider, object value)
{
using (var dlg = new FolderBrowserDialog())
{
dlg.SelectedPath = value?.ToString() ?? "";
return dlg.ShowDialog() == DialogResult.OK ? dlg.SelectedPath : value;
}
}
}
/// <summary>UITypeEditor that opens an OpenFileDialog for "file" option type.</summary>
class FilePickerEditor : UITypeEditor
{
private readonly string _initialDir;
public FilePickerEditor(string initialDir) { _initialDir = initialDir; }
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext ctx) =>
UITypeEditorEditStyle.Modal;
public override object EditValue(ITypeDescriptorContext ctx, IServiceProvider provider, object value)
{
using (var dlg = new OpenFileDialog())
{
dlg.FileName = value?.ToString() ?? "";
if (!string.IsNullOrEmpty(_initialDir))
dlg.InitialDirectory = _initialDir;
return dlg.ShowDialog() == DialogResult.OK ? dlg.FileName : value;
}
}
}
/// <summary>UITypeEditor that opens a small modal multi-line textbox for "multiline" option type.</summary>
class MultilineTextEditor : UITypeEditor
{
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext ctx) =>
UITypeEditorEditStyle.Modal;
public override object EditValue(ITypeDescriptorContext ctx, IServiceProvider provider, object value)
{
using (var form = new Form())
{
form.Text = "Edit Text";
form.StartPosition = FormStartPosition.CenterParent;
form.Size = new System.Drawing.Size(480, 360);
form.MinimizeBox = false;
form.MaximizeBox = false;
form.ShowIcon = false;
var textBox = new TextBox
{
Multiline = true,
ScrollBars = ScrollBars.Vertical,
AcceptsReturn = true,
AcceptsTab = true,
Dock = DockStyle.Fill,
Text = value?.ToString() ?? "",
};
var buttonOk = new Button { Text = "OK", DialogResult = DialogResult.OK };
var buttonCancel = new Button { Text = "Cancel", DialogResult = DialogResult.Cancel };
var buttonPanel = new FlowLayoutPanel
{
Dock = DockStyle.Bottom, Height = 36, FlowDirection = FlowDirection.RightToLeft,
};
buttonPanel.Controls.Add(buttonCancel);
buttonPanel.Controls.Add(buttonOk);
// Bottom-docked control must be added before the Fill-docked one, or the fill
// control's layout runs first and covers the whole form.
form.Controls.Add(buttonPanel);
form.Controls.Add(textBox);
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;
return form.ShowDialog() == DialogResult.OK ? textBox.Text : value;
}
}
}
}