diff --git a/src/GameCult.Caching/CultInspectorModel.cs b/src/GameCult.Caching/CultInspectorModel.cs index 6061791c..57c4eef3 100644 --- a/src/GameCult.Caching/CultInspectorModel.cs +++ b/src/GameCult.Caching/CultInspectorModel.cs @@ -19,8 +19,6 @@ namespace GameCult.Caching Float, Bool, Enum, - // An unkeyed value type rebuilt through its constructor (CultMath vectors, rect, Color32). - Composite, RecordRef, List, Dictionary, @@ -62,14 +60,14 @@ namespace GameCult.Caching public sealed class CultInspectorMember { - internal CultInspectorMember(MemberInfo member, Type valueType, int slot, bool assignable, bool component, CultInspectorMetadata metadata) + internal CultInspectorMember(MemberInfo member, Type valueType, int slot, bool assignable, CultInspectorMetadata metadata) { Member = member; ValueType = valueType; Slot = slot; IsAssignable = assignable; Metadata = metadata; - IsReadOnly = metadata.ReadOnly || !assignable && !component; + IsReadOnly = metadata.ReadOnly || !assignable; } public MemberInfo Member { get; } @@ -79,10 +77,10 @@ namespace GameCult.Caching public CultInspectorMetadata Metadata { get; } // SetValue works: MessagePack's own rule, the one the registry persists by (a public setter or non-readonly field, or - // any setter or readonly field under AllowPrivate). A composite component is never assignable; its owner is composed. + // any setter or readonly field under AllowPrivate). public bool IsAssignable { get; } - // The lowering offers no edit: declared [CultInspectorReadOnly], or a member that can be neither assigned nor composed. + // The lowering offers no edit: declared [CultInspectorReadOnly], or not assignable. public bool IsReadOnly { get; } public object? GetValue(object target) => @@ -121,14 +119,13 @@ namespace GameCult.Caching // Union: the declared [Union] subtypes in key order, and nothing else. public IReadOnlyList UnionChoices { get; internal set; } = Array.Empty(); - // Nested: the members in inspection order. Composite: the components in constructor order. + // Nested: the members in inspection order. public IReadOnlyList Members { get; internal set; } = Array.Empty(); // Unsupported: why. public string? Reason { get; internal set; } internal Type? BuildType { get; set; } - internal ConstructorInfo? Composer { get; set; } } public readonly struct CultInspectorClaim @@ -365,13 +362,6 @@ namespace GameCult.Caching return Activator.CreateInstance(subtype)!; } - public object Compose(CultInspectorShape composite, IReadOnlyList components) - { - if (composite?.Composer == null) - throw new ArgumentException("Only a composite shape is composed.", nameof(composite)); - return composite.Composer.Invoke(components.ToArray()); - } - // A new collection holding items; the value it replaces is never mutated. public object BuildList(Type listType, IReadOnlyList items) { @@ -522,14 +512,18 @@ namespace GameCult.Caching var keyed = KeyedMembers(type); if (keyed.Length > 0) return new CultInspectorShape(type, CultInspectorValueKind.Nested) { Members = keyed }; + // An unkeyed struct is edited in place through its public fields. State it cannot write in place (a readonly field, + // a get-only auto-property) makes it unsupported until a drawer claims it. if (type.IsValueType) { - var composite = Composite(type); - if (composite != null) - return composite; - var fields = type.GetFields(Public).Where(field => !field.IsLiteral) + var locked = type.GetFields(Public).FirstOrDefault(field => field.IsInitOnly)?.Name + ?? type.GetProperties(Public).FirstOrDefault(property => property.GetSetMethod() == null && + type.GetField($"<{property.Name}>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance) != null)?.Name; + if (locked != null) + return Unsupported(type, $"{type.Name}.{locked} is readonly or get-only, so {type.Name} cannot be edited in place; it needs a drawer."); + var fields = type.GetFields(Public) .OrderBy(field => field.MetadataToken) - .Select((field, slot) => new CultInspectorMember(field, field.FieldType, slot, !field.IsInitOnly, false, MetadataOf(field))) + .Select((field, slot) => new CultInspectorMember(field, field.FieldType, slot, true, MetadataOf(field))) .ToArray(); if (fields.Length > 0) return new CultInspectorShape(type, CultInspectorValueKind.Nested) { Members = fields }; @@ -564,42 +558,12 @@ namespace GameCult.Caching } return slotted - .Select(entry => new CultInspectorMember(entry.Member, TypeOf(entry.Member), entry.Slot, Assignable(entry.Member, allowPrivate), false, MetadataOf(entry.Member))) + .Select(entry => new CultInspectorMember(entry.Member, TypeOf(entry.Member), entry.Slot, Assignable(entry.Member, allowPrivate), MetadataOf(entry.Member))) .OrderBy(member => member.Metadata.Order ?? member.Slot) .ThenBy(member => member.Slot) .ToArray(); } - // The longest public constructor whose every parameter takes a readable member of the same name and type. Public - // fields it does not take are state a rebuild would drop, so such a type is not composite. - private CultInspectorShape? Composite(Type type) - { - var readable = type.GetFields(Public).Where(field => !field.IsLiteral).Cast() - .Concat(type.GetProperties(Public).Where(property => property.GetGetMethod() != null && property.GetIndexParameters().Length == 0)) - .ToArray(); - foreach (var constructor in type.GetConstructors().OrderByDescending(constructor => constructor.GetParameters().Length)) - { - var parameters = constructor.GetParameters(); - if (parameters.Length == 0) - break; - var components = parameters - .Select(parameter => readable.FirstOrDefault(member => - string.Equals(member.Name, parameter.Name, StringComparison.OrdinalIgnoreCase) && TypeOf(member) == parameter.ParameterType)) - .ToArray(); - if (components.Any(component => component == null) || components.Distinct().Count() != components.Length) - continue; - if (readable.OfType().Any(field => !components.Contains(field))) - continue; - return new CultInspectorShape(type, CultInspectorValueKind.Composite) - { - Members = components.Select((component, slot) => new CultInspectorMember(component!, TypeOf(component!), slot, false, true, MetadataOf(component))).ToArray(), - Composer = constructor - }; - } - - return null; - } - private static CultInspectorShape Unsupported(Type type, string reason) => new CultInspectorShape(type, CultInspectorValueKind.Unsupported) { Reason = reason }; diff --git a/src/GameCult.Unity/Assets/Caching/Editor/CultCacheStudioDrawers.cs b/src/GameCult.Unity/Assets/Caching/Editor/CultCacheStudioDrawers.cs index 8873a194..fd55369f 100644 --- a/src/GameCult.Unity/Assets/Caching/Editor/CultCacheStudioDrawers.cs +++ b/src/GameCult.Unity/Assets/Caching/Editor/CultCacheStudioDrawers.cs @@ -84,8 +84,6 @@ namespace GameCult.Unity.Caching.Editor case CultInspectorValueKind.Enum: var current = value as Enum ?? (Enum)Enum.ToObject(type, 0); return type.IsDefined(typeof(FlagsAttribute), false) ? EditorGUILayout.EnumFlagsField(label, current) : EditorGUILayout.EnumPopup(label, current); - case CultInspectorValueKind.Composite: - return DrawComposite(label, shape, value); case CultInspectorValueKind.RecordRef: return DrawRecordRef(label, type, value); case CultInspectorValueKind.List: @@ -189,55 +187,6 @@ namespace GameCult.Unity.Caching.Editor } } - // Scalar components draw on one row; anything else folds out. A change composes a new value. - private object DrawComposite(string label, CultInspectorShape shape, object value) - { - var path = _path; - value = value ?? Model.CreateDefault(shape.Type); - var components = shape.Members; - var values = components.Select(component => component.GetValue(value)).ToArray(); - var changed = false; - if (components.All(component => Model.ShapeOf(component.ValueType).Kind is CultInspectorValueKind.Float or CultInspectorValueKind.Integer or CultInspectorValueKind.Bool)) - { - using (new EditorGUILayout.HorizontalScope()) - { - EditorGUILayout.PrefixLabel(label); - var indent = EditorGUI.indentLevel; - var labelWidth = EditorGUIUtility.labelWidth; - EditorGUI.indentLevel = 0; - EditorGUIUtility.labelWidth = 8 + 7 * components.Max(component => component.Name.Length); - for (var i = 0; i < components.Count; i++) - { - EditorGUI.BeginChangeCheck(); - var next = DrawDefault(components[i].Name, components[i].ValueType, values[i], null); - if (!EditorGUI.EndChangeCheck()) continue; - values[i] = next; - changed = true; - } - - EditorGUIUtility.labelWidth = labelWidth; - EditorGUI.indentLevel = indent; - } - } - else - { - if (!Foldout(path, label)) return value; - EditorGUI.indentLevel++; - for (var i = 0; i < components.Count; i++) - { - EditorGUI.BeginChangeCheck(); - var next = DrawValue(LabelOf(components[i]), components[i].ValueType, values[i], components[i].Member, path + "." + components[i].Name); - if (!EditorGUI.EndChangeCheck()) continue; - values[i] = next; - changed = true; - } - - EditorGUI.indentLevel--; - } - - return changed ? Model.Compose(shape, values) : value; - } - private object DrawRecordRef(string label, Type type, object value) { var key = CultInspectorModel.RecordKey(value); diff --git a/src/GameCult.Unity/Assets/Caching/README.md b/src/GameCult.Unity/Assets/Caching/README.md index 6556dbba..c4274a49 100644 --- a/src/GameCult.Unity/Assets/Caching/README.md +++ b/src/GameCult.Unity/Assets/Caching/README.md @@ -42,10 +42,10 @@ reloading scripts drops unsaved edits. in `GameCult.Caching`. Given a registry and the store's document codec it gives the member list of a type (registry catalog slots, `CultInspector*` metadata, whether a member is assignable), the shape of any value (string, integer, -float, bool, enum, composite value rebuilt through its constructor, -`CultRecordRef` with its candidate records, rank-1 list or array, -dictionary, `[Union]` with only its declared subtypes, nested keyed object, or -unsupported with a reason), drawer claim resolution +float, bool, enum, `CultRecordRef` with its candidate records, rank-1 list +or array, dictionary, `[Union]` with only its declared subtypes, nested keyed +object, struct edited in place through its public fields, or unsupported with +a reason), drawer claim resolution (`CultInspectorDrawerClaims`), dictionary key identity and refusal (null keys, empty record references and duplicates), and edits that work on a copy (`CultInspectorEdit`): a refused upsert leaves the cached object unchanged. The @@ -55,11 +55,12 @@ the same documents under the same rules. ## Drawers -Built in: every model shape above. Composite values of scalars (`float2/3/4`, -`int2`, `double2/3`, `bool2`, `quaternion`, `Color32`) draw as one row; -`rect` folds out to its corners. Unity object references draw as object -fields. A value no drawer claims and no shape covers shows a red error row, as -does a multi-dimensional array. +Built in: every model shape above. A struct without `[Key]` members folds out +to its public fields and is edited in place; a struct with a readonly field or +a get-only auto-property is unsupported until a drawer claims it. Unity object +references draw as object fields. A value no drawer claims and no shape covers +shows a red error row with the model's reason, as does a multi-dimensional +array. A project adds or overrides a drawer with an editor class. `Claimed` is either a value type (an open generic definition claims every closed form) or an diff --git a/tests/GameCult.Caching.Tests/CultInspectorModelTests.cs b/tests/GameCult.Caching.Tests/CultInspectorModelTests.cs index c7f265b0..f8ca5dce 100644 --- a/tests/GameCult.Caching.Tests/CultInspectorModelTests.cs +++ b/tests/GameCult.Caching.Tests/CultInspectorModelTests.cs @@ -195,7 +195,7 @@ namespace GameCult.Caching.Tests } [Test] - public void ShapesClassifyCollectionsCompositesAndMultiDimensionalArrays() + public void ShapesClassifyCollectionsStructsAndMultiDimensionalArrays() { var model = Model(); @@ -204,10 +204,15 @@ namespace GameCult.Caching.Tests Assert.That(model.ShapeOf(typeof(List)).ElementType, Is.EqualTo(typeof(int))); Assert.That(model.BuildList(typeof(float[]), new object?[] { 1f, 2f }), Is.EqualTo(new[] { 1f, 2f })); - var pair = model.ShapeOf(typeof(InspectPair)); - Assert.That(pair.Kind, Is.EqualTo(CultInspectorValueKind.Composite)); - Assert.That(pair.Members.Select(member => member.Name), Is.EqualTo(new[] { "x", "y" })); - Assert.That(model.Compose(pair, new object?[] { 1f, 2f }), Is.EqualTo(new InspectPair(1f, 2f))); + var open = model.ShapeOf(typeof(InspectOpenStruct)); + Assert.That(open.Kind, Is.EqualTo(CultInspectorValueKind.Nested)); + Assert.That(open.Members.Select(member => member.Name), Is.EqualTo(new[] { "x", "y" })); + Assert.That(open.Members.All(member => member.IsAssignable), Is.True); + foreach (var (locked, member) in new[] { (typeof(InspectReadonlyField), "y"), (typeof(InspectGetOnly), "Id") }) + { + Assert.That(model.ShapeOf(locked).Kind, Is.EqualTo(CultInspectorValueKind.Unsupported), locked.Name); + Assert.That(model.ShapeOf(locked).Reason, Does.Contain(locked.Name + "." + member).And.Contain("readonly or get-only")); + } Assert.That(model.ShapeOf(typeof(IDictionary)).Kind, Is.EqualTo(CultInspectorValueKind.Dictionary)); Assert.That(model.BuildDictionary(typeof(IDictionary), new[] { new KeyValuePair("a", 1) }), @@ -295,7 +300,24 @@ namespace GameCult.Caching.Tests public new string Value = string.Empty; } - public readonly record struct InspectPair(float x, float y); + public struct InspectOpenStruct + { + public float x; + public float y; + public float Length => x + y; + } + + public struct InspectReadonlyField + { + public float x; + public readonly float y; + } + + public struct InspectGetOnly + { + public float x; + public int Id { get; } + } [MessagePackObject] public readonly record struct InspectKey([property: Key(0)] int Value)