forked from ppy/osu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettingSourceAttribute.cs
More file actions
299 lines (242 loc) · 12.4 KB
/
Copy pathSettingSourceAttribute.cs
File metadata and controls
299 lines (242 loc) · 12.4 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
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using osu.Framework.Bindables;
using osu.Framework.Extensions.ObjectExtensions;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Settings;
using osu.Game.Utils;
namespace osu.Game.Configuration
{
/// <summary>
/// An attribute to mark a bindable as being exposed to the user via settings controls.
/// Can be used in conjunction with <see cref="SettingSourceExtensions.CreateSettingsControls"/> to automatically create UI controls.
/// </summary>
/// <remarks>
/// All controls with <see cref="OrderPosition"/> set will be placed first in ascending order.
/// All controls with no <see cref="OrderPosition"/> will come afterward in default order.
/// </remarks>
[MeansImplicitUse]
[AttributeUsage(AttributeTargets.Property)]
public class SettingSourceAttribute : Attribute, IComparable<SettingSourceAttribute>
{
public LocalisableString Label { get; }
public LocalisableString Description { get; }
public int? OrderPosition { get; }
/// <summary>
/// The type of the settings control which handles this setting source.
/// </summary>
/// <remarks>
/// Must be a type deriving <see cref="SettingsItem{T}"/> with a public parameterless constructor.
/// </remarks>
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
public Type? SettingControlType { get; set; }
public SettingSourceAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type declaringType, string label, string? description = null)
{
Label = getLocalisableStringFromMember(label) ?? string.Empty;
Description = getLocalisableStringFromMember(description) ?? string.Empty;
LocalisableString? getLocalisableStringFromMember(string? member)
{
if (member == null)
return null;
var property = declaringType.GetMember(member, BindingFlags.Static | BindingFlags.Public).FirstOrDefault();
if (property == null)
return null;
switch (property)
{
case FieldInfo f:
return (LocalisableString)f.GetValue(null).AsNonNull();
case PropertyInfo p:
return (LocalisableString)p.GetValue(null).AsNonNull();
default:
throw new InvalidOperationException($"Member \"{member}\" was not found in type {declaringType} (must be a static field or property)");
}
}
}
public SettingSourceAttribute(string? label, string? description = null)
{
Label = label ?? string.Empty;
Description = description ?? string.Empty;
}
public SettingSourceAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type declaringType, string label, string description, int orderPosition)
: this(declaringType, label, description)
{
OrderPosition = orderPosition;
}
public SettingSourceAttribute(string label, string description, int orderPosition)
: this(label, description)
{
OrderPosition = orderPosition;
}
public int CompareTo(SettingSourceAttribute? other)
{
if (OrderPosition == other?.OrderPosition)
return 0;
// unordered items come last (are greater than any ordered items).
if (OrderPosition == null)
return 1;
if (other?.OrderPosition == null)
return -1;
// ordered items are sorted by the order value.
return OrderPosition.Value.CompareTo(other.OrderPosition);
}
}
public static partial class SettingSourceExtensions
{
[RequiresUnreferencedCode("SettingSourceAttribute uses reflection to instantiate settings controls and may not be compatible with trimming.")]
public static IEnumerable<Drawable> CreateSettingsControls(this object obj)
{
foreach (var (attr, property) in obj.GetOrderedSettingsSourceProperties())
{
object value = property.GetValue(obj)!;
if (attr.SettingControlType != null)
{
var controlType = attr.SettingControlType;
if (controlType.EnumerateBaseTypes().All(t => !t.IsGenericType || t.GetGenericTypeDefinition() != typeof(SettingsItem<>)))
throw new InvalidOperationException($"{nameof(SettingSourceAttribute)} had an unsupported custom control type ({controlType.ReadableName()})");
var control = (Drawable)Activator.CreateInstance(controlType)!;
controlType.GetProperty(nameof(SettingsItem<object>.SettingSourceObject))?.SetValue(control, obj);
controlType.GetProperty(nameof(SettingsItem<object>.LabelText))?.SetValue(control, attr.Label);
controlType.GetProperty(nameof(SettingsItem<object>.TooltipText))?.SetValue(control, attr.Description);
controlType.GetProperty(nameof(SettingsItem<object>.Current))?.SetValue(control, value);
yield return control;
continue;
}
switch (value)
{
case BindableNumber<float> bNumber:
yield return new SettingsSlider<float>
{
LabelText = attr.Label,
TooltipText = attr.Description,
Current = bNumber,
KeyboardStep = bNumber.Precision,
};
break;
case BindableNumber<double> bNumber:
yield return new SettingsSlider<double>
{
LabelText = attr.Label,
TooltipText = attr.Description,
Current = bNumber,
KeyboardStep = (float)bNumber.Precision,
};
break;
case BindableNumber<int> bNumber:
yield return new SettingsSlider<int>
{
LabelText = attr.Label,
TooltipText = attr.Description,
Current = bNumber,
KeyboardStep = bNumber.Precision,
};
break;
case Bindable<bool> bBool:
yield return new SettingsCheckbox
{
LabelText = attr.Label,
TooltipText = attr.Description,
Current = bBool
};
break;
case Bindable<string> bString:
yield return new SettingsTextBox
{
LabelText = attr.Label,
TooltipText = attr.Description,
Current = bString
};
break;
case BindableColour4 bColour:
yield return new SettingsColour
{
LabelText = attr.Label,
TooltipText = attr.Description,
Current = bColour
};
break;
case IBindable bindable:
var dropdownType = typeof(ModSettingsEnumDropdown<>).MakeGenericType(bindable.GetType().GetGenericArguments()[0]);
var dropdown = (Drawable)Activator.CreateInstance(dropdownType)!;
dropdownType.GetProperty(nameof(SettingsDropdown<object>.LabelText))?.SetValue(dropdown, attr.Label);
dropdownType.GetProperty(nameof(SettingsDropdown<object>.TooltipText))?.SetValue(dropdown, attr.Description);
dropdownType.GetProperty(nameof(SettingsDropdown<object>.Current))?.SetValue(dropdown, bindable);
yield return dropdown;
break;
default:
throw new InvalidOperationException($"{nameof(SettingSourceAttribute)} was attached to an unsupported type ({value})");
}
}
}
private static readonly ConcurrentDictionary<Type, (SettingSourceAttribute, PropertyInfo)[]> property_info_cache = new ConcurrentDictionary<Type, (SettingSourceAttribute, PropertyInfo)[]>();
/// <summary>
/// Returns the underlying value of the given mod setting object.
/// Can be used for serialization and equality comparison purposes.
/// </summary>
/// <param name="setting">A <see cref="SettingSourceAttribute"/> bindable.</param>
[RequiresUnreferencedCode("Uses BindableValueAccessor which relies on reflection and may not be compatible with trimming.")]
public static object GetUnderlyingSettingValue(this object setting)
{
switch (setting)
{
case Bindable<double> d:
return d.Value;
case Bindable<int> i:
return i.Value;
case Bindable<float> f:
return f.Value;
case Bindable<bool> b:
return b.Value;
case BindableColour4 c:
return c.Value.ToHex();
case IBindable u:
return BindableValueAccessor.GetValue(u);
default:
// fall back for non-bindable cases.
return setting;
}
}
[RequiresUnreferencedCode("SettingSourceAttribute uses reflection to retrieve properties and may not be compatible with trimming.")]
public static IEnumerable<(SettingSourceAttribute, PropertyInfo)> GetSettingsSourceProperties(this object obj)
{
var type = obj.GetType();
if (!property_info_cache.TryGetValue(type, out var properties))
property_info_cache[type] = properties = getSettingsSourceProperties(type).ToArray();
return properties;
}
private static IEnumerable<(SettingSourceAttribute, PropertyInfo)> getSettingsSourceProperties([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type)
{
foreach (var property in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance))
{
var attr = property.GetCustomAttribute<SettingSourceAttribute>(true);
if (attr == null)
continue;
yield return (attr, property);
}
}
[RequiresUnreferencedCode("SettingSourceAttribute uses reflection to retrieve properties and may not be compatible with trimming.")]
public static ICollection<(SettingSourceAttribute, PropertyInfo)> GetOrderedSettingsSourceProperties(this object obj)
=> obj.GetSettingsSourceProperties()
.OrderBy(attr => attr.Item1)
.ToArray();
private partial class ModSettingsEnumDropdown<T> : SettingsEnumDropdown<T>
where T : struct, Enum
{
protected override OsuDropdown<T> CreateDropdown() => new ModDropdownControl();
private partial class ModDropdownControl : DropdownControl
{
// Set menu's max height low enough to workaround nested scroll issues (see https://github.com/ppy/osu-framework/issues/4536).
protected override DropdownMenu CreateMenu() => base.CreateMenu().With(m => m.MaxHeight = 100);
}
}
}
}