This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e9c18861072146ca91af22a8a8dbab9d
timeCreated: 1772182293
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 83dbde7dc514d4e839b561f0df9bcad3
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,67 @@
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
class AssetReloadNotifier : AssetPostprocessor
{
internal static event Action<HashSet<string>> AssetsChanged;
internal static bool IsWatchedPath(
string file, HashSet<string> changedFullPaths)
{
if (string.IsNullOrEmpty(file))
return false;
if (file.StartsWith(Path.GetTempPath(), StringComparison.OrdinalIgnoreCase))
return false;
string fullPath = Path.GetFullPath(file);
if (changedFullPaths.Contains(fullPath))
return true;
if (!MetaPath.IsMetaPath(file))
return false;
string assetFullPath = Path.GetFullPath(
MetaPath.GetPathFromMetaPath(file));
return changedFullPaths.Contains(assetFullPath);
}
static void OnPostprocessAllAssets(
string[] importedAssets,
string[] deletedAssets,
string[] movedAssets,
string[] movedFromAssetPaths)
{
Action<HashSet<string>> handler = AssetsChanged;
if (handler == null)
return;
HashSet<string> changedFullPaths = new HashSet<string>(
StringComparer.OrdinalIgnoreCase);
AddFullPaths(changedFullPaths, importedAssets);
AddFullPaths(changedFullPaths, deletedAssets);
AddFullPaths(changedFullPaths, movedAssets);
AddFullPaths(changedFullPaths, movedFromAssetPaths);
if (changedFullPaths.Count == 0)
return;
handler(changedFullPaths);
}
static void AddFullPaths(HashSet<string> set, string[] assetPaths)
{
foreach (string assetPath in assetPaths)
set.Add(Path.GetFullPath(assetPath));
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c1920ac5329fb48e680e865d9a8567f8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,537 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Property;
using Unity.PlasticSCM.Editor.UI;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal class DiffValueDisplay : VisualElement
{
internal DiffValueDisplay()
{
CreateGUI();
}
internal void SetData(
object tag,
string fallbackText,
bool hasContent,
object counterpartTag)
{
HideActiveField();
if (!hasContent)
return;
if (tag is LeafPropertyData leaf)
{
LeafPropertyData? counterpart = counterpartTag is LeafPropertyData cp
? cp
: (LeafPropertyData?)null;
ShowTypedField(leaf, counterpart);
return;
}
ShowField(mTextField);
mTextField.SetValueWithoutNotify(fallbackText ?? string.Empty);
}
void CreateGUI()
{
style.flexGrow = 1;
style.overflow = Overflow.Visible;
mFloatField = AddField(new FloatField { label = string.Empty });
mIntField = AddField(new IntegerField { label = string.Empty });
mToggleField = AddField(new Toggle { label = string.Empty });
mTextField = AddField(new TextField { label = string.Empty });
mColorField = AddField(new ColorField
{
label = string.Empty,
showAlpha = true,
hdr = false,
showEyeDropper = false
});
mCurveField = AddField(new CurveField { label = string.Empty });
mGradientField = AddField(new GradientField { label = string.Empty });
mVector2Field = AddField(new Vector2Field { label = string.Empty });
mVector3Field = AddField(new Vector3Field { label = string.Empty });
mVector4Field = AddField(new Vector4Field { label = string.Empty });
mVector2IntField = AddField(new Vector2IntField { label = string.Empty });
mVector3IntField = AddField(new Vector3IntField { label = string.Empty });
mRectField = AddField(new RectField { label = string.Empty });
mRectIntField = AddField(new RectIntField { label = string.Empty });
mBoundsField = AddField(new BoundsField { label = string.Empty });
mBoundsIntField = AddField(new BoundsIntField { label = string.Empty });
mHash128Field = AddField(new Hash128Field { label = string.Empty });
}
T AddField<T>(T field) where T : VisualElement
{
field.SetEnabled(false);
field.style.opacity = 1f;
field.style.display = DisplayStyle.None;
field.style.flexGrow = 1;
field.style.marginTop = 0;
field.style.marginBottom = 0;
field.style.marginLeft = 0;
field.style.marginRight = 0;
Add(field);
field.RegisterCallback<AttachToPanelEvent>(_ =>
{
StyleColor readonlyBg = new StyleColor(
UnityStyles.Colors.Diff.AssetDiff.ReadonlyFieldBackgroundColor);
field.Query(className: INPUT_CLASS).ForEach(input =>
input.style.backgroundColor = readonlyBg);
field.Query(className: TOGGLE_CHECKMARK_CLASS).ForEach(checkmark =>
checkmark.style.unityBackgroundImageTintColor = new StyleColor(
UnityStyles.Colors.Diff.AssetDiff.ReadonlyToggleTintColor));
});
return field;
}
void HideActiveField()
{
if (mActiveField == null)
return;
mActiveField.style.display = DisplayStyle.None;
mActiveField = null;
}
void ShowField(VisualElement field)
{
field.style.display = DisplayStyle.Flex;
mActiveField = field;
}
void ShowTypedField(LeafPropertyData data, LeafPropertyData? counterpart)
{
switch (data.PropertyType)
{
case SerializedPropertyType.Float:
ShowField(mFloatField);
mFloatField.SetValueWithoutNotify(data.FloatValue);
return;
case SerializedPropertyType.Integer:
if (data.HasFormattedDisplay)
{
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
}
ShowField(mIntField);
mIntField.SetValueWithoutNotify(data.IntValue);
return;
case SerializedPropertyType.LayerMask:
if (data.HasFormattedDisplay)
{
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
}
ShowField(mIntField);
mIntField.SetValueWithoutNotify(data.IntValue);
return;
case SerializedPropertyType.Character:
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.FixedBufferSize:
ShowField(mIntField);
mIntField.SetValueWithoutNotify(data.IntValue);
return;
case SerializedPropertyType.Boolean:
ShowField(mToggleField);
mToggleField.SetValueWithoutNotify(data.BoolValue);
return;
case SerializedPropertyType.String:
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
case SerializedPropertyType.Color:
ShowField(mColorField);
mColorField.SetValueWithoutNotify(data.ColorValue);
return;
case SerializedPropertyType.AnimationCurve:
ShowField(mCurveField);
mCurveField.SetValueWithoutNotify(
data.AnimationCurveValue ?? new AnimationCurve());
return;
case SerializedPropertyType.Gradient:
ShowField(mGradientField);
mGradientField.SetValueWithoutNotify(
data.GradientValue ?? new Gradient());
return;
case SerializedPropertyType.Vector2:
ShowVector2(data.Vector2Value, counterpart);
return;
case SerializedPropertyType.Vector3:
ShowVector3(data.Vector3Value, counterpart);
return;
case SerializedPropertyType.Vector4:
ShowVector4(data.Vector4Value, counterpart);
return;
case SerializedPropertyType.Quaternion:
ShowQuaternion(data.QuaternionValue, counterpart);
return;
case SerializedPropertyType.Vector2Int:
ShowVector2Int(data.Vector2IntValue, counterpart);
return;
case SerializedPropertyType.Vector3Int:
ShowVector3Int(data.Vector3IntValue, counterpart);
return;
case SerializedPropertyType.Rect:
ShowRect(data.RectValue, counterpart);
return;
case SerializedPropertyType.RectInt:
ShowRectInt(data.RectIntValue, counterpart);
return;
case SerializedPropertyType.Bounds:
ShowBounds(data.BoundsValue, counterpart);
return;
case SerializedPropertyType.BoundsInt:
ShowBoundsInt(data.BoundsIntValue, counterpart);
return;
case SerializedPropertyType.Hash128:
ShowField(mHash128Field);
mHash128Field.SetValueWithoutNotify(data.Hash128Value);
return;
default:
ShowField(mTextField);
mTextField.SetValueWithoutNotify(data.StringValue ?? string.Empty);
return;
}
}
void ShowVector2(Vector2 value, LeafPropertyData? counterpart)
{
ShowField(mVector2Field);
mVector2Field.SetValueWithoutNotify(value);
float[] otherValues = TryGetVector2Components(counterpart);
HighlightFloatComponents(
mVector2Field, new[] { value.x, value.y }, otherValues);
}
void ShowVector3(Vector3 value, LeafPropertyData? counterpart)
{
ShowField(mVector3Field);
mVector3Field.SetValueWithoutNotify(value);
float[] otherValues = TryGetVector3Components(counterpart);
HighlightFloatComponents(
mVector3Field, new[] { value.x, value.y, value.z }, otherValues);
}
void ShowVector4(Vector4 value, LeafPropertyData? counterpart)
{
ShowField(mVector4Field);
mVector4Field.SetValueWithoutNotify(value);
float[] otherValues = TryGetVector4Components(counterpart);
HighlightFloatComponents(
mVector4Field,
new[] { value.x, value.y, value.z, value.w },
otherValues);
}
void ShowQuaternion(Quaternion value, LeafPropertyData? counterpart)
{
Vector3 euler = value.eulerAngles;
ShowField(mVector3Field);
mVector3Field.SetValueWithoutNotify(euler);
float[] otherValues = null;
if (counterpart.HasValue &&
counterpart.Value.PropertyType == SerializedPropertyType.Quaternion)
{
Vector3 otherEuler = counterpart.Value.QuaternionValue.eulerAngles;
otherValues = new[] { otherEuler.x, otherEuler.y, otherEuler.z };
}
HighlightFloatComponents(
mVector3Field, new[] { euler.x, euler.y, euler.z }, otherValues);
}
void ShowVector2Int(Vector2Int value, LeafPropertyData? counterpart)
{
ShowField(mVector2IntField);
mVector2IntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetVector2IntComponents(counterpart);
HighlightIntComponents(
mVector2IntField, new[] { value.x, value.y }, otherValues);
}
void ShowVector3Int(Vector3Int value, LeafPropertyData? counterpart)
{
ShowField(mVector3IntField);
mVector3IntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetVector3IntComponents(counterpart);
HighlightIntComponents(
mVector3IntField,
new[] { value.x, value.y, value.z },
otherValues);
}
void ShowRect(Rect value, LeafPropertyData? counterpart)
{
ShowField(mRectField);
mRectField.SetValueWithoutNotify(value);
float[] otherValues = TryGetRectComponents(counterpart);
HighlightFloatComponents(
mRectField,
new[] { value.x, value.y, value.width, value.height },
otherValues);
}
void ShowRectInt(RectInt value, LeafPropertyData? counterpart)
{
ShowField(mRectIntField);
mRectIntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetRectIntComponents(counterpart);
HighlightIntComponents(
mRectIntField,
new[] { value.x, value.y, value.width, value.height },
otherValues);
}
void ShowBounds(Bounds value, LeafPropertyData? counterpart)
{
ShowField(mBoundsField);
mBoundsField.SetValueWithoutNotify(value);
float[] otherValues = TryGetBoundsComponents(counterpart);
HighlightFloatComponents(
mBoundsField,
new[]
{
value.center.x, value.center.y, value.center.z,
value.extents.x, value.extents.y, value.extents.z
},
otherValues);
}
void ShowBoundsInt(BoundsInt value, LeafPropertyData? counterpart)
{
ShowField(mBoundsIntField);
mBoundsIntField.SetValueWithoutNotify(value);
int[] otherValues = TryGetBoundsIntComponents(counterpart);
HighlightIntComponents(
mBoundsIntField,
new[]
{
value.position.x, value.position.y, value.position.z,
value.size.x, value.size.y, value.size.z
},
otherValues);
}
static float[] TryGetVector2Components(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector2)
return null;
Vector2 v = counterpart.Value.Vector2Value;
return new[] { v.x, v.y };
}
static float[] TryGetVector3Components(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector3)
return null;
Vector3 v = counterpart.Value.Vector3Value;
return new[] { v.x, v.y, v.z };
}
static float[] TryGetVector4Components(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector4)
return null;
Vector4 v = counterpart.Value.Vector4Value;
return new[] { v.x, v.y, v.z, v.w };
}
static int[] TryGetVector2IntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector2Int)
return null;
Vector2Int v = counterpart.Value.Vector2IntValue;
return new[] { v.x, v.y };
}
static int[] TryGetVector3IntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Vector3Int)
return null;
Vector3Int v = counterpart.Value.Vector3IntValue;
return new[] { v.x, v.y, v.z };
}
static float[] TryGetRectComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Rect)
return null;
Rect r = counterpart.Value.RectValue;
return new[] { r.x, r.y, r.width, r.height };
}
static int[] TryGetRectIntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.RectInt)
return null;
RectInt r = counterpart.Value.RectIntValue;
return new[] { r.x, r.y, r.width, r.height };
}
static float[] TryGetBoundsComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.Bounds)
return null;
Bounds b = counterpart.Value.BoundsValue;
return new[]
{
b.center.x, b.center.y, b.center.z,
b.extents.x, b.extents.y, b.extents.z
};
}
static int[] TryGetBoundsIntComponents(LeafPropertyData? counterpart)
{
if (!counterpart.HasValue ||
counterpart.Value.PropertyType != SerializedPropertyType.BoundsInt)
return null;
BoundsInt b = counterpart.Value.BoundsIntValue;
return new[]
{
b.position.x, b.position.y, b.position.z,
b.size.x, b.size.y, b.size.z
};
}
static void HighlightFloatComponents(
VisualElement vectorField,
float[] values,
float[] counterpartValues)
{
var floatFields = vectorField.Query<FloatField>().ToList();
bool hasComparison = counterpartValues != null;
for (int i = 0; i < floatFields.Count && i < values.Length; i++)
{
bool changed = hasComparison
&& i < counterpartValues.Length
&& !Mathf.Approximately(values[i], counterpartValues[i]);
ApplyInputHighlight(floatFields[i], changed, hasComparison);
}
}
static void HighlightIntComponents(
VisualElement vectorField,
int[] values,
int[] counterpartValues)
{
var intFields = vectorField.Query<IntegerField>().ToList();
bool hasComparison = counterpartValues != null;
for (int i = 0; i < intFields.Count && i < values.Length; i++)
{
bool changed = hasComparison
&& i < counterpartValues.Length
&& values[i] != counterpartValues[i];
ApplyInputHighlight(intFields[i], changed, hasComparison);
}
}
static void ApplyInputHighlight(
VisualElement field, bool highlight, bool hasComparison)
{
VisualElement input = field.Q(className: INPUT_CLASS);
if (input == null)
return;
StyleColor color = highlight
? new StyleColor(UnityStyles.Colors.Diff.AssetDiff.VectorComponentHighlight)
: new StyleColor(StyleKeyword.Null);
input.style.borderTopColor = color;
input.style.borderBottomColor = color;
input.style.borderLeftColor = color;
input.style.borderRightColor = color;
input.style.opacity = (highlight || !hasComparison) ? 1f : 0.4f;
}
VisualElement mActiveField;
FloatField mFloatField;
IntegerField mIntField;
Toggle mToggleField;
TextField mTextField;
ColorField mColorField;
CurveField mCurveField;
GradientField mGradientField;
Vector2Field mVector2Field;
Vector3Field mVector3Field;
Vector4Field mVector4Field;
Vector2IntField mVector2IntField;
Vector3IntField mVector3IntField;
RectField mRectField;
RectIntField mRectIntField;
BoundsField mBoundsField;
BoundsIntField mBoundsIntField;
Hash128Field mHash128Field;
const string INPUT_CLASS = "unity-base-text-field__input";
const string TOGGLE_CHECKMARK_CLASS = "unity-toggle__checkmark";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cb707ab51a8fe45748564daa6476d9b8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,151 @@
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class HeaderRow
{
internal const float BASE_PADDING_LEFT = 4f;
internal const float INDENT_PX = 16f;
internal const string ARROW_RIGHT = "▶";
internal const string ARROW_DOWN = "▼";
internal static VisualElement BuildPanel(
out VisualElement content,
out Label arrow,
out Image icon,
out Label nameLabel,
out Label annotationLabel)
{
VisualElement panel = new VisualElement();
panel.style.flexGrow = 1;
panel.style.flexBasis = 0;
panel.style.flexDirection = FlexDirection.Row;
content = new VisualElement();
content.style.flexGrow = 1;
content.style.flexDirection = FlexDirection.Row;
content.style.alignItems = Align.Center;
content.style.borderTopWidth = 1;
content.style.borderBottomWidth = 1;
panel.Add(content);
arrow = new Label(ARROW_RIGHT);
arrow.style.width = 16;
arrow.style.fontSize = 10;
arrow.style.unityTextAlign = TextAnchor.MiddleCenter;
arrow.style.color = UnityStyles.Colors.Diff.AssetDiff.ExpanderColor;
content.Add(arrow);
icon = new Image();
icon.style.width = 16;
icon.style.height = 16;
icon.style.marginRight = 4;
content.Add(icon);
nameLabel = new Label();
nameLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
nameLabel.style.fontSize = 12;
nameLabel.style.flexShrink = 1;
nameLabel.style.overflow = Overflow.Hidden;
nameLabel.style.textOverflow = TextOverflow.Ellipsis;
content.Add(nameLabel);
annotationLabel = new Label();
annotationLabel.style.unityFontStyleAndWeight = FontStyle.Italic;
annotationLabel.style.fontSize = 12;
annotationLabel.style.marginLeft = 8;
annotationLabel.style.flexShrink = 0;
annotationLabel.style.color = UnityStyles.Colors.Diff.AssetDiff.AnnotationText;
annotationLabel.style.display = DisplayStyle.None;
content.Add(annotationLabel);
return panel;
}
internal static void ConfigurePanel(
Label arrow,
Image icon,
Label nameLabel,
Label annotationLabel,
VisualElement panel,
bool hasContent,
string arrowText,
Color panelBg,
UnityEngine.Texture objectIcon,
string displayName,
string searchFilter,
string annotation = null,
bool isExpandable = true)
{
panel.style.backgroundColor = panelBg;
arrow.text = arrowText;
arrow.style.display = (hasContent && isExpandable)
? DisplayStyle.Flex : DisplayStyle.None;
icon.image = hasContent ? objectIcon : null;
icon.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
bool hasSearch = !string.IsNullOrEmpty(searchFilter);
nameLabel.enableRichText = hasSearch;
nameLabel.text = hasSearch
? SearchHighlight.Apply(displayName, searchFilter)
: displayName;
nameLabel.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
nameLabel.style.color = hasContent
? UnityStyles.Colors.DefaultText
: UnityStyles.Colors.DefaultTextDisabled;
bool hasAnnotation = hasContent && !string.IsNullOrEmpty(annotation);
annotationLabel.style.display = hasAnnotation
? DisplayStyle.Flex : DisplayStyle.None;
if (hasAnnotation)
annotationLabel.text = annotation;
}
internal static void ApplyContentBorder(
VisualElement content,
bool hasContent,
float paddingLeft,
bool isExpanded,
bool suppressBottomBorder = false)
{
content.style.paddingLeft = paddingLeft;
content.style.borderTopColor = hasContent
? UnityStyles.Colors.Diff.AssetDiff.HeaderBorder
: Color.clear;
content.style.borderBottomColor = hasContent && isExpanded && !suppressBottomBorder
? UnityStyles.Colors.Diff.AssetDiff.HeaderBorderLight
: Color.clear;
}
internal static Color GetBackgroundColor(bool hasContent, bool bIsHovered)
{
if (!hasContent)
return UnityStyles.Colors.Diff.AssetDiff.EmptyPanelBackground;
return bIsHovered
? UnityStyles.Colors.Diff.AssetDiff.ObjectHeaderBackgroundHovered
: UnityStyles.Colors.Diff.AssetDiff.ObjectHeaderBackground;
}
internal static void SetHovered(
ref bool sideHovered,
bool hasContent,
VisualElement panel,
bool bIsHovered)
{
if (!hasContent || sideHovered == bIsHovered)
return;
sideHovered = bIsHovered;
panel.style.backgroundColor = GetBackgroundColor(hasContent, bIsHovered);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: edc2dbba232594aabbbad8bb87466a80
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 54ada74a1e58348099b007e35677f3aa
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,779 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Meta
{
internal static class MetaPropertyTreeBuilder
{
internal static PropertyTreeNode Build(byte[] fileBytes)
{
if (fileBytes == null || fileBytes.Length == 0)
return PropertyTreeNode.CreateRoot(new List<PropertyTreeNode>());
string[] lines = Encoding.UTF8.GetString(fileBytes).Split('\n');
int lineIdx = 0;
List<PropertyTreeNode> children = ParseMappingEntries(lines, ref lineIdx, -1, string.Empty);
return PropertyTreeNode.CreateRoot(children);
}
#region Block Parsing
static List<PropertyTreeNode> ParseMappingEntries(
string[] lines, ref int lineIdx, int parentIndent, string parentPath)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
while (lineIdx < lines.Length)
{
string line = TrimLineEnd(lines[lineIdx]);
if (string.IsNullOrWhiteSpace(line))
{
lineIdx++;
continue;
}
int indent = CountLeadingSpaces(line);
string content = line.Substring(indent);
if (IsDirectiveLine(content))
{
lineIdx++;
continue;
}
if (indent <= parentIndent)
break;
// Sequence items are handled by ParseSequenceItems, not here
if (content.StartsWith("- ", StringComparison.Ordinal))
break;
if (!TrySplitKeyValue(content, out string key, out string value))
{
lineIdx++;
continue;
}
lineIdx++;
string path = AppendPath(parentPath, key);
string displayName = ObjectNames.NicifyVariableName(key);
PropertyTreeNode node = BuildValueNode(
lines, ref lineIdx, indent, key, path, displayName, value);
children.Add(node);
}
return children;
}
static PropertyTreeNode BuildValueNode(
string[] lines, ref int lineIdx, int keyIndent,
string name, string path, string displayName, string value)
{
if (string.IsNullOrEmpty(value))
return BuildBlockValueNode(
lines, ref lineIdx, keyIndent, name, path, displayName);
if (value == "{}")
return PropertyTreeNode.CreateObject(
name, path, new List<PropertyTreeNode>(), displayName);
if (value == "[]")
return PropertyTreeNode.CreateArray(
name, path, new List<PropertyTreeNode>(), displayName);
if (value.StartsWith("{", StringComparison.Ordinal) &&
value.EndsWith("}", StringComparison.Ordinal))
return ParseInlineMap(name, path, displayName, value);
if (value.StartsWith("[", StringComparison.Ordinal) &&
value.EndsWith("]", StringComparison.Ordinal))
return ParseInlineSequence(name, path, displayName, value);
return CreateTypedLeaf(name, path, displayName, value);
}
static PropertyTreeNode BuildBlockValueNode(
string[] lines, ref int lineIdx, int keyIndent,
string name, string path, string displayName)
{
SkipBlankAndDirectiveLines(lines, ref lineIdx);
if (lineIdx >= lines.Length)
return CreateTypedLeaf(name, path, displayName, string.Empty);
string nextLine = TrimLineEnd(lines[lineIdx]);
int nextIndent = CountLeadingSpaces(nextLine);
string nextContent = nextLine.Substring(nextIndent);
// Sequences can appear at the same indent as the key (Unity's standard format)
// or indented further
bool isSequence = nextContent.StartsWith("- ", StringComparison.Ordinal)
&& nextIndent >= keyIndent;
if (isSequence)
{
List<PropertyTreeNode> items = ParseSequenceItems(
lines, ref lineIdx, nextIndent, path);
return PropertyTreeNode.CreateArray(name, path, items, displayName);
}
if (nextIndent > keyIndent)
{
List<PropertyTreeNode> children = ParseMappingEntries(
lines, ref lineIdx, keyIndent, path);
return PropertyTreeNode.CreateObject(name, path, children, displayName);
}
return CreateTypedLeaf(name, path, displayName, string.Empty);
}
static List<PropertyTreeNode> ParseSequenceItems(
string[] lines, ref int lineIdx, int dashIndent, string parentPath)
{
List<PropertyTreeNode> items = new List<PropertyTreeNode>();
int itemIndex = 0;
while (lineIdx < lines.Length)
{
string line = TrimLineEnd(lines[lineIdx]);
if (string.IsNullOrWhiteSpace(line))
{
lineIdx++;
continue;
}
int indent = CountLeadingSpaces(line);
if (indent < dashIndent)
break;
string content = line.Substring(indent);
if (IsDirectiveLine(content))
{
lineIdx++;
continue;
}
if (indent != dashIndent ||
!content.StartsWith("- ", StringComparison.Ordinal))
break;
lineIdx++;
string itemPath = $"{parentPath}[{itemIndex}]";
string itemName = $"[{itemIndex}]";
string itemContent = content.Substring(2).Trim();
int contentIndent = indent + 2;
PropertyTreeNode itemNode;
if (string.IsNullOrEmpty(itemContent))
{
List<PropertyTreeNode> children = ParseMappingEntries(
lines, ref lineIdx, indent, itemPath);
string label = FindNameLabel(children);
itemNode = PropertyTreeNode.CreateObject(
itemName, itemPath, children, label);
}
else if (TrySplitKeyValue(
itemContent, out string key, out string value))
{
List<PropertyTreeNode> itemChildren = new List<PropertyTreeNode>();
string firstPath = AppendPath(itemPath, key);
string firstDisplay = ObjectNames.NicifyVariableName(key);
PropertyTreeNode firstChild = BuildValueNode(
lines, ref lineIdx, contentIndent,
key, firstPath, firstDisplay, value);
itemChildren.Add(firstChild);
List<PropertyTreeNode> siblings = ParseMappingEntries(
lines, ref lineIdx, indent, itemPath);
itemChildren.AddRange(siblings);
string label = FindNameLabel(itemChildren);
itemNode = PropertyTreeNode.CreateObject(
itemName, itemPath, itemChildren, label);
}
else
{
LeafPropertyData leafData = InferScalarType(
string.Empty, itemPath, itemContent);
itemNode = PropertyTreeNode.CreateLeaf(
itemName, itemPath, leafData.PropertyType.ToString(),
leafData.StringValue, null, leafData);
}
items.Add(itemNode);
itemIndex++;
}
return items;
}
static string FindNameLabel(List<PropertyTreeNode> children)
{
foreach (PropertyTreeNode child in children)
{
if (child.Kind != NodeKind.Leaf)
continue;
bool isLabelKey =
string.Equals(child.Name, "name", StringComparison.OrdinalIgnoreCase) ||
string.Equals(child.Name, "buildTarget", StringComparison.OrdinalIgnoreCase);
if (!isLabelKey)
continue;
string value = child.Value?.Trim();
if (!string.IsNullOrEmpty(value))
return value;
}
return null;
}
#endregion
#region Inline Parsing
static PropertyTreeNode ParseInlineMap(
string name, string path, string displayName, string text)
{
string inner = text.Substring(1, text.Length - 2).Trim();
if (string.IsNullOrEmpty(inner))
return PropertyTreeNode.CreateObject(
name, path, new List<PropertyTreeNode>(), displayName);
if (TryBuildInlineVector(
name, path, displayName, inner, out PropertyTreeNode vectorNode))
return vectorNode;
if (TryBuildInlineRect(
name, path, displayName, inner, out PropertyTreeNode rectNode))
return rectNode;
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
foreach (string part in SplitInlineElements(inner))
{
if (!TrySplitKeyValue(part, out string key, out string value))
continue;
string childPath = AppendPath(path, key);
string childDisplay = ObjectNames.NicifyVariableName(key);
children.Add(CreateTypedLeaf(key, childPath, childDisplay, value));
}
return PropertyTreeNode.CreateObject(name, path, children, displayName);
}
static bool TryBuildInlineVector(
string name, string path, string displayName,
string inner, out PropertyTreeNode node)
{
node = null;
Dictionary<string, float> components = new Dictionary<string, float>(
StringComparer.OrdinalIgnoreCase);
foreach (string part in SplitInlineElements(inner))
{
if (!TrySplitKeyValue(part, out string key, out string val))
return false;
if (!VECTOR_COMPONENT_KEYS.Contains(key.ToLowerInvariant()))
return false;
if (!float.TryParse(
UnquoteValue(val), NumberStyles.Float,
CultureInfo.InvariantCulture, out float parsed))
return false;
components[key.ToLowerInvariant()] = parsed;
}
LeafPropertyData leafData;
if (components.Count == 2 &&
components.ContainsKey("x") &&
components.ContainsKey("y"))
{
Vector2 vec = new Vector2(components["x"], components["y"]);
leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector2,
StringValue = vec.ToString(),
Vector2Value = vec
};
}
else if (components.Count == 3 &&
components.ContainsKey("x") &&
components.ContainsKey("y") &&
components.ContainsKey("z"))
{
Vector3 vec = new Vector3(
components["x"], components["y"], components["z"]);
leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector3,
StringValue = vec.ToString(),
Vector3Value = vec
};
}
else if (components.Count == 4 &&
components.ContainsKey("x") &&
components.ContainsKey("y") &&
components.ContainsKey("z") &&
components.ContainsKey("w"))
{
Vector4 vec = new Vector4(
components["x"], components["y"],
components["z"], components["w"]);
leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector4,
StringValue = vec.ToString(),
Vector4Value = vec
};
}
else
{
return false;
}
node = PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
return true;
}
static bool TryBuildInlineRect(
string name, string path, string displayName,
string inner, out PropertyTreeNode node)
{
node = null;
Dictionary<string, float> components = new Dictionary<string, float>(
StringComparer.OrdinalIgnoreCase);
foreach (string part in SplitInlineElements(inner))
{
if (!TrySplitKeyValue(part, out string key, out string val))
return false;
string lowerKey = key.ToLowerInvariant();
if (!RECT_COMPONENT_KEYS.Contains(lowerKey))
return false;
if (!float.TryParse(
UnquoteValue(val), NumberStyles.Float,
CultureInfo.InvariantCulture, out float parsed))
return false;
components[lowerKey] = parsed;
}
if (components.Count != 4 ||
!components.ContainsKey("x") ||
!components.ContainsKey("y") ||
!components.ContainsKey("width") ||
!components.ContainsKey("height"))
return false;
Rect rect = new Rect(
components["x"], components["y"],
components["width"], components["height"]);
LeafPropertyData leafData = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Rect,
StringValue = rect.ToString(),
RectValue = rect
};
node = PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
return true;
}
static PropertyTreeNode ParseInlineSequence(
string name, string path, string displayName, string text)
{
string inner = text.Substring(1, text.Length - 2).Trim();
if (string.IsNullOrEmpty(inner))
return PropertyTreeNode.CreateArray(
name, path, new List<PropertyTreeNode>(), displayName);
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
int index = 0;
foreach (string element in SplitInlineElements(inner))
{
string itemPath = $"{path}[{index}]";
string itemName = $"[{index}]";
children.Add(CreateTypedLeaf(itemName, itemPath, null, element));
index++;
}
return PropertyTreeNode.CreateArray(name, path, children, displayName);
}
#endregion
#region Type Inference
static PropertyTreeNode CreateTypedLeaf(
string name, string path, string displayName, string rawValue)
{
LeafPropertyData leafData = InferScalarType(name, path, rawValue);
return PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
}
static LeafPropertyData InferScalarType(string key, string path, string rawValue)
{
string raw = (rawValue ?? string.Empty).Trim();
bool wasQuoted = IsQuotedValue(raw);
string display = UnquoteValue(raw);
if (wasQuoted)
return MakeStringLeaf(display);
if (IsBooleanNumericValue(key, raw, out bool boolFromNumeric))
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Boolean,
BoolValue = boolFromNumeric,
StringValue = boolFromNumeric.ToString()
};
}
if (TryParseBooleanLiteral(raw, out bool boolValue))
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Boolean,
BoolValue = boolValue,
StringValue = boolValue.ToString()
};
}
if (int.TryParse(raw, NumberStyles.Integer,
CultureInfo.InvariantCulture, out int intValue))
{
LeafPropertyData intLeaf = new LeafPropertyData
{
PropertyType = SerializedPropertyType.Integer,
IntValue = intValue,
StringValue = intValue.ToString()
};
if (!string.IsNullOrEmpty(path) &&
IntPropertyFormatters.TryFormatPath(path, intValue, out string formatted))
{
intLeaf.StringValue = formatted;
intLeaf.HasFormattedDisplay = true;
}
return intLeaf;
}
if (LooksLikeFloat(raw) &&
float.TryParse(raw, NumberStyles.Float,
CultureInfo.InvariantCulture, out float floatValue))
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Float,
FloatValue = floatValue,
StringValue = floatValue.ToString("G")
};
}
return MakeStringLeaf(display);
}
static LeafPropertyData MakeStringLeaf(string value)
{
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.String,
StringValue = value
};
}
static bool IsBooleanNumericValue(
string key, string value, out bool result)
{
result = false;
if (value != "0" && value != "1")
return false;
if (string.IsNullOrEmpty(key))
return false;
string leafKey = ExtractLeafName(key);
if (BOOLEAN_HINT_KEYS.Contains(leafKey) || LooksLikeBooleanKey(leafKey))
{
result = value == "1";
return true;
}
return false;
}
static bool LooksLikeBooleanKey(string key)
{
return StartsWithAny(key,
"is", "has", "use", "can", "allow",
"enable", "disable", "force", "preload",
"normalize", "loop");
}
static bool StartsWithAny(string text, params string[] prefixes)
{
foreach (string prefix in prefixes)
{
if (text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
static bool TryParseBooleanLiteral(string value, out bool result)
{
if (value.Equals("true", StringComparison.OrdinalIgnoreCase) ||
value.Equals("yes", StringComparison.OrdinalIgnoreCase))
{
result = true;
return true;
}
if (value.Equals("false", StringComparison.OrdinalIgnoreCase) ||
value.Equals("no", StringComparison.OrdinalIgnoreCase))
{
result = false;
return true;
}
result = false;
return false;
}
static bool LooksLikeFloat(string value)
{
return value.IndexOf('.') >= 0 ||
value.IndexOf('e') >= 0 ||
value.IndexOf('E') >= 0;
}
#endregion
#region String Parsing Utilities
static IEnumerable<string> SplitInlineElements(string text)
{
List<string> result = new List<string>();
int start = 0;
int curlyDepth = 0;
int squareDepth = 0;
char quote = '\0';
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (quote != '\0')
{
if (c == quote && (i == 0 || text[i - 1] != '\\'))
quote = '\0';
continue;
}
if (c == '"' || c == '\'') { quote = c; continue; }
if (c == '{') { curlyDepth++; continue; }
if (c == '}') { curlyDepth--; continue; }
if (c == '[') { squareDepth++; continue; }
if (c == ']') { squareDepth--; continue; }
if (c == ',' && curlyDepth == 0 && squareDepth == 0)
{
result.Add(text.Substring(start, i - start).Trim());
start = i + 1;
}
}
if (start < text.Length)
result.Add(text.Substring(start).Trim());
return result;
}
static bool TrySplitKeyValue(
string text, out string key, out string value)
{
key = null;
value = null;
int curlyDepth = 0;
int squareDepth = 0;
char quote = '\0';
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (quote != '\0')
{
if (c == quote && (i == 0 || text[i - 1] != '\\'))
quote = '\0';
continue;
}
if (c == '"' || c == '\'') { quote = c; continue; }
if (c == '{') { curlyDepth++; continue; }
if (c == '}') { curlyDepth--; continue; }
if (c == '[') { squareDepth++; continue; }
if (c == ']') { squareDepth--; continue; }
if (c == ':' && curlyDepth == 0 && squareDepth == 0)
{
key = text.Substring(0, i).Trim();
value = text.Substring(i + 1).Trim();
return !string.IsNullOrEmpty(key);
}
}
return false;
}
static bool IsQuotedValue(string value)
{
if (string.IsNullOrEmpty(value) || value.Length < 2)
return false;
return (value[0] == '"' && value[value.Length - 1] == '"') ||
(value[0] == '\'' && value[value.Length - 1] == '\'');
}
static string UnquoteValue(string value)
{
return IsQuotedValue(value)
? value.Substring(1, value.Length - 2)
: value;
}
static int CountLeadingSpaces(string line)
{
int count = 0;
while (count < line.Length && line[count] == ' ')
count++;
return count;
}
static bool IsDirectiveLine(string content)
{
return content.StartsWith("%", StringComparison.Ordinal) ||
content.StartsWith("---", StringComparison.Ordinal) ||
content.StartsWith("...", StringComparison.Ordinal);
}
static string AppendPath(string basePath, string key)
{
return string.IsNullOrEmpty(basePath) ? key : $"{basePath}.{key}";
}
static string ExtractLeafName(string key)
{
int lastDot = key.LastIndexOf('.');
string segment = lastDot >= 0 ? key.Substring(lastDot + 1) : key;
int bracket = segment.IndexOf('[');
if (bracket >= 0)
segment = segment.Substring(0, bracket);
return segment;
}
static string TrimLineEnd(string line)
{
return line.TrimEnd('\r');
}
static void SkipBlankAndDirectiveLines(string[] lines, ref int lineIdx)
{
while (lineIdx < lines.Length)
{
string line = TrimLineEnd(lines[lineIdx]);
if (string.IsNullOrWhiteSpace(line))
{
lineIdx++;
continue;
}
int indent = CountLeadingSpaces(line);
string content = line.Substring(indent);
if (IsDirectiveLine(content))
{
lineIdx++;
continue;
}
break;
}
}
#endregion
#region Constants
static readonly HashSet<string> BOOLEAN_HINT_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"3D",
"ambisonic",
"alphaIsTransparency",
"convertToNormalmap",
"crunchedCompression",
"forceToMono",
"generateCubemap",
"ignorePngGamma",
"isReadable",
"loadInBackground",
"loopable",
"mipMapsPreserveCoverage",
"normalize",
"preloadAudioData",
"streamingMipmaps",
"sRGBTexture"
};
static readonly HashSet<string> VECTOR_COMPONENT_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "x", "y", "z", "w" };
static readonly HashSet<string> RECT_COMPONENT_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{ "x", "y", "width", "height" };
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5bd2166cb8eff417d8c9b840aeaa5709
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,30 @@
using System;
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Meta
{
internal static class MetaTreeHelpers
{
internal static PropertyTreeNode FilterIgnoredKeys(PropertyTreeNode root)
{
List<PropertyTreeNode> filteredChildren = new List<PropertyTreeNode>();
foreach (PropertyTreeNode child in root.Children)
{
if (!IGNORED_TOP_LEVEL_KEYS.Contains(child.Name))
filteredChildren.Add(child);
}
return PropertyTreeNode.CreateRoot(filteredChildren);
}
static readonly HashSet<string> IGNORED_TOP_LEVEL_KEYS =
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
{
"guid",
"timeCreated",
"licenseType"
};
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c7acea46926a4331a5b68771443e3ed0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,19 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class ObjectExtensions
{
internal static int GetObjectId(this UnityEngine.Object obj)
{
#if UNITY_6000_4_OR_NEWER
return obj.GetEntityId().GetHashCode();
#else
return obj.GetInstanceID();
#endif
}
internal static long GetLocalFileId(this UnityEngine.Object obj)
{
return (long)UnityInternals.UnityEditor.Unsupported.GetFileIDHint(obj);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 209109a5fbc749468a4eb859dc531bd2
timeCreated: 1777362119
@@ -0,0 +1,72 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Content;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class ObjectIconResolver
{
internal static UnityEngine.Texture GetIcon(ObjectContent objContent)
{
if (objContent.IsMetaFileObject)
return GetMetaIcon(objContent.MetaSectionName);
return GetObjectIcon(objContent.Object);
}
internal static UnityEngine.Texture GetIcon(ObjectDiff objDiff)
{
if (objDiff.IsMetaFileObject)
return GetMetaIcon(objDiff.MetaSectionName);
return GetObjectIcon(objDiff.SrcObject ?? objDiff.DstObject);
}
static UnityEngine.Texture GetObjectIcon(UnityEngine.Object obj)
{
if (obj == null)
return GetFallbackIcon();
GUIContent content = EditorGUIUtility.ObjectContent(obj, obj.GetType());
return content.image != null ? content.image : GetFallbackIcon();
}
// Section names arrive nicified ("Audio Importer"), but our match
// tokens are the unspaced YAML keys ("audioimporter"). Normalise by
// stripping whitespace before the lowercase contains-check.
static UnityEngine.Texture GetMetaIcon(string sectionName)
{
if (string.IsNullOrEmpty(sectionName))
return GetFallbackIcon();
string key = sectionName.Replace(" ", "").ToLowerInvariant();
if (key.Contains("textureimporter"))
return TryGetIcon("Texture Icon");
if (key.Contains("audioimporter"))
return TryGetIcon("AudioClip Icon");
if (key.Contains("modelimporter"))
return TryGetIcon("PrefabModel Icon");
if (key.Contains("sprite"))
return TryGetIcon("Sprite Icon");
if (key.Contains("platformsettings"))
return TryGetIcon("BuildSettings.Editor.Small");
return TryGetIcon("TextAsset Icon");
}
static UnityEngine.Texture TryGetIcon(string iconName)
{
GUIContent content = EditorGUIUtility.IconContent(iconName);
if (content == null || content.image == null)
return GetFallbackIcon();
return content.image;
}
static UnityEngine.Texture GetFallbackIcon()
{
return EditorGUIUtility.IconContent("DefaultAsset Icon").image;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ef733891bfbb64dd2baa2c1668c7021a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d0a9ebc8de8b8428fae0574a3a7abc3f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,129 @@
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
// Replaces the generic "Curve" display name on AnimationClip curve leaves
// with a label derived from the parent struct's `attribute` and `path`
// fields, mirroring Unity's Animation window naming
// (e.g. "Position.x", "Rotation.y (Spine/Head)").
internal static class AnimationClipCurveLabels
{
internal static void TryDecorate(
List<PropertyTreeNode> arrayElements, string arrayPath)
{
if (!IsCurveArray(arrayPath))
return;
string fallback = GetFallbackLabel(arrayPath);
for (int i = 0; i < arrayElements.Count; i++)
{
PropertyTreeNode element = arrayElements[i];
if (element.Kind != NodeKind.Object)
continue;
PropertyTreeNode curveChild = null;
string attribute = null;
string targetPath = null;
foreach (PropertyTreeNode child in element.Children)
{
switch (child.Name)
{
case "curve": curveChild = child; break;
case "attribute": attribute = child.Value; break;
case "path": targetPath = child.Value; break;
}
}
if (curveChild == null || curveChild.Kind != NodeKind.Leaf)
continue;
string label = BuildLabel(attribute, targetPath, fallback);
arrayElements[i] = ReplaceChildDisplayName(element, curveChild, label);
}
}
static bool IsCurveArray(string path)
{
switch (path)
{
case "m_PositionCurves":
case "m_RotationCurves":
case "m_ScaleCurves":
case "m_EulerCurves":
case "m_FloatCurves":
case "m_PPtrCurves":
case "m_EditorCurves":
case "m_EulerEditorCurves":
return true;
default:
return false;
}
}
static string GetFallbackLabel(string arrayPath)
{
switch (arrayPath)
{
case "m_PositionCurves": return "Position";
case "m_RotationCurves": return "Rotation";
case "m_ScaleCurves": return "Scale";
case "m_EulerCurves": return "Rotation (Euler)";
case "m_EulerEditorCurves": return "Rotation (Euler)";
default: return "Curve";
}
}
static string BuildLabel(
string attribute, string targetPath, string fallback)
{
string baseLabel = string.IsNullOrEmpty(attribute)
? fallback
: StripAttributePrefix(attribute);
if (string.IsNullOrEmpty(targetPath))
return baseLabel;
return baseLabel + " (" + targetPath + ")";
}
static string StripAttributePrefix(string attribute)
{
if (attribute.StartsWith("m_Local"))
return attribute.Substring("m_Local".Length);
if (attribute.StartsWith("m_"))
return attribute.Substring(2);
return attribute;
}
static PropertyTreeNode ReplaceChildDisplayName(
PropertyTreeNode parent,
PropertyTreeNode targetChild,
string newDisplayName)
{
List<PropertyTreeNode> newChildren = new List<PropertyTreeNode>(
parent.Children.Count);
foreach (PropertyTreeNode child in parent.Children)
{
if (child == targetChild)
{
newChildren.Add(PropertyTreeNode.CreateLeaf(
child.Name, child.Path, child.TypeTag, child.Value,
newDisplayName, child.Tag));
continue;
}
newChildren.Add(child);
}
return PropertyTreeNode.CreateObject(
parent.Name, parent.Path, newChildren, parent.DisplayName, parent.Tag);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8c2f1ab3d4e5f64a9b7c0d1e2f3a4b5c
timeCreated: 1763000000
@@ -0,0 +1,47 @@
using UnityEditor;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class GroupHeaderLabels
{
internal static string ForArray(string displayName, string path)
{
if (string.IsNullOrEmpty(displayName) || displayName.StartsWith("m_"))
return ObjectNames.NicifyVariableName(SafeLastSegment(path));
return displayName;
}
internal static string ForArrayElement(string path)
{
return ELEMENT_PREFIX + (ExtractTrailingElementIndex(path) + 1);
}
static string SafeLastSegment(string path)
{
if (string.IsNullOrEmpty(path))
return string.Empty;
int lastDot = path.LastIndexOf('.');
return lastDot < 0 ? path : path.Substring(lastDot + 1);
}
static int ExtractTrailingElementIndex(string path)
{
if (string.IsNullOrEmpty(path))
return 0;
int closeBracket = path.LastIndexOf(']');
if (closeBracket <= 0)
return 0;
int openBracket = path.LastIndexOf('[', closeBracket - 1);
if (openBracket < 0)
return 0;
string indexText = path.Substring(
openBracket + 1, closeBracket - openBracket - 1);
return int.TryParse(indexText, out int idx) ? idx : 0;
}
const string ELEMENT_PREFIX = "Element ";
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5efbadbb9912116bb00fdab47698bcf4
timeCreated: 1747000000
@@ -0,0 +1,67 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class IgnoredProperties
{
internal static bool IsIgnored(string propertyPath)
{
// editor-only flags on every UnityEngine.Object
if (propertyPath == "m_ObjectHideFlags")
return true;
if (propertyPath == "m_EditorHideFlags")
return true;
// internal class-mapping field on MonoBehaviours
if (propertyPath == "m_EditorClassIdentifier")
return true;
// reference to the script asset itself
if (propertyPath == "m_Script" || propertyPath.StartsWith("m_Script."))
return true;
// opaque serialized-reference IDs inside ObjectReference fields
if (propertyPath.Contains(".m_FileID") || propertyPath.Contains(".m_PathID"))
return true;
// prefab system bookkeeping (includes legacy pre-2018.3 names)
if (propertyPath == "m_CorrespondingSourceObject" ||
propertyPath == "m_PrefabInstance" ||
propertyPath == "m_PrefabAsset" ||
propertyPath == "m_PrefabParentObject" ||
propertyPath == "m_PrefabInternal")
return true;
// GameObject's component list — components are diffed individually
if (propertyPath == "m_Component" || propertyPath.StartsWith("m_Component."))
return true;
// back-reference from Component to its owning GameObject
if (propertyPath == "m_GameObject" || propertyPath.StartsWith("m_GameObject."))
return true;
// scene/prefab root list — structural, not property data
if (propertyPath == "m_Roots" || propertyPath.StartsWith("m_Roots."))
return true;
// Transform hierarchy (parent/children/sibling order)
if (propertyPath == "m_Children" || propertyPath.StartsWith("m_Children."))
return true;
if (propertyPath == "m_Father" || propertyPath.StartsWith("m_Father."))
return true;
if (propertyPath == "m_RootOrder")
return true;
// redundant editor hint — the real rotation is m_LocalRotation
if (propertyPath.StartsWith("m_LocalEulerAnglesHint"))
return true;
// editor-only shadow data for animation curves
if (propertyPath == "m_EditorCurves" || propertyPath.StartsWith("m_EditorCurves."))
return true;
if (propertyPath == "m_EulerEditorCurves" || propertyPath.StartsWith("m_EulerEditorCurves."))
return true;
return false;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1c717ffc06a346f49df5a2fe06338439
timeCreated: 1775035659
@@ -0,0 +1,306 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class IntPropertyFormatters
{
internal static bool TryFormat(SerializedProperty prop, out string display)
{
display = null;
if (prop.propertyType == SerializedPropertyType.LayerMask)
{
display = FormatLayerMaskBits(prop.intValue);
return true;
}
if (prop.propertyType != SerializedPropertyType.Integer)
return false;
UnityEngine.Object target = prop.serializedObject.targetObject;
int value = prop.intValue;
if (TryFormatFromRegistry(target, prop.propertyPath, value, out display))
return true;
if (TryFormatFromReflectedEnum(target, prop.propertyPath, value, out display))
return true;
return TryFormatFromPathFallback(prop.propertyPath, value, out display);
}
internal static bool TryFormatPath(string path, int value, out string display)
{
return TryFormatFromPathFallback(path, value, out display);
}
internal static string FormatEnum(Type enumType, int value)
{
bool bIsFlags = enumType.IsDefined(typeof(FlagsAttribute), inherit: false);
if (bIsFlags)
{
if (value == 0)
return NOTHING_LABEL;
return NicifyFlagsList(Enum.ToObject(enumType, value).ToString());
}
string name = Enum.GetName(enumType, value);
return name == null ? value.ToString() : ObjectNames.NicifyVariableName(name);
}
static string NicifyFlagsList(string commaJoined)
{
if (string.IsNullOrEmpty(commaJoined))
return commaJoined;
string[] parts = commaJoined.Split(',');
for (int i = 0; i < parts.Length; i++)
parts[i] = ObjectNames.NicifyVariableName(parts[i].Trim());
return string.Join(", ", parts);
}
static bool TryFormatFromRegistry(
UnityEngine.Object target, string path, int value, out string display)
{
display = null;
if (target == null)
return false;
Type type = target.GetType();
for (Type t = type; t != null; t = t.BaseType)
{
Func<int, string> formatter;
if (mRegistry.TryGetValue(BuildKey(t, path), out formatter))
{
display = formatter(value);
return display != null;
}
}
return false;
}
static bool TryFormatFromPathFallback(string path, int value, out string display)
{
display = null;
Func<int, string> fallback;
if (mFallbackByPath.TryGetValue(path, out fallback))
{
display = fallback(value);
return display != null;
}
return false;
}
static bool TryFormatFromReflectedEnum(
UnityEngine.Object target, string path, int value, out string display)
{
display = null;
if (target == null)
return false;
FieldInfo field = ResolveFieldByPath(target.GetType(), path);
if (field == null || !field.FieldType.IsEnum)
return false;
display = FormatEnum(field.FieldType, value);
return true;
}
static FieldInfo ResolveFieldByPath(Type type, string path)
{
const BindingFlags FLAGS =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
Type current = type;
FieldInfo field = null;
string[] segments = path.Split('.');
for (int i = 0; i < segments.Length; i++)
{
if (current == null)
return null;
string segment = segments[i];
if (segment == "Array" || segment.StartsWith("data["))
return null;
field = current.GetField(segment, FLAGS);
if (field == null)
return null;
current = field.FieldType;
}
return field;
}
static string FormatStaticEditorFlags(int value)
{
if (value == 0)
return NOTHING_LABEL;
if (value == int.MaxValue)
return EVERYTHING_LABEL;
string raw = ((StaticEditorFlags)value).ToString()
.Replace(
"LightmapStatic", // obsolete -> use ContributeGI
nameof(StaticEditorFlags.ContributeGI));
return NicifyFlagsList(raw);
}
static string FormatLayer(int value)
{
string name = LayerMask.LayerToName(value);
return string.IsNullOrEmpty(name) ? value.ToString() : name;
}
static string FormatTargetDisplay(int value)
{
return string.Format("Display {0}", value + 1);
}
static string FormatLayerMaskBits(int value)
{
if (value == 0)
return "Nothing";
uint bits = unchecked((uint)value);
if (bits == uint.MaxValue)
return "Everything";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 32; i++)
{
if ((bits & (1u << i)) == 0)
continue;
string layerName = LayerMask.LayerToName(i);
if (string.IsNullOrEmpty(layerName))
continue;
if (builder.Length > 0)
builder.Append(", ");
builder.Append(layerName);
}
if (builder.Length == 0)
return string.Format("0x{0:X8}", bits);
return builder.ToString();
}
static string BuildKey(Type type, string path)
{
return string.Concat(type.FullName, "|", path);
}
static Dictionary<string, Func<int, string>> BuildRegistry()
{
Dictionary<string, Func<int, string>> registry =
new Dictionary<string, Func<int, string>>();
Add(registry, typeof(GameObject), "m_StaticEditorFlags", FormatStaticEditorFlags);
Add(registry, typeof(GameObject), "m_Layer", FormatLayer);
Add(registry, typeof(Camera), "m_FOVAxisMode",
value => FormatEnum(typeof(Camera.FieldOfViewAxis), value));
Add(registry, typeof(Camera), "m_GateFitMode",
value => FormatEnum(typeof(Camera.GateFitMode), value));
Add(registry, typeof(Camera), "m_RenderingPath",
value => FormatEnum(typeof(RenderingPath), value));
Add(registry, typeof(Camera), "m_TargetEye",
value => FormatEnum(typeof(StereoTargetEyeMask), value));
Add(registry, typeof(Camera), "m_ClearFlags",
value => FormatEnum(typeof(CameraClearFlags), value));
Add(registry, typeof(Camera), "m_TargetDisplay", FormatTargetDisplay);
Add(registry, typeof(Light), "m_Type",
value => FormatEnum(typeof(LightType), value));
Add(registry, typeof(Light), "m_Lightmapping",
value => FormatEnum(typeof(LightmapBakeType), value));
Add(registry, typeof(Light), "m_Shadows.m_Type",
value => FormatEnum(typeof(LightShadows), value));
Add(registry, typeof(Renderer), "m_LightProbeUsage",
value => FormatEnum(typeof(LightProbeUsage), value));
Add(registry, typeof(Renderer), "m_ReflectionProbeUsage",
value => FormatEnum(typeof(ReflectionProbeUsage), value));
Add(registry, typeof(ReflectionProbe), "m_Mode",
value => FormatEnum(typeof(ReflectionProbeMode), value));
Add(registry, typeof(ReflectionProbe), "m_ClearFlags",
value => FormatEnum(typeof(CameraClearFlags), value));
Add(registry, typeof(Rigidbody), "m_Constraints",
value => FormatEnum(typeof(RigidbodyConstraints), value));
Add(registry, typeof(Rigidbody2D), "m_Constraints",
value => FormatEnum(typeof(RigidbodyConstraints2D), value));
return registry;
}
static Dictionary<string, Func<int, string>> BuildFallbackByPath()
{
// Path-keyed entries used when sRegistry has no match, or when the caller
// has no target type at all (meta-file YAML parsing). Reach for sRegistry
// first; only add here when one of the cases below applies.
Dictionary<string, Func<int, string>> fallback =
new Dictionary<string, Func<int, string>>();
// LayerMask struct fields appear on many unrelated components
// (Camera, Rigidbody, every Collider variant...). Path-keyed avoids
// listing one entry per component type.
fallback["m_CullingMask.m_Bits"] = FormatLayerMaskBits;
fallback["m_IncludeLayers.m_Bits"] = FormatLayerMaskBits;
fallback["m_ExcludeLayers.m_Bits"] = FormatLayerMaskBits;
// Meta-file YAML has no SerializedObject, so MetaPropertyTreeBuilder
// calls TryFormatPath without a target type. The full path includes
// the document type prefix produced by the YAML parser.
fallback["AudioImporter.defaultSettings.loadType"] =
value => FormatEnum(typeof(AudioClipLoadType), value);
fallback["AudioImporter.defaultSettings.compressionFormat"] =
value => FormatEnum(typeof(AudioCompressionFormat), value);
fallback["AudioImporter.defaultSettings.sampleRateSetting"] =
value => FormatEnum(typeof(AudioSampleRateSetting), value);
return fallback;
}
static void Add(
Dictionary<string, Func<int, string>> registry,
Type type,
string path,
Func<int, string> formatter)
{
registry[BuildKey(type, path)] = formatter;
}
const string NOTHING_LABEL = "Nothing";
const string EVERYTHING_LABEL = "Everything";
static readonly Dictionary<string, Func<int, string>> mRegistry = BuildRegistry();
static readonly Dictionary<string, Func<int, string>> mFallbackByPath =
BuildFallbackByPath();
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: b8354167bc3f4fe68167ff2823a4334e
timeCreated: 1778574522
@@ -0,0 +1,180 @@
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal struct LeafPropertyData
{
internal SerializedPropertyType PropertyType;
internal string StringValue;
internal float FloatValue;
internal int IntValue;
internal bool BoolValue;
internal Vector2 Vector2Value;
internal Vector3 Vector3Value;
internal Vector4 Vector4Value;
internal Vector2Int Vector2IntValue;
internal Vector3Int Vector3IntValue;
internal Color ColorValue;
internal Quaternion QuaternionValue;
internal Rect RectValue;
internal Bounds BoundsValue;
internal AnimationCurve AnimationCurveValue;
internal Gradient GradientValue;
internal RectInt RectIntValue;
internal BoundsInt BoundsIntValue;
internal Hash128 Hash128Value;
internal bool HasFormattedDisplay;
internal static LeafPropertyData FromProperty(SerializedProperty prop)
{
LeafPropertyData data = new LeafPropertyData
{
PropertyType = prop.propertyType,
StringValue = GetStringValue(prop)
};
switch (prop.propertyType)
{
case SerializedPropertyType.Float:
data.FloatValue = prop.floatValue; break;
case SerializedPropertyType.Integer:
data.IntValue = prop.intValue;
string formattedInt;
if (IntPropertyFormatters.TryFormat(prop, out formattedInt))
{
data.StringValue = formattedInt;
data.HasFormattedDisplay = true;
}
break;
case SerializedPropertyType.LayerMask:
data.IntValue = prop.intValue;
string formattedLayerMask;
if (IntPropertyFormatters.TryFormat(prop, out formattedLayerMask))
{
data.StringValue = formattedLayerMask;
data.HasFormattedDisplay = true;
}
break;
case SerializedPropertyType.Character:
data.IntValue = prop.intValue; break;
case SerializedPropertyType.Boolean:
data.BoolValue = prop.boolValue; break;
case SerializedPropertyType.Vector2:
data.Vector2Value = prop.vector2Value; break;
case SerializedPropertyType.Vector3:
data.Vector3Value = prop.vector3Value; break;
case SerializedPropertyType.Vector4:
data.Vector4Value = prop.vector4Value; break;
case SerializedPropertyType.Vector2Int:
data.Vector2IntValue = prop.vector2IntValue; break;
case SerializedPropertyType.Vector3Int:
data.Vector3IntValue = prop.vector3IntValue; break;
case SerializedPropertyType.Color:
data.ColorValue = prop.colorValue; break;
case SerializedPropertyType.Quaternion:
data.QuaternionValue = prop.quaternionValue; break;
case SerializedPropertyType.Rect:
data.RectValue = prop.rectValue; break;
case SerializedPropertyType.Bounds:
data.BoundsValue = prop.boundsValue; break;
case SerializedPropertyType.String:
data.StringValue = prop.stringValue; break;
case SerializedPropertyType.Enum:
data.IntValue = prop.enumValueIndex;
data.StringValue = prop.enumDisplayNames.Length > prop.enumValueIndex
&& prop.enumValueIndex >= 0
? prop.enumDisplayNames[prop.enumValueIndex]
: prop.enumValueIndex.ToString();
break;
case SerializedPropertyType.AnimationCurve:
data.AnimationCurveValue = prop.animationCurveValue; break;
case SerializedPropertyType.Gradient:
data.GradientValue = prop.gradientValue; break;
case SerializedPropertyType.RectInt:
data.RectIntValue = prop.rectIntValue; break;
case SerializedPropertyType.BoundsInt:
data.BoundsIntValue = prop.boundsIntValue; break;
case SerializedPropertyType.Hash128:
data.Hash128Value = prop.hash128Value; break;
}
return data;
}
static string GetStringValue(SerializedProperty prop)
{
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
string formattedInt;
if (IntPropertyFormatters.TryFormat(prop, out formattedInt))
return formattedInt;
return prop.intValue.ToString();
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.FixedBufferSize:
return prop.intValue.ToString();
case SerializedPropertyType.Boolean:
return prop.boolValue.ToString();
case SerializedPropertyType.Float:
return prop.floatValue.ToString("G");
case SerializedPropertyType.String:
return prop.stringValue;
case SerializedPropertyType.Color:
return prop.colorValue.ToString();
case SerializedPropertyType.ObjectReference:
UnityEngine.Object obj = prop.objectReferenceValue;
return obj == null
? "(None)"
: $"{obj.GetType().Name}: {obj.name}";
case SerializedPropertyType.LayerMask:
string formattedLayerMask;
if (IntPropertyFormatters.TryFormat(prop, out formattedLayerMask))
return formattedLayerMask;
return prop.intValue.ToString();
case SerializedPropertyType.Enum:
return prop.enumDisplayNames.Length > prop.enumValueIndex
&& prop.enumValueIndex >= 0
? prop.enumDisplayNames[prop.enumValueIndex]
: prop.enumValueIndex.ToString();
case SerializedPropertyType.Vector2:
return prop.vector2Value.ToString();
case SerializedPropertyType.Vector3:
return prop.vector3Value.ToString();
case SerializedPropertyType.Vector4:
return prop.vector4Value.ToString();
case SerializedPropertyType.Rect:
return prop.rectValue.ToString();
case SerializedPropertyType.Character:
return ((char)prop.intValue).ToString();
case SerializedPropertyType.AnimationCurve:
AnimationCurve curve = prop.animationCurveValue;
return curve != null
? $"AnimationCurve ({curve.length} keys)"
: "AnimationCurve (empty)";
case SerializedPropertyType.Gradient:
Gradient gradient = prop.gradientValue;
return gradient != null
? $"Gradient ({gradient.colorKeys.Length} color keys, " +
$"{gradient.alphaKeys.Length} alpha keys)"
: "Gradient (empty)";
case SerializedPropertyType.Bounds:
return prop.boundsValue.ToString();
case SerializedPropertyType.Quaternion:
return prop.quaternionValue.eulerAngles.ToString();
case SerializedPropertyType.Vector2Int:
return prop.vector2IntValue.ToString();
case SerializedPropertyType.Vector3Int:
return prop.vector3IntValue.ToString();
case SerializedPropertyType.RectInt:
return prop.rectIntValue.ToString();
case SerializedPropertyType.BoundsInt:
return prop.boundsIntValue.ToString();
case SerializedPropertyType.Hash128:
return prop.hash128Value.ToString();
default:
return $"({prop.propertyType})";
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: a3d594c59c4d4cbfb273172a2edb6247
timeCreated: 1774968113
@@ -0,0 +1,272 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal static class PropertyTreeBuilder
{
internal static PropertyTreeNode Build(SerializedObject so)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
SerializedProperty prop = so.GetIterator();
if (!prop.Next(true))
return PropertyTreeNode.CreateRoot(children);
do
{
if (IgnoredProperties.IsIgnored(prop.propertyPath))
continue;
children.Add(BuildNode(prop.Copy(), isArrayElement: false));
}
while (prop.Next(false));
return PropertyTreeNode.CreateRoot(children);
}
static PropertyTreeNode BuildNode(
SerializedProperty prop,
bool isArrayElement)
{
string name = ExtractLocalName(prop.propertyPath);
string path = prop.propertyPath;
string displayName = BuildDisplayName(prop);
if (IsLeafProperty(prop))
{
LeafPropertyData leafData = BuildLeafData(prop);
return PropertyTreeNode.CreateLeaf(
name, path, leafData.PropertyType.ToString(),
leafData.StringValue, displayName, leafData);
}
if (isArrayElement)
displayName = GroupHeaderLabels.ForArrayElement(path);
else if (prop.isArray)
displayName = GroupHeaderLabels.ForArray(displayName, path);
if (prop.isArray)
return BuildArrayNode(prop, name, path, displayName);
return BuildObjectNode(prop, name, path, displayName);
}
static LeafPropertyData BuildLeafData(SerializedProperty prop)
{
if (prop.propertyPath == "m_LocalRotation"
&& prop.propertyType == SerializedPropertyType.Quaternion
&& prop.serializedObject.targetObject is Transform transform)
{
Vector3 inspectorEuler = TransformUtils.GetInspectorRotation(transform);
return new LeafPropertyData
{
PropertyType = SerializedPropertyType.Vector3,
Vector3Value = inspectorEuler,
StringValue = inspectorEuler.ToString()
};
}
return LeafPropertyData.FromProperty(prop);
}
static PropertyTreeNode BuildArrayNode(
SerializedProperty prop,
string name,
string path,
string displayName)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
for (int i = 0; i < prop.arraySize; i++)
{
SerializedProperty element = prop.GetArrayElementAtIndex(i);
if (IgnoredProperties.IsIgnored(element.propertyPath))
continue;
children.Add(BuildNode(element.Copy(), isArrayElement: true));
}
AnimationClipCurveLabels.TryDecorate(children, path);
if (IsKeyedArray(prop))
return BuildKeyedArrayAsObject(children, name, path, displayName);
return PropertyTreeNode.CreateArray(name, path, children, displayName);
}
static PropertyTreeNode BuildKeyedArrayAsObject(
List<PropertyTreeNode> rawElements,
string name,
string path,
string displayName)
{
List<PropertyTreeNode> namedChildren = new List<PropertyTreeNode>();
foreach (PropertyTreeNode element in rawElements)
{
string key = null;
PropertyTreeNode valueNode = null;
foreach (PropertyTreeNode child in element.Children)
{
if (child.Name == "first" && child.Kind == NodeKind.Leaf)
key = child.Value;
else if (child.Name == "second")
valueNode = child;
}
if (key != null && valueNode != null)
{
string childPath = path + "." + key;
string childDisplayName = ObjectNames.NicifyVariableName(
key.TrimStart('_'));
if (valueNode.Kind == NodeKind.Leaf)
{
namedChildren.Add(PropertyTreeNode.CreateLeaf(
key, childPath, valueNode.TypeTag,
valueNode.Value, childDisplayName, valueNode.Tag));
}
else
{
List<PropertyTreeNode> rewrappedChildren = new List<PropertyTreeNode>(
valueNode.Children);
namedChildren.Add(PropertyTreeNode.CreateObject(
key, childPath, rewrappedChildren, childDisplayName));
}
}
else
{
namedChildren.Add(element);
}
}
return PropertyTreeNode.CreateObject(name, path, namedChildren, displayName);
}
static PropertyTreeNode BuildObjectNode(
SerializedProperty prop,
string name,
string path,
string displayName)
{
List<PropertyTreeNode> children = new List<PropertyTreeNode>();
int parentDepth = prop.depth;
SerializedProperty iter = prop.Copy();
if (!iter.Next(true) || iter.depth <= parentDepth)
return PropertyTreeNode.CreateObject(name, path, children, displayName);
do
{
if (!IgnoredProperties.IsIgnored(iter.propertyPath))
children.Add(BuildNode(iter.Copy(), isArrayElement: false));
}
while (iter.Next(false) && iter.depth > parentDepth);
return PropertyTreeNode.CreateObject(name, path, children, displayName);
}
static bool IsKeyedArray(SerializedProperty arrayProp)
{
if (arrayProp.arraySize == 0)
return false;
SerializedProperty firstElement = arrayProp.GetArrayElementAtIndex(0);
if (firstElement.propertyType != SerializedPropertyType.Generic)
return false;
int parentDepth = firstElement.depth;
SerializedProperty iter = firstElement.Copy();
if (!iter.Next(true) || iter.depth <= parentDepth)
return false;
bool hasFirst = false;
bool hasSecond = false;
do
{
string localName = ExtractLocalName(iter.propertyPath);
if (localName == "first" && iter.propertyType == SerializedPropertyType.String)
hasFirst = true;
else if (localName == "second")
hasSecond = true;
}
while (iter.Next(false) && iter.depth > parentDepth);
return hasFirst && hasSecond;
}
static bool IsLeafProperty(SerializedProperty prop)
{
switch (prop.propertyType)
{
case SerializedPropertyType.Integer:
case SerializedPropertyType.Boolean:
case SerializedPropertyType.Float:
case SerializedPropertyType.String:
case SerializedPropertyType.Color:
case SerializedPropertyType.ObjectReference:
case SerializedPropertyType.LayerMask:
case SerializedPropertyType.Enum:
case SerializedPropertyType.Vector2:
case SerializedPropertyType.Vector3:
case SerializedPropertyType.Vector4:
case SerializedPropertyType.Rect:
case SerializedPropertyType.Character:
case SerializedPropertyType.AnimationCurve:
case SerializedPropertyType.Bounds:
case SerializedPropertyType.Gradient:
case SerializedPropertyType.Quaternion:
case SerializedPropertyType.Vector2Int:
case SerializedPropertyType.Vector3Int:
case SerializedPropertyType.RectInt:
case SerializedPropertyType.BoundsInt:
case SerializedPropertyType.Hash128:
return true;
case SerializedPropertyType.Generic:
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.FixedBufferSize:
return false;
default:
return !prop.hasChildren;
}
}
static string BuildDisplayName(SerializedProperty prop)
{
string path = prop.propertyPath;
if (path.StartsWith("m_LocalPosition"))
return prop.displayName.Replace("Local ", "");
if (path.StartsWith("m_LocalRotation"))
return prop.displayName.Replace("Local ", "");
if (path.StartsWith("m_LocalScale"))
return prop.displayName.Replace("Local ", "");
return prop.displayName;
}
static string ExtractLocalName(string propertyPath)
{
int lastDot = propertyPath.LastIndexOf('.');
if (lastDot < 0)
return propertyPath;
return propertyPath.Substring(lastDot + 1);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 8bf6e2e635fb45979c87aac695ae7567
timeCreated: 1774968004
@@ -0,0 +1,85 @@
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
internal enum NodeKind : byte
{
Leaf,
Object,
Array
}
internal class PropertyTreeNode
{
internal string Name { get; }
internal string Path { get; }
internal string DisplayName { get; }
internal NodeKind Kind { get; }
internal string TypeTag { get; }
internal string Value { get; }
internal IReadOnlyList<PropertyTreeNode> Children => mChildren;
internal object Tag { get; }
internal PropertyTreeNode(
string name,
string path,
string displayName,
NodeKind kind,
string typeTag,
string value,
List<PropertyTreeNode> children,
object tag)
{
Name = name ?? string.Empty;
Path = path ?? string.Empty;
DisplayName = displayName ?? name ?? string.Empty;
Kind = kind;
TypeTag = typeTag ?? string.Empty;
Value = value;
mChildren = children ?? EMPTY_CHILDREN;
Tag = tag;
}
internal static PropertyTreeNode CreateLeaf(
string name,
string path,
string typeTag,
string value,
string displayName = null,
object tag = null)
{
return new PropertyTreeNode(
name, path, displayName, NodeKind.Leaf, typeTag, value, null, tag);
}
internal static PropertyTreeNode CreateObject(
string name,
string path,
List<PropertyTreeNode> children,
string displayName = null,
object tag = null)
{
return new PropertyTreeNode(
name, path, displayName, NodeKind.Object, "Generic", null, children, tag);
}
internal static PropertyTreeNode CreateArray(
string name,
string path,
List<PropertyTreeNode> children,
string displayName = null,
object tag = null)
{
return new PropertyTreeNode(
name, path, displayName, NodeKind.Array, "Array", null, children, tag);
}
internal static PropertyTreeNode CreateRoot(List<PropertyTreeNode> children)
{
return CreateObject(string.Empty, string.Empty, children);
}
static readonly List<PropertyTreeNode> EMPTY_CHILDREN = new List<PropertyTreeNode>();
readonly List<PropertyTreeNode> mChildren;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 54e0e46a04464397b85f0fd0f73f9d33
timeCreated: 1774968610
@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.Property
{
// Walks a property tree (PropertyTreeNode or PropertyDiffNode) and emits
// rows via caller-supplied callbacks. Replaces the previously duplicated
// AddTreeNode recursion in AssetDiffControl and AssetContentControl with
// a single generic walker, parameterised on the node type via accessors
// (mirroring the HierarchyOrderSorting<T> precedent in this codebase).
internal class PropertyTreeWalker<TNode>
{
internal PropertyTreeWalker(
Func<TNode, NodeKind> getKind,
Func<TNode, IReadOnlyList<TNode>> getChildren)
{
mGetKind = getKind;
mGetChildren = getChildren;
}
// Visits every container in the tree and registers its group key,
// regardless of visibility or expansion state. Run before Walk so
// that CollapseAll can collapse groups that are currently hidden by
// filter / search — otherwise those groups would silently fall out
// of mKnownGroups and re-appear expanded when the filter clears.
internal void CollectGroupKeys(
IReadOnlyList<TNode> roots,
Func<TNode, string> buildGroupKey,
Action<string> registerGroupKey)
{
foreach (TNode node in roots)
CollectGroupKeysFromNode(node, buildGroupKey, registerGroupKey);
}
internal void Walk(
IReadOnlyList<TNode> roots,
int baseIndent,
Func<TNode, bool> isVisible,
Func<TNode, string> buildGroupKey,
Func<string, bool> isExpanded,
Action<TNode, int> emitLeaf,
Action<TNode, int, string> emitContainerHeader)
{
foreach (TNode node in roots)
WalkNode(
node, baseIndent,
isVisible, buildGroupKey, isExpanded,
emitLeaf, emitContainerHeader);
}
void CollectGroupKeysFromNode(
TNode node,
Func<TNode, string> buildGroupKey,
Action<string> registerGroupKey)
{
if (mGetKind(node) == NodeKind.Leaf)
return;
IReadOnlyList<TNode> children = mGetChildren(node);
if (children.Count == 0)
return;
registerGroupKey(buildGroupKey(node));
foreach (TNode child in children)
CollectGroupKeysFromNode(child, buildGroupKey, registerGroupKey);
}
void WalkNode(
TNode node,
int indent,
Func<TNode, bool> isVisible,
Func<TNode, string> buildGroupKey,
Func<string, bool> isExpanded,
Action<TNode, int> emitLeaf,
Action<TNode, int, string> emitContainerHeader)
{
if (!isVisible(node))
return;
if (mGetKind(node) == NodeKind.Leaf)
{
emitLeaf(node, indent);
return;
}
IReadOnlyList<TNode> children = mGetChildren(node);
string fullKey = buildGroupKey(node);
emitContainerHeader(node, indent, fullKey);
if (children.Count == 0 || !isExpanded(fullKey))
return;
foreach (TNode child in children)
WalkNode(
child, indent + 1,
isVisible, buildGroupKey, isExpanded,
emitLeaf, emitContainerHeader);
}
readonly Func<TNode, NodeKind> mGetKind;
readonly Func<TNode, IReadOnlyList<TNode>> mGetChildren;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d26996aad4c14674bb5bc7a9b6704930
timeCreated: 1779062400
@@ -0,0 +1,71 @@
using UnityEditor;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.UI;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class PropertyRow
{
internal const float BASE_PADDING_LEFT = 20f;
internal const float INDENT_PX = 16f;
internal const float LABEL_WIDTH = 180f;
internal const float LABEL_MIN_WIDTH = 60f;
internal static bool IsTallProperty(object tag)
{
if (!(tag is LeafPropertyData leaf))
return false;
switch (leaf.PropertyType)
{
case SerializedPropertyType.Rect:
case SerializedPropertyType.RectInt:
case SerializedPropertyType.Bounds:
case SerializedPropertyType.BoundsInt:
return true;
default:
return false;
}
}
internal static VisualElement BuildPanel(out Label nameLabel)
{
VisualElement panel = new VisualElement();
panel.style.flexGrow = 1;
panel.style.flexBasis = 0;
panel.style.flexDirection = FlexDirection.Row;
panel.style.alignItems = Align.FlexStart;
panel.style.paddingLeft = BASE_PADDING_LEFT;
panel.style.paddingRight = 4;
panel.style.paddingTop = 3;
panel.style.paddingBottom = 1;
nameLabel = new Label();
nameLabel.style.width = LABEL_WIDTH;
nameLabel.style.minWidth = LABEL_MIN_WIDTH;
nameLabel.style.fontSize = 12;
nameLabel.style.overflow = Overflow.Hidden;
nameLabel.style.textOverflow = TextOverflow.Ellipsis;
nameLabel.style.color = UnityStyles.Colors.DefaultText;
panel.Add(nameLabel);
return panel;
}
internal static void ConfigureNameLabel(
Label label,
bool hasContent,
bool hasSearch,
string displayLabel,
string tooltipPath)
{
label.enableRichText = hasSearch;
label.text = hasContent ? displayLabel : string.Empty;
label.tooltip = hasContent ? tooltipPath : string.Empty;
label.style.display = hasContent
? DisplayStyle.Flex : DisplayStyle.None;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fc66293009c443c68b1a22dc6b931e6f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,57 @@
using System;
using System.Text;
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class SearchHighlight
{
internal static string Apply(string text, string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm) || string.IsNullOrEmpty(text))
return text;
int firstIdx = text.IndexOf(
searchTerm, StringComparison.OrdinalIgnoreCase);
if (firstIdx < 0)
return text;
string openTag = GetOpenTag();
int searchLen = searchTerm.Length;
StringBuilder sb = new StringBuilder(
text.Length + openTag.Length + CLOSE_TAG.Length);
int startIdx = 0;
while (startIdx < text.Length)
{
int idx = text.IndexOf(
searchTerm, startIdx, StringComparison.OrdinalIgnoreCase);
if (idx < 0)
{
sb.Append(text, startIdx, text.Length - startIdx);
break;
}
sb.Append(text, startIdx, idx - startIdx);
sb.Append(openTag);
sb.Append(text, idx, searchLen);
sb.Append(CLOSE_TAG);
startIdx = idx + searchLen;
}
return sb.ToString();
}
static string GetOpenTag()
{
string bgHex = ColorUtility.ToHtmlStringRGBA(
UnityStyles.Colors.Diff.AssetDiff.SearchHighlightBackground);
return $"<mark=#{bgHex}>";
}
const string CLOSE_TAG = "</mark>";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7c604fb7bc9da45fca4bb28b110301ef
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,15 @@
using System;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common
{
internal static class SearchMatcher
{
internal static bool Contains(string text, string search)
{
if (string.IsNullOrEmpty(text))
return false;
return text.IndexOf(
search, StringComparison.OrdinalIgnoreCase) >= 0;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 80c6d1e65404944acb1fa3405e5b9a34
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4230d3b9af6f940719414ab4bd67a08e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,134 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.UnityObject
{
// Sorts top-level items by their natural scene/prefab hierarchy order
// (DFS over scene roots and their children). Without this pass, items
// come out in the unspecified order LoadSerializedFileAndForget returns
// objects in, not the order the user sees in the Unity Hierarchy panel.
// Items whose object is not part of the hierarchy (settings, etc.) land
// at the end, preserving their relative input order.
internal static class HierarchyOrderSorting
{
internal static void SortByHierarchyOrder<T>(
List<T> items,
Func<T, UnityEngine.Object> objectSelector,
params UnityEngine.Object[][] objectArrays)
{
if (items.Count <= 1)
return;
Dictionary<long, int> orderByFileId = BuildHierarchyOrder(objectArrays);
int trailingOrder = orderByFileId.Count;
int n = items.Count;
int[] sortKeys = new int[n];
int[] indices = new int[n];
for (int i = 0; i < n; i++)
{
sortKeys[i] = ResolveSortKey(
objectSelector(items[i]), orderByFileId, trailingOrder);
indices[i] = i;
}
System.Array.Sort(indices, (a, b) =>
{
int cmp = sortKeys[a].CompareTo(sortKeys[b]);
if (cmp != 0)
return cmp;
return a.CompareTo(b);
});
T[] reordered = new T[n];
for (int i = 0; i < n; i++)
reordered[i] = items[indices[i]];
items.Clear();
items.AddRange(reordered);
}
static int ResolveSortKey(
UnityEngine.Object obj,
Dictionary<long, int> orderByFileId,
int trailingOrder)
{
if (obj == null)
return trailingOrder;
long fileId = obj.GetLocalFileId();
if (fileId == 0)
return trailingOrder;
return orderByFileId.TryGetValue(fileId, out int order)
? order
: trailingOrder;
}
static Dictionary<long, int> BuildHierarchyOrder(
UnityEngine.Object[][] objectArrays)
{
Dictionary<long, int> result = new Dictionary<long, int>();
int counter = 0;
foreach (UnityEngine.Object[] objects in objectArrays)
{
foreach (GameObject root in CollectRootGameObjects(objects))
VisitGameObjectDfs(root, result, ref counter);
}
return result;
}
static void VisitGameObjectDfs(
GameObject go,
Dictionary<long, int> result,
ref int counter)
{
if (go == null)
return;
long fileId = go.GetLocalFileId();
if (fileId != 0 && !result.ContainsKey(fileId))
result[fileId] = counter++;
Transform transform = go.transform;
if (transform == null)
return;
int childCount = transform.childCount;
for (int i = 0; i < childCount; i++)
{
Transform child = transform.GetChild(i);
if (child != null)
VisitGameObjectDfs(child.gameObject, result, ref counter);
}
}
static List<GameObject> CollectRootGameObjects(UnityEngine.Object[] objects)
{
UnityEngine.Object sceneRoots = SceneRootsReader.Find(objects);
if (sceneRoots != null)
return SceneRootsReader.ReadRootGameObjects(sceneRoots);
// Prefab (no SceneRoots) — fall back to Transforms with no parent.
List<GameObject> roots = new List<GameObject>();
foreach (UnityEngine.Object obj in objects)
{
if (!(obj is Transform t))
continue;
if (t.parent != null)
continue;
if (t.gameObject == null)
continue;
roots.Add(t.gameObject);
}
return roots;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7e76dfb34c2145fbb3b128aa04febf80
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,59 @@
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Common.UnityObject
{
// SceneRoots is an internal Unity type without a public managed wrapper,
// so we identify it structurally by the presence of an `m_Roots` array
// property of object references. Prefabs have no SceneRoots.
internal static class SceneRootsReader
{
internal static UnityEngine.Object Find(UnityEngine.Object[] objects)
{
foreach (UnityEngine.Object obj in objects)
{
if (obj == null)
continue;
if (obj is GameObject || obj is Component)
continue;
using (SerializedObject so = new SerializedObject(obj))
{
SerializedProperty roots = so.FindProperty("m_Roots");
if (roots != null && roots.isArray)
return obj;
}
}
return null;
}
internal static List<GameObject> ReadRootGameObjects(
UnityEngine.Object sceneRootsObj)
{
List<GameObject> result = new List<GameObject>();
using (SerializedObject so = new SerializedObject(sceneRootsObj))
{
SerializedProperty roots = so.FindProperty("m_Roots");
if (roots == null || !roots.isArray)
return result;
for (int i = 0; i < roots.arraySize; i++)
{
SerializedProperty element = roots.GetArrayElementAtIndex(i);
if (element.objectReferenceValue is Transform t
&& t.gameObject != null)
{
result.Add(t.gameObject);
}
}
}
return result;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 36c9ccdf0df04c64a5a41ffbb2a66e8e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 324df26159c3d422783de457f2915b96
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,804 @@
using System.Collections.Generic;
using Codice.Client.Common.Threading;
using Codice.CM.Client.Differences;
using Codice.CM.Client.Differences.Graphic;
using MergetoolGui;
using PlasticGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Meta;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.UnityObject;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Filtering;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Search;
using Unity.PlasticSCM.Editor.Diff.Purged;
using Unity.PlasticSCM.Editor.Diff.Text;
using Unity.PlasticSCM.Editor.UI;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using XDiffGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal class AssetContentControl : VisualElement, IBigFilePanelListener
{
internal AssetContentControl(
IBigFileDownloader bigFileDownloader,
IBigFileChecker bigFileChecker)
{
mBigFileDownloader = bigFileDownloader;
mBigFileChecker = bigFileChecker;
CreateGUI();
RegisterCallback<AttachToPanelEvent>(_ =>
{
AssetReloadNotifier.AssetsChanged += OnAssetsChanged;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
});
RegisterCallback<DetachFromPanelEvent>(_ =>
{
AssetReloadNotifier.AssetsChanged -= OnAssetsChanged;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
});
}
internal void ShowData(DiffViewerData diffData)
{
if (diffData == null)
return;
mDiffViewerData = diffData;
DisplayCurrentData(isReload: false);
}
internal void Dispose()
{
mToolbarPanel.Dispose();
if (mBigFileMessagePanel != null)
mBigFileMessagePanel.Dispose();
if (mPurgedRevisionControl != null)
mPurgedRevisionControl.Dispose();
}
void IBigFilePanelListener.OnCalculateDifferencesButtonClick()
{
mBigFileMessagePanel.Disable();
IThreadWaiter waiter = ThreadWaiter.GetWaiter(10);
waiter.Execute(
/*threadOperationDelegate*/ delegate
{
mBigFileDownloader.DownloadFiles(mDiffViewerData, null);
},
/*afterOperationDelegate*/ delegate
{
mBigFileMessagePanel.Enable();
if (waiter.Exception != null)
{
MergetoolExceptionsHandler.DisplayException(
waiter.Exception);
return;
}
DisplayCurrentData(isReload: false);
});
}
void DisplayCurrentData(bool isReload)
{
DiffViewerData diffData = mDiffViewerData;
ReplaceMainView(mNormalContentPanel);
EntryData entryData = diffData.Left;
mContributorLabel.text = PlasticLocalization.Name.Content.GetString(
entryData.SymbolicName);
if (BigFileDiffCalculator.IsBigFileDiff(diffData, mBigFileDownloader, mBigFileChecker))
{
ShowBigFileMessage();
return;
}
if (diffData.Left?.IsPurged == true || diffData.Right?.IsPurged == true)
{
ShowPurgedRevision(diffData);
return;
}
ShowAssetContent(entryData.File, isReload);
}
void OnAssetsChanged(HashSet<string> changedFullPaths)
{
if (mDiffViewerData == null)
return;
if (!AssetReloadNotifier.IsWatchedPath(
mDiffViewerData.Left?.File, changedFullPaths)
&& !AssetReloadNotifier.IsWatchedPath(
mDiffViewerData.Right?.File, changedFullPaths))
return;
DisplayCurrentData(isReload: true);
}
// Entering or exiting play mode causes Unity to drop the objects we
// loaded into mObjectContents via LoadSerializedFileAndForget.
// Without a fresh load the next re-bind would render every header
// as a fallback ("Unknown" / generic file icon), since the
// underlying native objects are gone even though the C# refs remain.
void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (mDiffViewerData == null)
return;
if (state != PlayModeStateChange.EnteredEditMode
&& state != PlayModeStateChange.EnteredPlayMode)
return;
DisplayCurrentData(isReload: true);
}
void ShowAssetContent(string file, bool isReload)
{
mContributorLabel.style.borderBottomWidth = 0;
ReplaceView(mListView);
mVisibleRows.Clear();
ExpansionSnapshot previousCache = isReload
? SnapshotExpansionState()
: null;
bool isMetaContent = MetaPath.IsMetaPath(file);
mObjectContents = isMetaContent
? MetaFileContents.BuildContentData(file)
: UnityObjectContents.BuildContentData(file);
ApplyExpansionState(previousCache);
UpdateAvailableFilters(isMetaContent);
RebuildVisibleRows();
}
void UpdateAvailableFilters(bool isMetaContent)
{
if (isMetaContent)
{
mToolbarPanel.UpdateAvailableFilters(null, null, show: false);
return;
}
mToolbarPanel.UpdateAvailableFilters(
ObjectContentOptions.ExtractGameObjects(mObjectContents, GetGameObjectIcon),
ObjectContentOptions.ExtractTypes(mObjectContents, GetObjectIcon),
show: true);
}
static UnityEngine.Texture GetGameObjectIcon(ObjectContent content)
{
GameObject go = content.GetGameObject();
if (go != null)
return EditorGUIUtility.ObjectContent(go, typeof(GameObject)).image;
return GetObjectIcon(content);
}
static UnityEngine.Texture GetObjectIcon(ObjectContent content)
{
UnityEngine.Object obj = content.Object;
if (obj == null)
return null;
return EditorGUIUtility.ObjectContent(obj, obj.GetType()).image;
}
ExpansionSnapshot SnapshotExpansionState()
{
ExpansionSnapshot snapshot = new ExpansionSnapshot();
foreach (ObjectContent obj in mObjectContents)
{
snapshot.Objects[BuildObjectKey(obj)] =
mExpandedObjects.Contains(obj.GetObjectId());
if (obj.ComponentContents == null)
continue;
for (int i = 0; i < obj.ComponentContents.Count; i++)
{
ObjectContent comp = obj.ComponentContents[i];
snapshot.Objects[BuildComponentKey(obj, comp, i)] =
mExpandedObjects.Contains(comp.GetObjectId());
}
}
foreach (string fullKey in mCollapsedGroups)
snapshot.CollapsedGroups.Add(fullKey);
return snapshot;
}
void ApplyExpansionState(ExpansionSnapshot previousCache)
{
mExpandedObjects.Clear();
mCollapsedGroups.Clear();
foreach (ObjectContent obj in mObjectContents)
{
if (ShouldExpand(previousCache?.Objects, BuildObjectKey(obj), DefaultExpand(obj)))
mExpandedObjects.Add(obj.GetObjectId());
if (obj.ComponentContents == null)
continue;
for (int i = 0; i < obj.ComponentContents.Count; i++)
{
ObjectContent comp = obj.ComponentContents[i];
if (ShouldExpand(previousCache?.Objects, BuildComponentKey(obj, comp, i), DefaultExpand(comp)))
mExpandedObjects.Add(comp.GetObjectId());
}
}
if (previousCache == null)
return;
foreach (string fullKey in previousCache.CollapsedGroups)
mCollapsedGroups.Add(fullKey);
}
static bool ShouldExpand(
Dictionary<string, bool> previousCache, string key, bool defaultExpand)
{
if (previousCache != null && previousCache.TryGetValue(key, out bool wasExpanded))
return wasExpanded;
return defaultExpand;
}
static bool DefaultExpand(ObjectContent obj)
{
return true;
}
static string BuildObjectKey(ObjectContent obj)
{
return "o:" + obj.GetDisplayName();
}
static string BuildComponentKey(
ObjectContent parent, ObjectContent comp, int index)
{
return "c:" + parent.GetDisplayName() + "/" + index + ":" + comp.GetDisplayName();
}
static string BuildGroupFullKey(ObjectContent owner, string groupKey)
{
return owner.GetObjectId() + ":" + groupKey;
}
void ShowBigFileMessage()
{
if (mBigFileMessagePanel == null)
mBigFileMessagePanel = new BigFileMessagePanel(this, false);
mBigFileMessagePanel.UpdateDisplayData(
BigFileDisplayData.Build(
mDiffViewerData, mBigFileDownloader));
mContributorLabel.style.borderBottomWidth = 1;
ReplaceView(mBigFileMessagePanel);
}
void ShowPurgedRevision(DiffViewerData data)
{
if (mPurgedRevisionControl == null)
mPurgedRevisionControl = new PurgedRevisionControl();
mPurgedRevisionControl.ShowData(data);
ReplaceMainView(mPurgedRevisionControl);
}
void ReplaceMainView(VisualElement panel)
{
if (hierarchy.childCount == 1 && hierarchy[0] == panel)
return;
Clear();
Add(panel);
}
void ReplaceView(VisualElement view)
{
if (mCurrentView == view)
return;
if (mCurrentView != null)
mContainerPanel.Remove(mCurrentView);
mContainerPanel.Add(view);
mCurrentView = view;
}
void RebuildVisibleRows()
{
mVisibleRows.Clear();
mKnownGroups.Clear();
mSearchIndex = PropertyContentSearchIndex.Build(mObjectContents, mSearchFilter);
CollectAllGroupKeys();
foreach (ObjectContent objContent in mObjectContents)
{
if (!PassesGameObjectFilter(objContent))
continue;
if (mSearchIndex.IsActive)
AddObjectRowsWithSearch(objContent);
else
AddObjectRows(objContent);
}
mListView.RefreshItems();
}
bool PassesGameObjectFilter(ObjectContent content)
{
return ObjectContentFilters.PassesGameObjectFilter(content, mSelectedGameObjects);
}
bool PassesTypeFilter(ObjectContent content)
{
return ObjectContentFilters.PassesTypeFilter(content, mSelectedTypes);
}
void AddObjectRows(ObjectContent objContent)
{
bool selfTypePasses = PassesTypeFilter(objContent);
bool anyChildPasses = HasVisibleChildComponent(objContent);
if (!selfTypePasses && !anyChildPasses)
return;
mVisibleRows.Add(new ContentRow(
ContentRowKind.ObjectHeader, objContent, null));
if (!mExpandedObjects.Contains(objContent.GetObjectId()))
return;
if (selfTypePasses)
AddPropertyRows(objContent, indentLevel: 0);
AddComponentRows(objContent);
}
bool HasVisibleChildComponent(ObjectContent parent)
{
if (parent.ComponentContents == null)
return false;
foreach (ObjectContent comp in parent.ComponentContents)
{
if (PassesTypeFilter(comp))
return true;
}
return false;
}
void AddComponentRows(ObjectContent parent)
{
if (parent.ComponentContents == null)
return;
foreach (ObjectContent compContent in parent.ComponentContents)
{
if (!PassesTypeFilter(compContent))
continue;
mVisibleRows.Add(new ContentRow(
ContentRowKind.ComponentHeader, compContent, null, indentLevel: 1));
if (!mExpandedObjects.Contains(compContent.GetObjectId()))
continue;
AddPropertyRows(compContent, indentLevel: 1);
}
}
void AddPropertyRows(ObjectContent objContent, int indentLevel)
{
PropertyTreeNode root = objContent.PropertyTree;
if (root == null)
return;
mWalker.Walk(
root.Children,
indentLevel,
mSearchIndex.IsNodeVisible,
node => BuildGroupFullKey(objContent, node.Path),
IsGroupExpanded,
(node, indent) => AddPropertyRow(
objContent, ToPropertyContent(node), indent),
(node, indent, fullKey) => AddContainerHeaderRow(
objContent, node, fullKey, indent));
}
// Containers with zero children render as a regular property row with
// the empty literal in the value column — that matches how Unity's
// Inspector shows empty arrays and keeps the visual hierarchy honest
// (a bold expandable header without children would lie about being
// expandable).
void AddContainerHeaderRow(
ObjectContent objContent,
PropertyTreeNode node,
string fullKey,
int indent)
{
if (node.Children.Count == 0)
{
AddPropertyRow(
objContent, ToEmptyContainerProperty(node), indent);
return;
}
mVisibleRows.Add(new ContentRow(
ContentRowKind.ContainerHeader, objContent, fullKey,
node.DisplayName, indent));
}
static PropertyContent ToEmptyContainerProperty(PropertyTreeNode node)
{
return new PropertyContent
{
Path = node.Path,
DisplayName = node.DisplayName,
TypeTag = node.TypeTag,
Value = node.Kind == NodeKind.Array ? "[]" : "{}",
Tag = null
};
}
void CollectAllGroupKeys()
{
foreach (ObjectContent objContent in mObjectContents)
{
CollectGroupKeysForOwner(objContent);
if (objContent.ComponentContents == null)
continue;
foreach (ObjectContent comp in objContent.ComponentContents)
CollectGroupKeysForOwner(comp);
}
}
void CollectGroupKeysForOwner(ObjectContent owner)
{
if (owner.PropertyTree == null)
return;
mWalker.CollectGroupKeys(
owner.PropertyTree.Children,
node => BuildGroupFullKey(owner, node.Path),
key => mKnownGroups.Add(key));
}
bool IsGroupExpanded(string fullKey)
{
if (mSearchIndex.IsActive)
return true;
return !mCollapsedGroups.Contains(fullKey);
}
static PropertyContent ToPropertyContent(PropertyTreeNode node)
{
return new PropertyContent
{
Path = node.Path,
DisplayName = node.DisplayName,
TypeTag = node.TypeTag,
Value = node.Value,
Tag = node.Tag
};
}
void AddPropertyRow(
ObjectContent owner, PropertyContent prop, int indentLevel)
{
mVisibleRows.Add(new ContentRow(
ContentRowKind.Property, owner, prop, indentLevel));
if (PropertyRow.IsTallProperty(prop.Tag))
mVisibleRows.Add(new ContentRow(
ContentRowKind.Property, owner, prop,
indentLevel, isSpacer: true));
}
void AddObjectRowsWithSearch(ObjectContent objContent)
{
bool selfTypePasses = PassesTypeFilter(objContent);
bool nameMatches = SearchMatcher.Contains(objContent.GetDisplayName(), mSearchFilter);
bool hasOwnPropertyMatch = selfTypePasses && SubtreeHasSearchMatch(objContent);
bool hasComponentMatch = HasComponentSearchMatch(objContent);
bool selfWouldShow = selfTypePasses
&& (hasOwnPropertyMatch || nameMatches);
bool nameMatchSurfacesChildren =
nameMatches && HasVisibleChildComponent(objContent);
if (!selfWouldShow && !hasComponentMatch && !nameMatchSurfacesChildren)
return;
mVisibleRows.Add(new ContentRow(
ContentRowKind.ObjectHeader, objContent, null));
if (hasOwnPropertyMatch
|| (selfTypePasses && nameMatches
&& mExpandedObjects.Contains(objContent.GetObjectId())))
{
AddPropertyRows(objContent, indentLevel: 0);
}
AddComponentRowsWithSearch(objContent, nameMatches);
}
void AddComponentRowsWithSearch(
ObjectContent parent, bool parentNameMatches)
{
if (parent.ComponentContents == null)
return;
foreach (ObjectContent compContent in parent.ComponentContents)
{
if (!PassesTypeFilter(compContent))
continue;
bool compNameMatches = SearchMatcher.Contains(
compContent.GetDisplayName(), mSearchFilter);
bool compHasPropertyMatch = SubtreeHasSearchMatch(compContent);
if (!parentNameMatches && !compNameMatches && !compHasPropertyMatch)
continue;
mVisibleRows.Add(new ContentRow(
ContentRowKind.ComponentHeader, compContent, null, indentLevel: 1));
if (compHasPropertyMatch
|| mExpandedObjects.Contains(compContent.GetObjectId()))
{
AddPropertyRows(compContent, indentLevel: 1);
}
}
}
bool SubtreeHasSearchMatch(ObjectContent objContent)
{
return mSearchIndex.SubtreeHasMatch(objContent);
}
bool HasComponentSearchMatch(ObjectContent objContent)
{
if (objContent.ComponentContents == null)
return false;
foreach (ObjectContent compContent in objContent.ComponentContents)
{
if (!PassesTypeFilter(compContent))
continue;
if (SearchMatcher.Contains(compContent.GetDisplayName(), mSearchFilter))
return true;
if (SubtreeHasSearchMatch(compContent))
return true;
}
return false;
}
void OnBindRow(VisualElement element, int index)
{
if (index < 0 || index >= mVisibleRows.Count)
return;
ContentRow row = mVisibleRows[index];
ContentRowElement rowElement = (ContentRowElement)element;
if (row.IsSpacer)
{
rowElement.BindSpacer();
return;
}
switch (row.Kind)
{
case ContentRowKind.ObjectHeader:
case ContentRowKind.ComponentHeader:
bool isExpanded = mExpandedObjects.Contains(
row.ObjectContent.GetObjectId());
rowElement.BindHeader(
row.ObjectContent,
isExpanded,
mSearchFilter,
row.IndentLevel);
return;
case ContentRowKind.ContainerHeader:
rowElement.BindGroupHeader(
row.GroupDisplayName,
row.GroupKey,
IsGroupExpanded(row.GroupKey),
mSearchFilter,
row.IndentLevel);
return;
default:
rowElement.BindProperty(
row.PropertyContent,
mSearchFilter,
row.IndentLevel);
return;
}
}
void OnObjectToggled(ObjectContent objContent)
{
int id = objContent.GetObjectId();
if (!mExpandedObjects.Remove(id))
mExpandedObjects.Add(id);
RebuildVisibleRows();
}
void OnGroupToggled(string groupFullKey)
{
if (!mCollapsedGroups.Remove(groupFullKey))
mCollapsedGroups.Add(groupFullKey);
RebuildVisibleRows();
}
void SetSearchFilter(string searchFilter)
{
mSearchFilter = searchFilter ?? string.Empty;
RebuildVisibleRows();
}
void SetGameObjectFilter(HashSet<string> selected)
{
mSelectedGameObjects = selected;
RebuildVisibleRows();
}
void SetTypeFilter(HashSet<string> selected)
{
mSelectedTypes = selected;
RebuildVisibleRows();
}
void ExpandAll()
{
foreach (ObjectContent objContent in mObjectContents)
{
mExpandedObjects.Add(objContent.GetObjectId());
if (objContent.ComponentContents == null)
continue;
foreach (ObjectContent compContent in objContent.ComponentContents)
mExpandedObjects.Add(compContent.GetObjectId());
}
mCollapsedGroups.Clear();
RebuildVisibleRows();
}
void CollapseAll()
{
mExpandedObjects.Clear();
foreach (string fullKey in mKnownGroups)
mCollapsedGroups.Add(fullKey);
RebuildVisibleRows();
}
void CreateGUI()
{
style.flexGrow = 1;
mToolbarPanel = new ContentToolbarPanel(
SetSearchFilter, ExpandAll, CollapseAll,
SetGameObjectFilter, SetTypeFilter);
mContributorLabel = new Label();
mContributorLabel.style.paddingLeft = 6;
mContributorLabel.style.paddingTop = 4;
mContributorLabel.style.paddingBottom = 4;
mContributorLabel.style.borderBottomColor = UnityStyles.Colors.BarBorder;
mListView = CreateListView();
mContainerPanel = new VisualElement();
mContainerPanel.style.flexGrow = 1;
mNormalContentPanel = new VisualElement();
mNormalContentPanel.style.flexGrow = 1;
mNormalContentPanel.Add(mToolbarPanel);
mNormalContentPanel.Add(mContributorLabel);
mNormalContentPanel.Add(mContainerPanel);
Add(mNormalContentPanel);
ReplaceView(mListView);
}
ListView CreateListView()
{
ListView result = new ListView();
result.style.flexGrow = 1;
result.fixedItemHeight = ContentRowElement.ROW_HEIGHT;
result.makeItem = () => new ContentRowElement(OnObjectToggled, OnGroupToggled);
result.bindItem = OnBindRow;
result.selectionType = SelectionType.None;
result.itemsSource = mVisibleRows;
return result;
}
ContentToolbarPanel mToolbarPanel;
Label mContributorLabel;
ListView mListView;
VisualElement mNormalContentPanel;
VisualElement mContainerPanel;
VisualElement mCurrentView;
BigFileMessagePanel mBigFileMessagePanel;
PurgedRevisionControl mPurgedRevisionControl;
List<ObjectContent> mObjectContents = new List<ObjectContent>();
readonly HashSet<int> mExpandedObjects = new HashSet<int>();
readonly HashSet<string> mCollapsedGroups = new HashSet<string>();
readonly HashSet<string> mKnownGroups = new HashSet<string>();
readonly List<ContentRow> mVisibleRows = new List<ContentRow>();
PropertyContentSearchIndex mSearchIndex = PropertyContentSearchIndex.Build(
new List<ObjectContent>(), null);
string mSearchFilter = string.Empty;
HashSet<string> mSelectedGameObjects;
HashSet<string> mSelectedTypes;
DiffViewerData mDiffViewerData;
readonly IBigFileDownloader mBigFileDownloader;
readonly IBigFileChecker mBigFileChecker;
static readonly PropertyTreeWalker<PropertyTreeNode> mWalker =
new PropertyTreeWalker<PropertyTreeNode>(
node => node.Kind,
node => node.Children);
class ExpansionSnapshot
{
internal readonly Dictionary<string, bool> Objects =
new Dictionary<string, bool>();
internal readonly HashSet<string> CollapsedGroups =
new HashSet<string>();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 57a63f5d522d4da98a48cb71348c223e
timeCreated: 1772187002
@@ -0,0 +1,73 @@
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal class ContentGroupHeaderRow : VisualElement
{
internal ContentGroupHeaderRow()
{
CreateGUI();
}
internal void Bind(
string label, bool isExpanded, string searchFilter, int indentLevel)
{
float padding = PropertyRow.BASE_PADDING_LEFT
+ indentLevel * PropertyRow.INDENT_PX;
mPanel.style.paddingLeft = padding;
mPanel.style.backgroundColor =
UnityStyles.Colors.Diff.AssetDiff.PropertyRowBackground;
mArrow.text = isExpanded
? HeaderRow.ARROW_DOWN : HeaderRow.ARROW_RIGHT;
bool hasSearch = !string.IsNullOrEmpty(searchFilter);
mLabel.enableRichText = hasSearch;
mLabel.text = hasSearch
? SearchHighlight.Apply(label ?? string.Empty, searchFilter)
: label ?? string.Empty;
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mPanel = new VisualElement();
mPanel.style.flexGrow = 1;
mPanel.style.flexDirection = FlexDirection.Row;
mPanel.style.alignItems = Align.Center;
mPanel.style.paddingLeft = PropertyRow.BASE_PADDING_LEFT;
mPanel.style.paddingRight = 4;
mPanel.style.paddingTop = 1;
mPanel.style.paddingBottom = 1;
mArrow = new Label(HeaderRow.ARROW_RIGHT);
mArrow.style.width = 16;
mArrow.style.fontSize = 10;
mArrow.style.unityTextAlign = TextAnchor.MiddleCenter;
mArrow.style.color = UnityStyles.Colors.Diff.AssetDiff.ExpanderColor;
mPanel.Add(mArrow);
mLabel = new Label();
mLabel.style.fontSize = 12;
mLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
mLabel.style.flexShrink = 1;
mLabel.style.overflow = Overflow.Hidden;
mLabel.style.textOverflow = TextOverflow.Ellipsis;
mLabel.style.color = UnityStyles.Colors.DefaultText;
mPanel.Add(mLabel);
Add(mPanel);
}
VisualElement mPanel;
Label mArrow;
Label mLabel;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: db010bdfb5124461bf82c83e532a3f26
timeCreated: 1747310600
@@ -0,0 +1,74 @@
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal class ContentHeaderRow : VisualElement
{
internal ContentHeaderRow()
{
CreateGUI();
}
internal void Bind(
ObjectContent objContent,
bool isExpanded,
string searchFilter,
int indentLevel)
{
mbIsHovered = false;
float padding = HeaderRow.BASE_PADDING_LEFT
+ indentLevel * HeaderRow.INDENT_PX;
HeaderRow.ApplyContentBorder(
mContent, hasContent: true, padding, isExpanded,
suppressBottomBorder: objContent.IsGameObject());
string arrowText = isExpanded
? HeaderRow.ARROW_DOWN : HeaderRow.ARROW_RIGHT;
UnityEngine.Texture icon = ObjectIconResolver.GetIcon(objContent);
HeaderRow.ConfigurePanel(
mArrow, mIcon, mLabel, mAnnotation, mPanel,
hasContent: true, arrowText,
HeaderRow.GetBackgroundColor(hasContent: true, mbIsHovered), icon,
objContent.GetDisplayName(),
searchFilter);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mPanel = HeaderRow.BuildPanel(
out mContent, out mArrow, out mIcon, out mLabel, out mAnnotation);
mPanel.RegisterCallback<MouseEnterEvent>(OnPanelMouseEnter);
mPanel.RegisterCallback<MouseLeaveEvent>(OnPanelMouseLeave);
Add(mPanel);
}
void OnPanelMouseEnter(MouseEnterEvent evt)
{
HeaderRow.SetHovered(
ref mbIsHovered, hasContent: true, mPanel, bIsHovered: true);
}
void OnPanelMouseLeave(MouseLeaveEvent evt)
{
HeaderRow.SetHovered(
ref mbIsHovered, hasContent: true, mPanel, bIsHovered: false);
}
VisualElement mPanel;
VisualElement mContent;
Label mArrow;
Image mIcon;
Label mLabel;
Label mAnnotation;
bool mbIsHovered;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fe0c3fddc9d7444cad1202bea40ff63f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,58 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Property;
using Unity.PlasticSCM.Editor.UI;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal class ContentPropertyRow : VisualElement
{
internal ContentPropertyRow()
{
CreateGUI();
}
internal void Bind(
PropertyContent prop,
string searchFilter,
int indentLevel)
{
float padding = PropertyRow.BASE_PADDING_LEFT
+ indentLevel * PropertyRow.INDENT_PX;
mPanel.style.paddingLeft = padding;
mPanel.style.backgroundColor =
UnityStyles.Colors.Diff.AssetDiff.PropertyRowBackground;
string label = prop.DisplayName ?? prop.Path;
bool hasSearch = !string.IsNullOrEmpty(searchFilter);
string displayLabel = hasSearch
? SearchHighlight.Apply(label, searchFilter)
: label;
PropertyRow.ConfigureNameLabel(
mLabel, hasContent: true, hasSearch, displayLabel, prop.Path);
mValue.style.display = DisplayStyle.Flex;
mValue.SetData(prop.Tag, prop.Value, hasContent: true, counterpartTag: null);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mPanel = PropertyRow.BuildPanel(out mLabel);
mValue = new DiffValueDisplay();
mPanel.Add(mValue);
Add(mPanel);
}
VisualElement mPanel;
Label mLabel;
DiffValueDisplay mValue;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b7a6e00fe1c54225a6eaeb9fb907f498
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,55 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal enum ContentRowKind : byte
{
ObjectHeader,
ComponentHeader,
ContainerHeader,
Property
}
internal readonly struct ContentRow
{
internal readonly ContentRowKind Kind;
internal readonly ObjectContent ObjectContent;
internal readonly PropertyContent PropertyContent;
internal readonly int IndentLevel;
internal readonly bool IsSpacer;
internal readonly string GroupKey;
internal readonly string GroupDisplayName;
internal ContentRow(
ContentRowKind kind,
ObjectContent objectContent,
PropertyContent propertyContent,
int indentLevel = 0,
bool isSpacer = false)
{
Kind = kind;
ObjectContent = objectContent;
PropertyContent = propertyContent;
IndentLevel = indentLevel;
IsSpacer = isSpacer;
GroupKey = null;
GroupDisplayName = null;
}
internal ContentRow(
ContentRowKind kind,
ObjectContent objectContent,
string groupKey,
string groupDisplayName,
int indentLevel)
{
Kind = kind;
ObjectContent = objectContent;
PropertyContent = null;
IndentLevel = indentLevel;
IsSpacer = false;
GroupKey = groupKey;
GroupDisplayName = groupDisplayName;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2628fb5d276334c46b602b8fb8e0af3c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,140 @@
using System;
using Unity.PlasticSCM.Editor.Diff.Asset.Content.Property;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal class ContentRowElement : VisualElement
{
internal const float ROW_HEIGHT = 22f;
internal ContentRowElement(
Action<ObjectContent> toggleObjectCallback,
Action<string> toggleGroupCallback)
{
mToggleObjectCallback = toggleObjectCallback;
mToggleGroupCallback = toggleGroupCallback;
CreateGUI();
RegisterCallback<ClickEvent>(OnClicked);
}
internal void BindHeader(
ObjectContent objContent,
bool isExpanded,
string searchFilter,
int indentLevel = 0)
{
mBoundObjectContent = objContent;
mBoundGroupKey = null;
mBoundKind = BoundKind.ObjectHeader;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.Flex;
mPropertyRow.style.display = DisplayStyle.None;
mGroupHeaderRow.style.display = DisplayStyle.None;
mHeaderRow.Bind(objContent, isExpanded, searchFilter, indentLevel);
}
internal void BindGroupHeader(
string label,
string groupKey,
bool isExpanded,
string searchFilter,
int indentLevel)
{
mBoundObjectContent = null;
mBoundGroupKey = groupKey;
mBoundKind = BoundKind.GroupHeader;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.None;
mGroupHeaderRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.Bind(label, isExpanded, searchFilter, indentLevel);
}
internal void BindProperty(
PropertyContent prop,
string searchFilter,
int indentLevel = 0)
{
mBoundObjectContent = null;
mBoundGroupKey = null;
mBoundKind = BoundKind.PropertyRow;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.Bind(prop, searchFilter, indentLevel);
}
internal void BindSpacer()
{
mBoundObjectContent = null;
mBoundGroupKey = null;
mBoundKind = BoundKind.PropertyRow;
pickingMode = PickingMode.Ignore;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.None;
mGroupHeaderRow.style.display = DisplayStyle.None;
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Column;
style.minHeight = ROW_HEIGHT;
style.overflow = Overflow.Visible;
mHeaderRow = new ContentHeaderRow();
Add(mHeaderRow);
mGroupHeaderRow = new ContentGroupHeaderRow();
Add(mGroupHeaderRow);
mPropertyRow = new ContentPropertyRow();
Add(mPropertyRow);
}
void OnClicked(ClickEvent evt)
{
switch (mBoundKind)
{
case BoundKind.ObjectHeader:
if (mBoundObjectContent != null)
mToggleObjectCallback?.Invoke(mBoundObjectContent);
return;
case BoundKind.GroupHeader:
if (mBoundGroupKey != null)
mToggleGroupCallback?.Invoke(mBoundGroupKey);
return;
}
}
readonly Action<ObjectContent> mToggleObjectCallback;
readonly Action<string> mToggleGroupCallback;
ContentHeaderRow mHeaderRow;
ContentGroupHeaderRow mGroupHeaderRow;
ContentPropertyRow mPropertyRow;
ObjectContent mBoundObjectContent;
string mBoundGroupKey;
BoundKind mBoundKind;
enum BoundKind : byte
{
None,
ObjectHeader,
GroupHeader,
PropertyRow
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0e3cb890d25a9473296427cdde6f83b7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,129 @@
using System;
using System.Collections.Generic;
using PlasticGui;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.UIElements;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal class ContentToolbarPanel : VisualElement
{
internal ContentToolbarPanel(
Action<string> filterChanged,
Action expandAll,
Action collapseAll,
Action<HashSet<string>> setGameObjectFilter,
Action<HashSet<string>> setTypeFilter)
{
mFilterChanged = filterChanged;
mExpandAll = expandAll;
mCollapseAll = collapseAll;
mSetGameObjectFilter = setGameObjectFilter;
mSetTypeFilter = setTypeFilter;
CreateGUI();
mDelayedFilterAction = new DelayedActionBySecondsRunner(
DelayedSearchChanged, UnityConstants.SEARCH_DELAYED_INPUT_ACTION_INTERVAL);
}
internal void Dispose()
{
mSearchField.UnregisterValueChangedCallback(OnSearchFieldValueChanged);
mGameObjectDropdown.SelectionChanged -= OnGameObjectSelectionChanged;
mTypeDropdown.SelectionChanged -= OnTypeSelectionChanged;
}
internal void UpdateAvailableFilters(
IList<MultiSelectDropdownItem> gameObjects,
IList<MultiSelectDropdownItem> types,
bool show)
{
DisplayStyle display = show ? DisplayStyle.Flex : DisplayStyle.None;
mGameObjectDropdown.style.display = display;
mTypeDropdown.style.display = display;
if (!show)
return;
mGameObjectDropdown.SetItems(gameObjects);
mTypeDropdown.SetItems(types);
}
void DelayedSearchChanged()
{
mFilterChanged(mSearchField.value);
}
void CreateGUI()
{
UnityEditor.UIElements.Toolbar toolbar = ControlBuilder.Toolbar.Create();
mGameObjectDropdown = ControlBuilder.Toolbar.CreateMultiSelectDropdownLeft(
PlasticLocalization.Name.DiffGameObjectFilterLabel.GetString());
mGameObjectDropdown.SelectionChanged += OnGameObjectSelectionChanged;
mGameObjectDropdown.style.display = DisplayStyle.None;
mTypeDropdown = ControlBuilder.Toolbar.CreateMultiSelectDropdown(
PlasticLocalization.Name.DiffTypeFilterLabel.GetString());
mTypeDropdown.SelectionChanged += OnTypeSelectionChanged;
mTypeDropdown.style.display = DisplayStyle.None;
mSearchField = ControlBuilder.Toolbar.CreateSearchField();
mSearchField.RegisterValueChangedCallback(OnSearchFieldValueChanged);
toolbar.Add(mGameObjectDropdown);
toolbar.Add(mTypeDropdown);
VisualElement spacer = new VisualElement();
spacer.style.flexGrow = 1;
toolbar.Add(spacer);
mExpandAllButton = ControlBuilder.Toolbar.CreateButtonLeft(
PlasticLocalization.Name.DiffExpandAllButton.GetString(), mExpandAll);
toolbar.Add(mExpandAllButton);
mCollapseAllButton = ControlBuilder.Toolbar.CreateButton(
PlasticLocalization.Name.DiffCollapseAllButton.GetString(), mCollapseAll);
toolbar.Add(mCollapseAllButton);
toolbar.Add(mSearchField);
Add(toolbar);
}
void OnSearchFieldValueChanged(ChangeEvent<string> evt)
{
mDelayedFilterAction.Run();
}
void OnGameObjectSelectionChanged()
{
mSetGameObjectFilter(mGameObjectDropdown.Selected);
}
void OnTypeSelectionChanged()
{
mSetTypeFilter(mTypeDropdown.Selected);
}
readonly Action<string> mFilterChanged;
readonly Action mExpandAll;
readonly Action mCollapseAll;
readonly Action<HashSet<string>> mSetGameObjectFilter;
readonly Action<HashSet<string>> mSetTypeFilter;
readonly DelayedActionBySecondsRunner mDelayedFilterAction;
ToolbarButton mExpandAllButton;
ToolbarButton mCollapseAllButton;
MultiSelectDropdown mGameObjectDropdown;
MultiSelectDropdown mTypeDropdown;
ToolbarSearchField mSearchField;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e534c3e00f154e72ba2a02fbe533bd1a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e0f244660204c468a8fe30e330135e0d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,27 @@
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content.Filtering
{
internal static class ObjectContentFilters
{
internal static bool PassesGameObjectFilter(
ObjectContent content, HashSet<string> selected)
{
if (selected == null)
return true;
string name = content.GetObjectName();
return name != null && selected.Contains(name);
}
internal static bool PassesTypeFilter(
ObjectContent content, HashSet<string> selected)
{
if (selected == null)
return true;
string typeName = content.GetTypeName();
return typeName != null && selected.Contains(typeName);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5ba5950af72324af4be4d53de594d2b9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.UI.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content.Filtering
{
internal static class ObjectContentOptions
{
internal static List<MultiSelectDropdownItem> ExtractGameObjects(
IList<ObjectContent> objectContents,
Func<ObjectContent, UnityEngine.Texture> iconResolver)
{
List<MultiSelectDropdownItem> result = new List<MultiSelectDropdownItem>();
HashSet<string> seen = new HashSet<string>();
foreach (ObjectContent content in objectContents)
{
string name = content.GetObjectName();
if (string.IsNullOrEmpty(name) || !seen.Add(name))
continue;
result.Add(new MultiSelectDropdownItem(name, iconResolver(content)));
}
return result;
}
internal static List<MultiSelectDropdownItem> ExtractTypes(
IList<ObjectContent> objectContents,
Func<ObjectContent, UnityEngine.Texture> iconResolver)
{
List<MultiSelectDropdownItem> result = new List<MultiSelectDropdownItem>();
HashSet<string> seen = new HashSet<string>();
foreach (ObjectContent content in objectContents)
{
AddTypeIfPresent(content, result, seen, iconResolver);
if (content.ComponentContents == null)
continue;
foreach (ObjectContent comp in content.ComponentContents)
AddTypeIfPresent(comp, result, seen, iconResolver);
}
return result;
}
static void AddTypeIfPresent(
ObjectContent content,
List<MultiSelectDropdownItem> result,
HashSet<string> seen,
Func<ObjectContent, UnityEngine.Texture> iconResolver)
{
string typeName = content.GetTypeName();
if (string.IsNullOrEmpty(typeName) || !seen.Add(typeName))
return;
result.Add(new MultiSelectDropdownItem(typeName, iconResolver(content)));
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4b00ba0e9b00a43229c0589749f0cf25
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0c9e6fa111057499c9ed2c22d2c00f95
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,68 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using Codice.LogWrapper;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Meta;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content.Meta
{
internal static class MetaFileContents
{
internal static List<ObjectContent> BuildContentData(string file)
{
Stopwatch sw = Stopwatch.StartNew();
string metaFileName = Path.GetFileName(file);
PropertyTreeNode tree = MetaPropertyTreeBuilder.Build(
File.ReadAllBytes(file));
PropertyTreeNode filteredTree = MetaTreeHelpers.FilterIgnoredKeys(tree);
if (filteredTree.Children.Count == 0)
return EmptyList;
// Each top-level YAML key becomes its own ObjectContent — analogous
// to a Component in a UnityObject diff. For an Object/Array key
// the section's tree carries the key's children directly (the
// "AudioImporter" wrapper is hoisted into the section header so
// it doesn't duplicate as the first child row).
List<ObjectContent> result = new List<ObjectContent>(
filteredTree.Children.Count);
foreach (PropertyTreeNode section in filteredTree.Children)
{
result.Add(new ObjectContent
{
MetaFileName = metaFileName,
MetaSectionName = section.DisplayName,
PropertyTree = WrapAsSectionRoot(section)
});
}
mLog.DebugFormat(
"{0} meta sections calculated in {1} ms for '{2}'",
result.Count, sw.ElapsedMilliseconds, metaFileName);
return result;
}
static PropertyTreeNode WrapAsSectionRoot(PropertyTreeNode section)
{
if (section.Kind == NodeKind.Leaf)
{
return PropertyTreeNode.CreateRoot(
new List<PropertyTreeNode> { section });
}
return PropertyTreeNode.CreateRoot(
new List<PropertyTreeNode>(section.Children));
}
static readonly List<ObjectContent> EmptyList =
new List<ObjectContent>();
static readonly ILog mLog = PlasticApp.GetLogger("MetaFileContents");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c305dffd0bd94ae788894e50eb35e343
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,86 @@
using System.Collections.Generic;
using PlasticGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content
{
internal class ObjectContent
{
internal UnityEngine.Object Object;
internal PropertyTreeNode PropertyTree;
internal List<ObjectContent> ComponentContents;
// Populated when this row represents a section of a .meta file —
// the originating .meta filename (MetaFileName) and the nicified
// top-level YAML key (MetaSectionName, e.g. "Audio Importer"),
// analogous to a Component header in UnityObject diffs. MetaFileName
// is the canonical "this is a meta row" flag (see IsMetaFileObject);
// Object is null on meta rows.
internal string MetaFileName;
internal string MetaSectionName;
// Gated on MetaFileName rather than Object being null, so we don't
// misclassify a UnityObject row whose underlying native object has
// been destroyed (Unity's overloaded == reports it null) as a meta
// row.
internal bool IsMetaFileObject
{
get { return !string.IsNullOrEmpty(MetaFileName); }
}
internal int GetObjectId()
{
if (IsMetaFileObject)
return (MetaFileName + ":" + MetaSectionName).GetHashCode();
return Object != null ? Object.GetObjectId() : 0;
}
internal string GetDisplayName()
{
if (IsMetaFileObject)
return GetMetaDisplayName();
if (Object == null)
return PlasticLocalization.Name.DiffUnknownObject.GetString();
// Components share their GameObject's name, so showing it would
// duplicate the parent header. For everything else the icon
// already conveys the type — show the object's own name.
if (Object is UnityEngine.Component)
return Object.GetType().Name;
return string.IsNullOrEmpty(Object.name) ? Object.GetType().Name : Object.name;
}
internal string GetTypeName()
{
return Object == null ? null : Object.GetType().Name;
}
internal string GetObjectName()
{
return Object == null ? null : Object.name;
}
internal bool IsGameObject()
{
return Object is UnityEngine.GameObject;
}
internal UnityEngine.GameObject GetGameObject()
{
if (Object is UnityEngine.GameObject go)
return go;
if (Object is UnityEngine.Component c)
return c.gameObject;
return null;
}
string GetMetaDisplayName()
{
return string.IsNullOrEmpty(MetaSectionName)
? MetaFileName
: MetaSectionName;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a03d6d8b450b42229e7201066ecd389d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 018268bdd48d54121b0fe237a6571615
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content.Property
{
internal class PropertyContent
{
internal string Path;
internal string DisplayName;
internal string TypeTag;
internal string Value;
internal object Tag;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4482fa6271aa4d47a88eb0abab598eb2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7b2b4aac3415145888e9c580fb869826
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,144 @@
using System.Collections.Generic;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content.Search
{
internal class PropertyContentSearchIndex
{
internal bool IsActive { get; }
internal static PropertyContentSearchIndex Build(
IList<ObjectContent> objectContents, string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm))
return new PropertyContentSearchIndex(isActive: false, null);
HashSet<PropertyTreeNode> visible = new HashSet<PropertyTreeNode>();
foreach (ObjectContent content in objectContents)
{
bool objectInScope = SearchMatcher.Contains(
content.GetDisplayName(), searchTerm);
CollectVisibleForObject(
content.PropertyTree, searchTerm, objectInScope, visible);
if (content.ComponentContents == null)
continue;
foreach (ObjectContent comp in content.ComponentContents)
{
bool componentInScope = objectInScope
|| SearchMatcher.Contains(
comp.GetDisplayName(), searchTerm);
CollectVisibleForObject(
comp.PropertyTree, searchTerm, componentInScope, visible);
}
}
return new PropertyContentSearchIndex(isActive: true, visible);
}
static void CollectVisibleForObject(
PropertyTreeNode root,
string searchTerm,
bool ownerNameMatches,
HashSet<PropertyTreeNode> visible)
{
if (root == null)
return;
if (ownerNameMatches)
{
foreach (PropertyTreeNode child in root.Children)
AddSubtree(child, visible);
return;
}
CollectVisible(root, searchTerm, visible);
}
internal bool IsNodeVisible(PropertyTreeNode node)
{
if (!IsActive)
return true;
return mVisibleNodes.Contains(node);
}
internal bool SubtreeHasMatch(ObjectContent content)
{
if (!IsActive)
return false;
if (content.PropertyTree == null)
return false;
foreach (PropertyTreeNode child in content.PropertyTree.Children)
{
if (mVisibleNodes.Contains(child))
return true;
}
return false;
}
PropertyContentSearchIndex(bool isActive, HashSet<PropertyTreeNode> visibleNodes)
{
IsActive = isActive;
mVisibleNodes = visibleNodes;
}
static bool CollectVisible(
PropertyTreeNode node,
string searchTerm,
HashSet<PropertyTreeNode> visible)
{
if (node == null)
return false;
if (node.Kind == NodeKind.Leaf)
{
string label = node.DisplayName ?? node.Path;
bool matches =
SearchMatcher.Contains(label, searchTerm) ||
SearchMatcher.Contains(node.Path, searchTerm);
if (matches)
visible.Add(node);
return matches;
}
bool nodeMatches =
SearchMatcher.Contains(node.DisplayName, searchTerm) ||
SearchMatcher.Contains(node.Path, searchTerm);
if (nodeMatches)
{
AddSubtree(node, visible);
return true;
}
bool anyChildMatches = false;
foreach (PropertyTreeNode child in node.Children)
{
if (CollectVisible(child, searchTerm, visible))
anyChildMatches = true;
}
if (anyChildMatches)
visible.Add(node);
return anyChildMatches;
}
static void AddSubtree(
PropertyTreeNode node, HashSet<PropertyTreeNode> visible)
{
visible.Add(node);
foreach (PropertyTreeNode child in node.Children)
AddSubtree(child, visible);
}
readonly HashSet<PropertyTreeNode> mVisibleNodes;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fc407072748964c61a00ee8d7e579db1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 17560f2306bb24c3f829b2c849fdf839
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,149 @@
using System.Collections.Generic;
using System.Diagnostics;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
using Codice.LogWrapper;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.UnityObject;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Content.UnityObject
{
internal static class UnityObjectContents
{
internal static List<ObjectContent> BuildContentData(string file)
{
Stopwatch sw = Stopwatch.StartNew();
List<ObjectContent> objectContents = new List<ObjectContent>();
UnityEngine.Object[] objects = InternalEditorUtility.LoadSerializedFileAndForget(file);
foreach (UnityEngine.Object obj in objects)
{
if (obj == null)
continue;
objectContents.Add(BuildObjectContent(obj));
}
GroupComponentsUnderGameObjects(objectContents);
RemoveEmptyNonGameObjects(objectContents);
HierarchyOrderSorting.SortByHierarchyOrder(
objectContents, c => c.Object, objects);
mLog.DebugFormat(
"{0} object contents calculated in {1} ms",
objectContents.Count, sw.ElapsedMilliseconds);
return objectContents;
}
static ObjectContent BuildObjectContent(UnityEngine.Object obj)
{
ObjectContent content = new ObjectContent
{
Object = obj
};
using (SerializedObject so = new SerializedObject(obj))
content.PropertyTree = PropertyTreeBuilder.Build(so);
return content;
}
static void GroupComponentsUnderGameObjects(List<ObjectContent> objectContents)
{
Dictionary<GameObject, ObjectContent> gameObjectMap =
new Dictionary<GameObject, ObjectContent>();
foreach (ObjectContent content in objectContents)
{
if (content.Object is GameObject go)
gameObjectMap[go] = content;
}
if (gameObjectMap.Count == 0)
return;
List<ObjectContent> topLevel = new List<ObjectContent>(objectContents.Count);
foreach (ObjectContent content in objectContents)
{
if (content.Object is Component c && c.gameObject != null
&& gameObjectMap.TryGetValue(c.gameObject, out ObjectContent parent))
{
if (parent.ComponentContents == null)
parent.ComponentContents = new List<ObjectContent>();
parent.ComponentContents.Add(content);
continue;
}
topLevel.Add(content);
}
objectContents.Clear();
objectContents.AddRange(topLevel);
foreach (ObjectContent content in objectContents)
SortComponentsByGameObjectOrder(content);
}
static void SortComponentsByGameObjectOrder(ObjectContent gameObjectContent)
{
if (gameObjectContent.ComponentContents == null)
return;
if (!(gameObjectContent.Object is GameObject go))
return;
Component[] orderedComponents = go.GetComponents<Component>();
Dictionary<Component, int> orderIndex = new Dictionary<Component, int>(
orderedComponents.Length);
for (int i = 0; i < orderedComponents.Length; i++)
{
if (orderedComponents[i] != null)
orderIndex[orderedComponents[i]] = i;
}
gameObjectContent.ComponentContents.Sort((a, b) =>
{
int ia = a.Object is Component ca && orderIndex.TryGetValue(ca, out int va)
? va : int.MaxValue;
int ib = b.Object is Component cb && orderIndex.TryGetValue(cb, out int vb)
? vb : int.MaxValue;
return ia.CompareTo(ib);
});
}
// Drops objects whose property tree is empty after IgnoredProperties
// filtering — e.g. SceneRoots, whose only fields (m_ObjectHideFlags
// and m_Roots) are both ignored. GameObjects are kept regardless
// because they own their components.
static void RemoveEmptyNonGameObjects(List<ObjectContent> objectContents)
{
for (int i = objectContents.Count - 1; i >= 0; i--)
{
ObjectContent content = objectContents[i];
if (content.Object is GameObject)
continue;
PropertyTreeNode tree = content.PropertyTree;
if (tree != null && tree.Children.Count > 0)
continue;
objectContents.RemoveAt(i);
}
}
static readonly ILog mLog = PlasticApp.GetLogger("UnityObjectContents");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 17a6aa48df0d4d69a081f9c2b83ecb1c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c52dccb0f71c4bc0b587555b3017d7ec
timeCreated: 1774967992
@@ -0,0 +1,972 @@
using System;
using System.Collections.Generic;
using Codice.Client.Common.Threading;
using Codice.CM.Client.Differences;
using Codice.CM.Client.Differences.Graphic;
using MergetoolGui;
using PlasticGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Meta;
using Unity.PlasticSCM.Editor.Diff.Asset.Common.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.UnityObject;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Filtering;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Search;
using Unity.PlasticSCM.Editor.Diff.Purged;
using Unity.PlasticSCM.Editor.Diff.Text;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using XDiffGui;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class AssetDiffControl : VisualElement, IBigFilePanelListener
{
internal AssetDiffControl(
IBigFileDownloader bigFileDownloader,
IBigFileChecker bigFileChecker,
Action onViewAsTextDiff)
{
mBigFileDownloader = bigFileDownloader;
mBigFileChecker = bigFileChecker;
mOnViewAsTextDiff = onViewAsTextDiff;
CreateGUI();
RegisterCallback<AttachToPanelEvent>(_ =>
{
AssetReloadNotifier.AssetsChanged += OnAssetsChanged;
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
});
RegisterCallback<DetachFromPanelEvent>(_ =>
{
AssetReloadNotifier.AssetsChanged -= OnAssetsChanged;
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
});
}
internal void ShowData(DiffViewerData diffData)
{
if (diffData == null)
return;
mDiffViewerData = diffData;
DisplayCurrentData(isReload: false);
}
void DisplayCurrentData(bool isReload)
{
DiffViewerData diffData = mDiffViewerData;
string leftContributor;
string rightContributor;
SymbolicNameParser.GetContributorSpecs(diffData.Left.SymbolicName,
diffData.Right.SymbolicName, out leftContributor, out rightContributor);
mContributorsHeaderPanel.SetNames(leftContributor, rightContributor);
mMessagePanel.Hide();
ReplaceMainView(mContentPanel);
if (BigFileDiffCalculator.IsBigFileDiff(diffData, mBigFileDownloader, mBigFileChecker))
{
ShowBigFileMessage();
return;
}
if (diffData.Left?.IsPurged == true || diffData.Right?.IsPurged == true)
{
ShowPurgedRevision(diffData);
return;
}
ShowAssetDiff(diffData.Left.File, diffData.Right.File, isReload);
}
void OnAssetsChanged(HashSet<string> changedFullPaths)
{
if (mDiffViewerData == null)
return;
if (!AssetReloadNotifier.IsWatchedPath(
mDiffViewerData.Left?.File, changedFullPaths)
&& !AssetReloadNotifier.IsWatchedPath(
mDiffViewerData.Right?.File, changedFullPaths))
return;
DisplayCurrentData(isReload: true);
}
// Entering or exiting play mode causes Unity to drop the objects we
// loaded into mObjectDiffs via LoadSerializedFileAndForget. Without
// a fresh load the next re-bind would render every header as a
// fallback ("Unknown" / generic file icon), since the underlying
// native objects are gone even though the C# refs remain.
void OnPlayModeStateChanged(PlayModeStateChange state)
{
if (mDiffViewerData == null)
return;
if (state != PlayModeStateChange.EnteredEditMode
&& state != PlayModeStateChange.EnteredPlayMode)
return;
DisplayCurrentData(isReload: true);
}
void ShowAssetDiff(string leftFile, string rightFile, bool isReload)
{
ReplaceView(mListView);
mVisibleRows.Clear();
ExpansionSnapshot previousCache = isReload
? SnapshotExpansionState()
: null;
bool isMetaDiff = MetaPath.IsMetaPath(leftFile);
mObjectDiffs = isMetaDiff ?
MetaFileDiffs.BuildDiffData(leftFile, rightFile) :
UnityObjectDiffs.BuildDiffData(leftFile, rightFile);
UpdateDataLossBanner(mObjectDiffs);
ApplyExpansionState(previousCache);
UpdateAvailableFilters(isMetaDiff);
RebuildVisibleRows();
}
void UpdateAvailableFilters(bool isMetaDiff)
{
if (isMetaDiff)
{
mDiffToolbarPanel.UpdateAvailableFilters(null, null, show: false);
return;
}
mDiffToolbarPanel.UpdateAvailableFilters(
ObjectDiffOptions.ExtractGameObjects(mObjectDiffs, GetGameObjectIcon),
ObjectDiffOptions.ExtractTypes(mObjectDiffs, GetIconForObject),
show: true);
}
static UnityEngine.Texture GetGameObjectIcon(ObjectDiff diff)
{
GameObject go = diff.GetGameObject();
if (go != null)
return EditorGUIUtility.ObjectContent(go, typeof(GameObject)).image;
return GetIconForObject(diff);
}
static UnityEngine.Texture GetIconForObject(ObjectDiff diff)
{
UnityEngine.Object obj = diff.SrcObject ?? diff.DstObject;
if (obj == null)
return null;
return EditorGUIUtility.ObjectContent(obj, obj.GetType()).image;
}
ExpansionSnapshot SnapshotExpansionState()
{
ExpansionSnapshot snapshot = new ExpansionSnapshot();
foreach (ObjectDiff obj in mObjectDiffs)
{
AddIfDeviatesFromDefault(snapshot.Objects, BuildObjectKey(obj), obj);
if (obj.ComponentDiffs == null)
continue;
for (int i = 0; i < obj.ComponentDiffs.Count; i++)
{
ObjectDiff comp = obj.ComponentDiffs[i];
AddIfDeviatesFromDefault(
snapshot.Objects, BuildComponentKey(obj, comp, i), comp);
}
}
foreach (string fullKey in mCollapsedGroups)
snapshot.CollapsedGroups.Add(fullKey);
return snapshot;
}
void AddIfDeviatesFromDefault(
Dictionary<string, bool> snapshot, string key, ObjectDiff obj)
{
bool isExpanded = mExpandedObjects.Contains(obj.GetObjectId());
if (isExpanded == DefaultExpand(obj))
return;
snapshot[key] = isExpanded;
}
void ApplyExpansionState(ExpansionSnapshot previousCache)
{
mExpandedObjects.Clear();
mCollapsedGroups.Clear();
foreach (ObjectDiff obj in mObjectDiffs)
{
if (ShouldExpand(previousCache?.Objects, BuildObjectKey(obj), DefaultExpand(obj)))
mExpandedObjects.Add(obj.GetObjectId());
if (obj.ComponentDiffs == null)
continue;
for (int i = 0; i < obj.ComponentDiffs.Count; i++)
{
ObjectDiff comp = obj.ComponentDiffs[i];
if (ShouldExpand(previousCache?.Objects, BuildComponentKey(obj, comp, i), DefaultExpand(comp)))
mExpandedObjects.Add(comp.GetObjectId());
}
}
if (previousCache == null)
return;
foreach (string fullKey in previousCache.CollapsedGroups)
mCollapsedGroups.Add(fullKey);
}
static bool ShouldExpand(
Dictionary<string, bool> previousCache, string key, bool defaultExpand)
{
if (previousCache != null && previousCache.TryGetValue(key, out bool wasExpanded))
return wasExpanded;
return defaultExpand;
}
static bool DefaultExpand(ObjectDiff obj)
{
bool hasComponents = obj.ComponentDiffs != null && obj.ComponentDiffs.Count > 0;
if (hasComponents)
return true;
if (obj.DiffType != DiffType.Modified)
return false;
return obj.PropertyDiffTree != null && obj.PropertyDiffTree.Children.Count > 0;
}
static string BuildObjectKey(ObjectDiff obj)
{
return "o:" + obj.GetSrcDisplayName();
}
static string BuildComponentKey(
ObjectDiff parent, ObjectDiff comp, int index)
{
return "c:" + parent.GetSrcDisplayName() + "/" + index + ":" + comp.GetSrcDisplayName();
}
static string BuildGroupFullKey(ObjectDiff owner, string groupKey)
{
return owner.GetObjectId() + ":" + groupKey;
}
void IBigFilePanelListener.OnCalculateDifferencesButtonClick()
{
mBigFileMessagePanel.Disable();
IThreadWaiter waiter = ThreadWaiter.GetWaiter(10);
waiter.Execute(
/*threadOperationDelegate*/ delegate
{
mBigFileDownloader.DownloadFiles(mDiffViewerData, null);
},
/*afterOperationDelegate*/ delegate
{
mBigFileMessagePanel.Enable();
if (waiter.Exception != null)
{
MergetoolExceptionsHandler.DisplayException(
waiter.Exception);
return;
}
DisplayCurrentData(isReload: false);
});
}
void ShowBigFileMessage()
{
if (mBigFileMessagePanel == null)
mBigFileMessagePanel = new BigFileMessagePanel(this, false);
mBigFileMessagePanel.UpdateDisplayData(
BigFileDisplayData.Build(
mDiffViewerData, mBigFileDownloader));
mContributorsHeaderPanel.SetSeparatorsVisible(true);
ReplaceView(mBigFileMessagePanel);
}
void ShowPurgedRevision(DiffViewerData data)
{
if (mPurgedRevisionControl == null)
mPurgedRevisionControl = new PurgedRevisionControl();
mPurgedRevisionControl.ShowData(data);
ReplaceMainView(mPurgedRevisionControl);
}
void ReplaceMainView(VisualElement panel)
{
if (hierarchy.childCount == 1 && hierarchy[0] == panel)
return;
Clear();
Add(panel);
}
void ReplaceView(VisualElement view)
{
if (mCurrentView == view)
return;
if (mCurrentView != null)
mContainerPanel.Remove(mCurrentView);
mContainerPanel.Add(view);
mCurrentView = view;
}
internal void Dispose()
{
mDiffToolbarPanel.Dispose();
if (mBigFileMessagePanel != null)
mBigFileMessagePanel.Dispose();
if (mPurgedRevisionControl != null)
mPurgedRevisionControl.Dispose();
}
void RebuildVisibleRows()
{
mVisibleRows.Clear();
mKnownGroups.Clear();
mSearchIndex = PropertyDiffSearchIndex.Build(mObjectDiffs, mSearchFilter);
CollectAllGroupKeys();
int modified = 0, added = 0, removed = 0;
foreach (ObjectDiff objDiff in mObjectDiffs)
{
CountByDiffType(objDiff.DiffType, ref modified, ref added, ref removed);
if (objDiff.ComponentDiffs == null)
continue;
foreach (ObjectDiff comp in objDiff.ComponentDiffs)
CountByDiffType(comp.DiffType, ref modified, ref added, ref removed);
}
foreach (ObjectDiff objDiff in mObjectDiffs)
{
if (!PassesGameObjectFilter(objDiff))
continue;
if (mSearchIndex.IsActive)
AddObjectRowsWithSearch(objDiff);
else
AddObjectRows(objDiff);
}
mDiffToolbarPanel.UpdateFilterButtons(modified, added, removed, mDiffFilter);
mContributorsHeaderPanel.SetSeparatorsVisible(mVisibleRows.Count == 0);
if (mVisibleRows.Count == 0)
{
ShowEmptyState();
return;
}
ReplaceView(mListView);
mListView.RefreshItems();
}
void ShowEmptyState()
{
if (mEmptyStatePanel == null)
mEmptyStatePanel = new DiffMessagePanel();
mEmptyStatePanel.ShowMessage(GetEmptyStateMessage());
ReplaceView(mEmptyStatePanel);
}
string GetEmptyStateMessage()
{
bool hasSearch = !string.IsNullOrEmpty(mSearchFilter);
bool hasFilter = mDiffFilter != DiffFilter.All
|| mSelectedGameObjects != null
|| mSelectedTypes != null;
if (hasSearch || hasFilter)
return PlasticLocalization.Name.NoDiffsMatchingFilters.GetString();
return PlasticLocalization.Name.NoSerializedAssetDifferencesFound.GetString();
}
void AddObjectRows(ObjectDiff objDiff)
{
bool selfPasses = PassesDiffFilter(objDiff.DiffType)
&& PassesTypeFilter(objDiff);
bool anyChildPasses = HasVisibleChildComponent(objDiff);
if (!selfPasses && !anyChildPasses)
return;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ObjectHeader, objDiff, null));
if (!mExpandedObjects.Contains(objDiff.GetObjectId()))
return;
if (selfPasses)
AddPropertyRows(objDiff, 0);
AddComponentRows(objDiff);
}
bool HasVisibleChildComponent(ObjectDiff parent)
{
if (parent.ComponentDiffs == null)
return false;
foreach (ObjectDiff comp in parent.ComponentDiffs)
{
if (!PassesDiffFilter(comp.DiffType))
continue;
if (!PassesTypeFilter(comp))
continue;
return true;
}
return false;
}
void AddComponentRows(ObjectDiff parentDiff)
{
if (parentDiff.ComponentDiffs == null)
return;
foreach (ObjectDiff compDiff in parentDiff.ComponentDiffs)
{
if (!PassesDiffFilter(compDiff.DiffType))
continue;
if (!PassesTypeFilter(compDiff))
continue;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ComponentHeader, compDiff, null, 1));
if (!mExpandedObjects.Contains(compDiff.GetObjectId()))
continue;
AddPropertyRows(compDiff, 1);
}
}
void AddPropertyRows(ObjectDiff objDiff, int indentLevel)
{
PropertyDiffNode root = objDiff.PropertyDiffTree;
if (root == null)
return;
mWalker.Walk(
root.Children,
indentLevel,
IsNodeVisible,
node => BuildGroupFullKey(objDiff, node.Path),
IsGroupExpanded,
(node, indent) => AddPropertyRow(
objDiff, ToFlatDiff(node), indent),
(node, indent, fullKey) => mVisibleRows.Add(new DiffRow(
DiffRowKind.ContainerHeader, objDiff, fullKey,
node.DisplayName, node.DiffType, indent)));
}
void CollectAllGroupKeys()
{
foreach (ObjectDiff objDiff in mObjectDiffs)
{
CollectGroupKeysForOwner(objDiff);
if (objDiff.ComponentDiffs == null)
continue;
foreach (ObjectDiff comp in objDiff.ComponentDiffs)
CollectGroupKeysForOwner(comp);
}
}
void CollectGroupKeysForOwner(ObjectDiff owner)
{
if (owner.PropertyDiffTree == null)
return;
mWalker.CollectGroupKeys(
owner.PropertyDiffTree.Children,
node => BuildGroupFullKey(owner, node.Path),
key => mKnownGroups.Add(key));
}
bool IsNodeVisible(PropertyDiffNode node)
{
if (!HasFilterMatchInSubtree(node))
return false;
return mSearchIndex.IsNodeVisible(node);
}
bool HasFilterMatchInSubtree(PropertyDiffNode node)
{
switch (mDiffFilter)
{
case DiffFilter.All:
return node.DescendantDiffTypes != DiffTypeFlags.None;
case DiffFilter.Modified:
return node.HasDescendantOfType(DiffType.Modified);
case DiffFilter.Added:
return node.HasDescendantOfType(DiffType.Added);
case DiffFilter.Removed:
return node.HasDescendantOfType(DiffType.Removed);
default:
return true;
}
}
bool IsGroupExpanded(string fullKey)
{
if (mSearchIndex.IsActive)
return true;
return !mCollapsedGroups.Contains(fullKey);
}
static PropertyDiff ToFlatDiff(PropertyDiffNode node)
{
return new PropertyDiff
{
Path = node.Path,
DisplayName = node.DisplayName,
TypeTag = node.TypeTag,
DiffType = node.DiffType,
SrcValue = node.SrcValue,
DstValue = node.DstValue,
SrcTag = node.SrcTag,
DstTag = node.DstTag
};
}
void AddPropertyRow(
ObjectDiff owner, PropertyDiff propDiff, int indentLevel)
{
mVisibleRows.Add(new DiffRow(
DiffRowKind.PropertyDiff, owner, propDiff, indentLevel));
if (PropertyRow.IsTallProperty(propDiff.SrcTag)
|| PropertyRow.IsTallProperty(propDiff.DstTag))
{
mVisibleRows.Add(new DiffRow(
DiffRowKind.PropertyDiff, owner, propDiff,
indentLevel, isSpacer: true));
}
}
void AddObjectRowsWithSearch(ObjectDiff objDiff)
{
bool selfPasses = PassesDiffFilter(objDiff.DiffType)
&& PassesTypeFilter(objDiff);
bool objectNameMatches =
SearchMatcher.Contains(objDiff.GetSrcDisplayName(), mSearchFilter) ||
SearchMatcher.Contains(objDiff.GetDstDisplayName(), mSearchFilter);
bool hasOwnPropertyMatch = selfPasses && SubtreeHasSearchMatch(objDiff);
bool hasComponentMatch = HasComponentSearchMatch(objDiff);
bool selfWouldShow = selfPasses
&& (hasOwnPropertyMatch || objectNameMatches);
bool nameMatchSurfacesChildren =
objectNameMatches && HasVisibleChildComponent(objDiff);
if (!selfWouldShow && !hasComponentMatch && !nameMatchSurfacesChildren)
return;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ObjectHeader, objDiff, null));
if (selfPasses && (hasOwnPropertyMatch || objectNameMatches))
AddPropertyRows(objDiff, 0);
AddComponentRowsWithSearch(objDiff, objectNameMatches);
}
void AddComponentRowsWithSearch(
ObjectDiff parentDiff, bool parentNameMatches)
{
if (parentDiff.ComponentDiffs == null)
return;
foreach (ObjectDiff compDiff in parentDiff.ComponentDiffs)
{
if (!PassesDiffFilter(compDiff.DiffType))
continue;
if (!PassesTypeFilter(compDiff))
continue;
bool compNameMatches =
SearchMatcher.Contains(
compDiff.GetSrcDisplayName(), mSearchFilter) ||
SearchMatcher.Contains(
compDiff.GetDstDisplayName(), mSearchFilter);
bool compHasPropertyMatch = SubtreeHasSearchMatch(compDiff);
if (!parentNameMatches && !compNameMatches && !compHasPropertyMatch)
continue;
mVisibleRows.Add(new DiffRow(
DiffRowKind.ComponentHeader, compDiff, null, 1));
if (compHasPropertyMatch
|| mExpandedObjects.Contains(compDiff.GetObjectId()))
{
AddPropertyRows(compDiff, 1);
}
}
}
bool SubtreeHasSearchMatch(ObjectDiff objDiff)
{
if (objDiff.PropertyDiffTree == null)
return false;
foreach (PropertyDiffNode child in objDiff.PropertyDiffTree.Children)
{
if (mSearchIndex.IsNodeVisible(child) && HasFilterMatchInSubtree(child))
return true;
}
return false;
}
bool HasComponentSearchMatch(ObjectDiff objDiff)
{
if (objDiff.ComponentDiffs == null)
return false;
foreach (ObjectDiff compDiff in objDiff.ComponentDiffs)
{
if (!PassesDiffFilter(compDiff.DiffType))
continue;
if (!PassesTypeFilter(compDiff))
continue;
if (SearchMatcher.Contains(
compDiff.GetSrcDisplayName(), mSearchFilter) ||
SearchMatcher.Contains(
compDiff.GetDstDisplayName(), mSearchFilter))
return true;
if (SubtreeHasSearchMatch(compDiff))
return true;
}
return false;
}
static void CountByDiffType(
DiffType diffType, ref int modified, ref int added, ref int removed)
{
switch (diffType)
{
case DiffType.Modified: modified++; break;
case DiffType.Added: added++; break;
case DiffType.Removed: removed++; break;
}
}
bool PassesDiffFilter(DiffType diffType)
{
switch (mDiffFilter)
{
case DiffFilter.All: return diffType != DiffType.Unchanged;
case DiffFilter.Modified: return diffType == DiffType.Modified;
case DiffFilter.Added: return diffType == DiffType.Added;
case DiffFilter.Removed: return diffType == DiffType.Removed;
default: return true;
}
}
bool PassesGameObjectFilter(ObjectDiff diff)
{
return ObjectDiffFilters.PassesGameObjectFilter(diff, mSelectedGameObjects);
}
bool PassesTypeFilter(ObjectDiff diff)
{
return ObjectDiffFilters.PassesTypeFilter(diff, mSelectedTypes);
}
void OnBindRow(VisualElement element, int index)
{
if (index < 0 || index >= mVisibleRows.Count)
return;
DiffRow row = mVisibleRows[index];
DiffRowElement rowElement = (DiffRowElement)element;
if (row.IsSpacer)
{
rowElement.BindSpacer(row.PropertyDiff, row.IndentLevel);
return;
}
switch (row.Kind)
{
case DiffRowKind.ObjectHeader:
case DiffRowKind.ComponentHeader:
bool isExpanded = mExpandedObjects.Contains(
row.ObjectDiff.GetObjectId());
rowElement.BindHeader(
row.ObjectDiff,
isExpanded,
mSearchFilter,
row.IndentLevel);
return;
case DiffRowKind.ContainerHeader:
rowElement.BindGroupHeader(
row.GroupDisplayName,
row.GroupDiffType,
row.GroupKey,
IsGroupExpanded(row.GroupKey),
mSearchFilter,
row.IndentLevel);
return;
default:
rowElement.BindProperty(
row.PropertyDiff,
mSearchFilter,
row.IndentLevel);
return;
}
}
void OnObjectToggled(ObjectDiff objDiff)
{
int id = objDiff.GetObjectId();
if (!mExpandedObjects.Remove(id))
mExpandedObjects.Add(id);
RebuildVisibleRows();
}
void OnGroupToggled(string groupFullKey)
{
if (!mCollapsedGroups.Remove(groupFullKey))
mCollapsedGroups.Add(groupFullKey);
RebuildVisibleRows();
}
void SetDiffFilter(DiffFilter filter)
{
mDiffFilter = filter;
RebuildVisibleRows();
}
void SetSearchFilter(string searchFilter)
{
mSearchFilter = searchFilter ?? string.Empty;
RebuildVisibleRows();
}
void SetGameObjectFilter(HashSet<string> selected)
{
mSelectedGameObjects = selected;
RebuildVisibleRows();
}
void SetTypeFilter(HashSet<string> selected)
{
mSelectedTypes = selected;
RebuildVisibleRows();
}
void ExpandAll()
{
foreach (ObjectDiff objDiff in mObjectDiffs)
{
mExpandedObjects.Add(objDiff.GetObjectId());
if (objDiff.ComponentDiffs == null)
continue;
foreach (ObjectDiff compDiff in objDiff.ComponentDiffs)
mExpandedObjects.Add(compDiff.GetObjectId());
}
mCollapsedGroups.Clear();
RebuildVisibleRows();
}
void CollapseAll()
{
mExpandedObjects.Clear();
foreach (string fullKey in mKnownGroups)
mCollapsedGroups.Add(fullKey);
RebuildVisibleRows();
}
void UpdateDataLossBanner(List<ObjectDiff> diffs)
{
int dataLossCount = CountObjectsWithDataLoss(diffs);
if (dataLossCount == 0)
{
mMessagePanel.Hide();
return;
}
mMessagePanel.HandleMessage(
DataLossDescriptions.GetBannerMessage(dataLossCount),
DataLossDescriptions.GetViewAsTextDiffButtonText(),
mOnViewAsTextDiff);
}
// Counts every ObjectDiff (top-level or nested under a GameObject
// container) whose own DataLoss is non-None. We don't add the
// container's rolled-up signal because containers don't have their
// own data — counting them would double-count the children.
static int CountObjectsWithDataLoss(List<ObjectDiff> diffs)
{
int n = 0;
foreach (ObjectDiff d in diffs)
{
if (d.DataLoss != DataLossKind.None)
n++;
if (d.ComponentDiffs == null)
continue;
foreach (ObjectDiff c in d.ComponentDiffs)
{
if (c.DataLoss != DataLossKind.None)
n++;
}
}
return n;
}
void CreateGUI()
{
style.flexGrow = 1;
mMessagePanel = new MessagePanel();
mDiffToolbarPanel = new DiffToolbarPanel(
SetDiffFilter, SetSearchFilter, ExpandAll, CollapseAll,
SetGameObjectFilter, SetTypeFilter);
mContributorsHeaderPanel = new ContributorsHeaderPanel();
mListView = CreateListView();
mContainerPanel = new VisualElement();
mContainerPanel.style.flexGrow = 1;
mContentPanel = new VisualElement();
mContentPanel.style.flexGrow = 1;
mContentPanel.Add(mMessagePanel);
mContentPanel.Add(mDiffToolbarPanel);
mContentPanel.Add(mContributorsHeaderPanel);
mContentPanel.Add(mContainerPanel);
Add(mContentPanel);
ReplaceView(mListView);
}
ListView CreateListView()
{
ListView result = new ListView();
result.style.flexGrow = 1;
result.fixedItemHeight = DiffRowElement.ROW_HEIGHT;
result.makeItem = () => new DiffRowElement(OnObjectToggled, OnGroupToggled);
result.bindItem = OnBindRow;
result.selectionType = SelectionType.None;
result.itemsSource = mVisibleRows;
return result;
}
DiffToolbarPanel mDiffToolbarPanel;
ContributorsHeaderPanel mContributorsHeaderPanel;
MessagePanel mMessagePanel;
ListView mListView;
VisualElement mContentPanel;
VisualElement mContainerPanel;
VisualElement mCurrentView;
BigFileMessagePanel mBigFileMessagePanel;
PurgedRevisionControl mPurgedRevisionControl;
DiffMessagePanel mEmptyStatePanel;
List<ObjectDiff> mObjectDiffs = new List<ObjectDiff>();
readonly HashSet<int> mExpandedObjects = new HashSet<int>();
readonly HashSet<string> mCollapsedGroups = new HashSet<string>();
readonly HashSet<string> mKnownGroups = new HashSet<string>();
readonly List<DiffRow> mVisibleRows = new List<DiffRow>();
PropertyDiffSearchIndex mSearchIndex = PropertyDiffSearchIndex.Build(
new List<ObjectDiff>(), null);
DiffFilter mDiffFilter = DiffFilter.All;
HashSet<string> mSelectedGameObjects;
HashSet<string> mSelectedTypes;
string mSearchFilter = string.Empty;
DiffViewerData mDiffViewerData;
readonly IBigFileDownloader mBigFileDownloader;
readonly IBigFileChecker mBigFileChecker;
readonly Action mOnViewAsTextDiff;
static readonly PropertyTreeWalker<PropertyDiffNode> mWalker =
new PropertyTreeWalker<PropertyDiffNode>(
node => node.Kind,
node => node.Children);
class ExpansionSnapshot
{
internal readonly Dictionary<string, bool> Objects =
new Dictionary<string, bool>();
internal readonly HashSet<string> CollapsedGroups =
new HashSet<string>();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 83ac42cfcef844f98fd021a805db6392
timeCreated: 1772182350
@@ -0,0 +1,83 @@
using PlasticGui;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
// The diff was produced from an object whose serialized data was
// dropped by Unity's loader (LoadSerializedFileAndForget). The diff is
// incomplete — fields the loader couldn't materialize are missing from
// it — and the user should be steered to text diff.
//
// Each kind corresponds to a specific failure mode in Unity's loader
// that we have explicitly identified. We do not surface a generic
// "something might be wrong" signal — every entry here names a concrete
// problem so the UI can give the user an accurate explanation. Higher
// values are more specific — see DataLossDetection.PickMoreSpecific for
// the precedence used when multiple signals fire on the same object pair.
internal enum DataLossKind
{
None = 0,
// AnimatorOverrideController whose runtimeAnimatorController is
// null. AwakeFromLoad → BuildAsset wipes m_Clips whenever the
// controller is null (see Modules/Animation/AnimatorOverrideController.cpp
// in the Unity source), so any clip overrides serialized in the
// YAML are silently dropped and never reach the diff.
UnresolvedAnimatorController = 1,
// MonoBehaviour with no resolvable MonoScript reference (missing
// script). Serialized fields beyond the base MonoBehaviour are lost.
UnresolvedMonoScript = 2,
// The loader replaced the object with UnityEditor.FallbackEditorWindow
// because its script could not be loaded into the editor AppDomain
// (typically: package not installed or AppDomain reload timing). All
// fields except the base EditorWindow members are stripped.
FallbackEditorWindow = 3
}
// Localized copy for every data-loss surface — per-row tooltip,
// file-level banner, and the "switch to text diff" button. Kept
// alongside DataLossKind so adding a new kind forces the maintainer
// to also choose the user-facing message.
internal static class DataLossDescriptions
{
internal static string GetRowTooltip(DataLossKind kind)
{
switch (kind)
{
case DataLossKind.UnresolvedAnimatorController:
return PlasticLocalization.Name
.DiffDataLossUnresolvedAnimatorController.GetString();
case DataLossKind.UnresolvedMonoScript:
return PlasticLocalization.Name
.DiffDataLossUnresolvedMonoScript.GetString();
case DataLossKind.FallbackEditorWindow:
return PlasticLocalization.Name
.DiffDataLossFallbackEditorWindow.GetString();
default:
return string.Empty;
}
}
internal static string GetBannerMessage(int dataLossCount)
{
if (dataLossCount <= 0)
return string.Empty;
if (dataLossCount == 1)
{
return PlasticLocalization.Name
.DiffDataLossBannerSingular.GetString();
}
return PlasticLocalization.Name
.DiffDataLossBannerPlural.GetString(dataLossCount);
}
internal static string GetViewAsTextDiffButtonText()
{
return PlasticLocalization.Name
.DiffDataLossViewAsTextButton.GetString();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6eaff6a39d1545778e6362a438cb9da4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,10 @@
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal enum DiffFilter : byte
{
All,
Modified,
Added,
Removed
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fbb5000a0504a4acd8b805b122326c9f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,39 @@
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal static class DiffGutter
{
internal static Color GetColor(DiffType diffType)
{
switch (diffType)
{
case DiffType.Added:
return UnityStyles.Colors.Diff.AssetDiff.GutterAdded;
case DiffType.Removed:
return UnityStyles.Colors.Diff.AssetDiff.GutterRemoved;
case DiffType.Modified:
return UnityStyles.Colors.Diff.AssetDiff.GutterModified;
default:
return Color.clear;
}
}
internal static void Apply(
VisualElement panel, Color color, float paddingLeft)
{
SetColor(panel, color);
panel.style.paddingLeft = paddingLeft;
}
internal static void SetColor(VisualElement panel, Color color)
{
panel.style.borderLeftWidth = GUTTER_WIDTH;
panel.style.borderLeftColor = color;
}
const float GUTTER_WIDTH = 3f;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c10e8fc853bad4a54a96aedac078a036
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,257 @@
using PlasticGui;
using UnityEngine;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffHeaderRow : VisualElement
{
internal DiffHeaderRow()
{
CreateGUI();
}
internal void Bind(
ObjectDiff objDiff,
bool isExpanded,
string searchFilter,
int indentLevel)
{
// Container GameObjects (no own changes, only nested component
// changes) are stored as Unchanged so they don't inflate status
// counts, but visually they should display like Modified.
DiffType displayType = IsContainer(objDiff)
? DiffType.Modified
: objDiff.DiffType;
mHasSrc = displayType != DiffType.Added;
mHasDst = displayType != DiffType.Removed;
mbIsLeftHovered = false;
mbIsRightHovered = false;
float padding = HeaderRow.BASE_PADDING_LEFT
+ indentLevel * HeaderRow.INDENT_PX;
Color gutterColor = DiffGutter.GetColor(displayType);
DiffGutter.SetColor(mLeftPanel, mHasSrc ? gutterColor : Color.clear);
DiffGutter.SetColor(mRightPanel, mHasDst ? gutterColor : Color.clear);
bool suppressBottomBorder = objDiff.IsGameObject();
HeaderRow.ApplyContentBorder(mLeftContent, mHasSrc, padding, isExpanded, suppressBottomBorder);
HeaderRow.ApplyContentBorder(mRightContent, mHasDst, padding, isExpanded, suppressBottomBorder);
string arrowText = isExpanded
? HeaderRow.ARROW_DOWN : HeaderRow.ARROW_RIGHT;
UnityEngine.Texture icon = ObjectIconResolver.GetIcon(objDiff);
string leftAnnotation = BuildLeftAnnotation(objDiff);
string rightAnnotation = BuildRightAnnotation(objDiff);
bool isExpandable =
(objDiff.PropertyDiffTree != null
&& objDiff.PropertyDiffTree.Children.Count > 0)
|| (objDiff.ComponentDiffs != null && objDiff.ComponentDiffs.Count > 0);
HeaderRow.ConfigurePanel(
mLeftArrow, mLeftIcon, mLeftLabel, mLeftAnnotation, mLeftPanel,
mHasSrc, arrowText,
HeaderRow.GetBackgroundColor(mHasSrc, mbIsLeftHovered), icon,
mHasSrc ? objDiff.GetSrcDisplayName() : string.Empty,
searchFilter,
leftAnnotation,
isExpandable);
HeaderRow.ConfigurePanel(
mRightArrow, mRightIcon, mRightLabel, mRightAnnotation, mRightPanel,
mHasDst, arrowText,
HeaderRow.GetBackgroundColor(mHasDst, mbIsRightHovered), icon,
mHasDst ? objDiff.GetDstDisplayName() : string.Empty,
searchFilter,
rightAnnotation,
isExpandable);
ApplyDataLossTooltip(objDiff, mLeftAnnotation, mRightAnnotation);
}
// The annotation Label is hardcoded italic in HeaderRow.BuildPanel
// — fine for "moved up 1 position" but visually off for the data-
// loss glyph. Toggle the font style + add the tooltip in one pass
// so the two stay in sync.
static void ApplyDataLossTooltip(
ObjectDiff objDiff, Label leftAnnotation, Label rightAnnotation)
{
DataLossKind kind = GetEffectiveDataLoss(objDiff);
bool showingDataLoss = kind != DataLossKind.None;
string tooltip = showingDataLoss
? DataLossDescriptions.GetRowTooltip(kind)
: string.Empty;
FontStyle fontStyle = showingDataLoss
? FontStyle.Normal
: FontStyle.Italic;
leftAnnotation.tooltip = tooltip;
leftAnnotation.style.unityFontStyleAndWeight = fontStyle;
rightAnnotation.tooltip = tooltip;
rightAnnotation.style.unityFontStyleAndWeight = fontStyle;
}
// Reparenting and sibling reorder are mutually exclusive on the same
// GameObject — see ParentChangeDiffs / SiblingReorderDiffs.
// Reparent annotation is per-side (prior location on src, new location
// on dst); sibling reorder uses the same delta-based annotation on both.
//
// Data-loss takes precedence over reorder/reparent text — the
// user needs to know the diff is incomplete before they reason
// about position changes. The two rarely co-occur in practice
// (broken objects don't typically get reordered alongside their
// breakage). The annotation slot then carries a short warning
// glyph and the full description goes on the Label's tooltip
// (set in Bind after ConfigurePanel runs).
static string BuildLeftAnnotation(ObjectDiff objDiff)
{
if (GetEffectiveDataLoss(objDiff) != DataLossKind.None)
return DATA_LOSS_GLYPH;
if (objDiff.HasParentChange())
return BuildParentLocationAnnotation(objDiff.SrcParent, isDst: false);
return BuildPositionAnnotation(objDiff.PositionDelta);
}
static string BuildRightAnnotation(ObjectDiff objDiff)
{
if (GetEffectiveDataLoss(objDiff) != DataLossKind.None)
return DATA_LOSS_GLYPH;
if (objDiff.HasParentChange())
return BuildParentLocationAnnotation(objDiff.DstParent, isDst: true);
return BuildPositionAnnotation(objDiff.PositionDelta);
}
// Returns this row's own DataLoss when set, otherwise the worst
// DataLoss across nested ComponentDiffs. This lets a collapsed
// GameObject container surface the warning when any nested
// component is broken — the user shouldn't have to expand every
// row to discover where data was dropped.
static DataLossKind GetEffectiveDataLoss(ObjectDiff objDiff)
{
if (objDiff.DataLoss != DataLossKind.None)
return objDiff.DataLoss;
if (objDiff.ComponentDiffs == null)
return DataLossKind.None;
DataLossKind worst = DataLossKind.None;
foreach (ObjectDiff comp in objDiff.ComponentDiffs)
{
if ((int)comp.DataLoss > (int)worst)
worst = comp.DataLoss;
}
return worst;
}
static string BuildParentLocationAnnotation(
UnityEngine.GameObject parent, bool isDst)
{
string parentLabel = parent == null
? PlasticLocalization.Name.DiffSceneRoot.GetString()
: "'" + parent.name + "'";
return isDst
? PlasticLocalization.Name.DiffMovedToLocation.GetString(parentLabel)
: PlasticLocalization.Name.DiffInLocation.GetString(parentLabel);
}
static bool IsContainer(ObjectDiff objDiff)
{
return objDiff.DiffType == DiffType.Unchanged
&& objDiff.ComponentDiffs != null
&& objDiff.ComponentDiffs.Count > 0;
}
static string BuildPositionAnnotation(int delta)
{
if (delta == 0)
return null;
int abs = delta < 0 ? -delta : delta;
if (delta < 0)
{
return abs == 1
? PlasticLocalization.Name.DiffMovedUpOnePosition.GetString(abs)
: PlasticLocalization.Name.DiffMovedUpPositions.GetString(abs);
}
return abs == 1
? PlasticLocalization.Name.DiffMovedDownOnePosition.GetString(abs)
: PlasticLocalization.Name.DiffMovedDownPositions.GetString(abs);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mLeftPanel = HeaderRow.BuildPanel(
out mLeftContent, out mLeftArrow, out mLeftIcon,
out mLeftLabel, out mLeftAnnotation);
mLeftPanel.RegisterCallback<MouseEnterEvent>(OnLeftPanelMouseEnter);
mLeftPanel.RegisterCallback<MouseLeaveEvent>(OnLeftPanelMouseLeave);
Add(mLeftPanel);
mRightPanel = HeaderRow.BuildPanel(
out mRightContent, out mRightArrow, out mRightIcon,
out mRightLabel, out mRightAnnotation);
mRightPanel.RegisterCallback<MouseEnterEvent>(OnRightPanelMouseEnter);
mRightPanel.RegisterCallback<MouseLeaveEvent>(OnRightPanelMouseLeave);
Add(mRightPanel);
}
void OnLeftPanelMouseEnter(MouseEnterEvent evt)
{
HeaderRow.SetHovered(
ref mbIsLeftHovered, mHasSrc, mLeftPanel, bIsHovered: true);
}
void OnLeftPanelMouseLeave(MouseLeaveEvent evt)
{
HeaderRow.SetHovered(
ref mbIsLeftHovered, mHasSrc, mLeftPanel, bIsHovered: false);
}
void OnRightPanelMouseEnter(MouseEnterEvent evt)
{
HeaderRow.SetHovered(
ref mbIsRightHovered, mHasDst, mRightPanel, bIsHovered: true);
}
void OnRightPanelMouseLeave(MouseLeaveEvent evt)
{
HeaderRow.SetHovered(
ref mbIsRightHovered, mHasDst, mRightPanel, bIsHovered: false);
}
VisualElement mLeftPanel;
VisualElement mLeftContent;
Label mLeftArrow;
Image mLeftIcon;
Label mLeftLabel;
Label mLeftAnnotation;
VisualElement mRightPanel;
VisualElement mRightContent;
Label mRightArrow;
Image mRightIcon;
Label mRightLabel;
Label mRightAnnotation;
bool mHasSrc;
bool mHasDst;
bool mbIsLeftHovered;
bool mbIsRightHovered;
const string DATA_LOSS_GLYPH = "⚠";
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e5cbdaec4d63a4013ad3089e2435b53f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,137 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using Unity.PlasticSCM.Editor.UI;
using UnityEngine;
using UnityEngine.UIElements;
using Unity.PlasticSCM.Editor.Diff.Asset.Common;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffPropertyRow : VisualElement
{
internal DiffPropertyRow()
{
CreateGUI();
}
internal void BindSpacer(PropertyDiff propDiff, int indentLevel)
{
DiffType diffType = propDiff.DiffType;
bool hasSrc = diffType != DiffType.Added;
bool hasDst = diffType != DiffType.Removed;
float padding = PropertyRow.BASE_PADDING_LEFT
+ indentLevel * PropertyRow.INDENT_PX;
Color gutterColor = DiffGutter.GetColor(diffType);
DiffGutter.Apply(mLeftPanel, hasSrc ? gutterColor : Color.clear, padding);
DiffGutter.Apply(mRightPanel, hasDst ? gutterColor : Color.clear, padding);
mLeftPanel.style.backgroundColor = Color.clear;
mRightPanel.style.backgroundColor = Color.clear;
mLeftLabel.style.display = DisplayStyle.None;
mRightLabel.style.display = DisplayStyle.None;
mLeftValue.style.display = DisplayStyle.None;
mRightValue.style.display = DisplayStyle.None;
pickingMode = PickingMode.Ignore;
mLeftPanel.pickingMode = PickingMode.Ignore;
mRightPanel.pickingMode = PickingMode.Ignore;
}
internal void Bind(
PropertyDiff propDiff,
string searchFilter,
int indentLevel)
{
DiffType diffType = propDiff.DiffType;
bool hasSrc = diffType != DiffType.Added;
bool hasDst = diffType != DiffType.Removed;
float padding = PropertyRow.BASE_PADDING_LEFT
+ indentLevel * PropertyRow.INDENT_PX;
Color gutterColor = DiffGutter.GetColor(diffType);
DiffGutter.Apply(mLeftPanel, hasSrc ? gutterColor : Color.clear, padding);
DiffGutter.Apply(mRightPanel, hasDst ? gutterColor : Color.clear, padding);
ApplyPanelBackground(mLeftPanel, diffType, isLeftSide: true);
ApplyPanelBackground(mRightPanel, diffType, isLeftSide: false);
pickingMode = PickingMode.Position;
mLeftPanel.pickingMode = PickingMode.Position;
mRightPanel.pickingMode = PickingMode.Position;
string label = propDiff.DisplayName ?? propDiff.Path;
bool hasSearch = !string.IsNullOrEmpty(searchFilter);
string displayLabel = hasSearch
? SearchHighlight.Apply(label, searchFilter)
: label;
PropertyRow.ConfigureNameLabel(
mLeftLabel, hasSrc, hasSearch, displayLabel, propDiff.Path);
PropertyRow.ConfigureNameLabel(
mRightLabel, hasDst, hasSearch, displayLabel, propDiff.Path);
mLeftValue.style.display = hasSrc
? DisplayStyle.Flex : DisplayStyle.None;
mRightValue.style.display = hasDst
? DisplayStyle.Flex : DisplayStyle.None;
mLeftValue.SetData(
propDiff.SrcTag, propDiff.SrcValue, hasSrc,
hasDst ? propDiff.DstTag : null);
mRightValue.SetData(
propDiff.DstTag, propDiff.DstValue, hasDst,
hasSrc ? propDiff.SrcTag : null);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Row;
style.flexGrow = 1;
mLeftPanel = BuildPanel(out mLeftLabel, out mLeftValue);
Add(mLeftPanel);
mRightPanel = BuildPanel(out mRightLabel, out mRightValue);
Add(mRightPanel);
}
static VisualElement BuildPanel(
out Label nameLabel,
out DiffValueDisplay valueDisplay)
{
VisualElement panel = PropertyRow.BuildPanel(out nameLabel);
valueDisplay = new DiffValueDisplay();
panel.Add(valueDisplay);
return panel;
}
static void ApplyPanelBackground(
VisualElement panel,
DiffType diffType,
bool isLeftSide)
{
bool isEmpty =
(diffType == DiffType.Added && isLeftSide) ||
(diffType == DiffType.Removed && !isLeftSide);
panel.style.backgroundColor = isEmpty
? UnityStyles.Colors.Diff.AssetDiff.EmptyPanelBackground
: UnityStyles.Colors.Diff.AssetDiff.PropertyRowBackground;
}
VisualElement mLeftPanel;
Label mLeftLabel;
DiffValueDisplay mLeftValue;
VisualElement mRightPanel;
Label mRightLabel;
DiffValueDisplay mRightValue;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0beb995ef89b74dd4880e1d7c7b342f9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,59 @@
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal enum DiffRowKind : byte
{
ObjectHeader,
ComponentHeader,
ContainerHeader,
PropertyDiff
}
internal readonly struct DiffRow
{
internal readonly DiffRowKind Kind;
internal readonly ObjectDiff ObjectDiff;
internal readonly PropertyDiff PropertyDiff;
internal readonly int IndentLevel;
internal readonly bool IsSpacer;
internal readonly string GroupKey;
internal readonly string GroupDisplayName;
internal readonly DiffType GroupDiffType;
internal DiffRow(
DiffRowKind kind,
ObjectDiff objectDiff,
PropertyDiff propertyDiff,
int indentLevel = 0,
bool isSpacer = false)
{
Kind = kind;
ObjectDiff = objectDiff;
PropertyDiff = propertyDiff;
IndentLevel = indentLevel;
IsSpacer = isSpacer;
GroupKey = null;
GroupDisplayName = null;
GroupDiffType = DiffType.Unchanged;
}
internal DiffRow(
DiffRowKind kind,
ObjectDiff objectDiff,
string groupKey,
string groupDisplayName,
DiffType groupDiffType,
int indentLevel)
{
Kind = kind;
ObjectDiff = objectDiff;
PropertyDiff = null;
IndentLevel = indentLevel;
IsSpacer = false;
GroupKey = groupKey;
GroupDisplayName = groupDisplayName;
GroupDiffType = groupDiffType;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 15065be9d58284ff3a0be3d0e4527920
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,144 @@
using System;
using Unity.PlasticSCM.Editor.Diff.Asset.Diff.Property;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffRowElement : VisualElement
{
internal const float ROW_HEIGHT = 22f;
internal DiffRowElement(
Action<ObjectDiff> toggleObjectCallback,
Action<string> toggleGroupCallback)
{
mToggleObjectCallback = toggleObjectCallback;
mToggleGroupCallback = toggleGroupCallback;
CreateGUI();
RegisterCallback<ClickEvent>(OnClicked);
}
internal void BindHeader(
ObjectDiff objDiff,
bool isExpanded,
string searchFilter,
int indentLevel = 0)
{
mBoundObjectDiff = objDiff;
mBoundGroupKey = null;
mBoundKind = BoundKind.ObjectHeader;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.Flex;
mPropertyRow.style.display = DisplayStyle.None;
mGroupHeaderRow.style.display = DisplayStyle.None;
mHeaderRow.Bind(objDiff, isExpanded, searchFilter, indentLevel);
}
internal void BindGroupHeader(
string label,
DiffType groupDiffType,
string groupKey,
bool isExpanded,
string searchFilter,
int indentLevel)
{
mBoundObjectDiff = null;
mBoundGroupKey = groupKey;
mBoundKind = BoundKind.GroupHeader;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.None;
mGroupHeaderRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.Bind(
label, groupDiffType, isExpanded, searchFilter, indentLevel);
}
internal void BindProperty(
PropertyDiff propDiff,
string searchFilter,
int indentLevel = 0)
{
mBoundObjectDiff = null;
mBoundGroupKey = null;
mBoundKind = BoundKind.PropertyRow;
pickingMode = PickingMode.Position;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.Bind(propDiff, searchFilter, indentLevel);
}
internal void BindSpacer(PropertyDiff propDiff, int indentLevel)
{
mBoundObjectDiff = null;
mBoundGroupKey = null;
mBoundKind = BoundKind.PropertyRow;
pickingMode = PickingMode.Ignore;
mHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.style.display = DisplayStyle.Flex;
mGroupHeaderRow.style.display = DisplayStyle.None;
mPropertyRow.BindSpacer(propDiff, indentLevel);
}
void CreateGUI()
{
style.flexDirection = FlexDirection.Column;
style.minHeight = ROW_HEIGHT;
style.overflow = Overflow.Visible;
mHeaderRow = new DiffHeaderRow();
Add(mHeaderRow);
mGroupHeaderRow = new GroupHeaderRow();
Add(mGroupHeaderRow);
mPropertyRow = new DiffPropertyRow();
Add(mPropertyRow);
}
void OnClicked(ClickEvent evt)
{
switch (mBoundKind)
{
case BoundKind.ObjectHeader:
if (mBoundObjectDiff != null)
mToggleObjectCallback?.Invoke(mBoundObjectDiff);
return;
case BoundKind.GroupHeader:
if (mBoundGroupKey != null)
mToggleGroupCallback?.Invoke(mBoundGroupKey);
return;
}
}
readonly Action<ObjectDiff> mToggleObjectCallback;
readonly Action<string> mToggleGroupCallback;
DiffHeaderRow mHeaderRow;
GroupHeaderRow mGroupHeaderRow;
DiffPropertyRow mPropertyRow;
ObjectDiff mBoundObjectDiff;
string mBoundGroupKey;
BoundKind mBoundKind;
enum BoundKind : byte
{
None,
ObjectHeader,
GroupHeader,
PropertyRow
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f868eac0bc3ab44cfbc98c7099fce8cb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,239 @@
using System;
using System.Collections.Generic;
using PlasticGui;
using Unity.PlasticSCM.Editor.UI;
using Unity.PlasticSCM.Editor.UI.UIElements;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff
{
internal class DiffToolbarPanel : VisualElement
{
internal DiffToolbarPanel(
Action<DiffFilter> setDiffFilter,
Action<string> filterChanged,
Action expandAll,
Action collapseAll,
Action<HashSet<string>> setGameObjectFilter,
Action<HashSet<string>> setTypeFilter)
{
mSetDiffFilter = setDiffFilter;
mFilterChanged = filterChanged;
mExpandAll = expandAll;
mCollapseAll = collapseAll;
mSetGameObjectFilter = setGameObjectFilter;
mSetTypeFilter = setTypeFilter;
CreateGUI();
mDelayedFilterAction = new DelayedActionBySecondsRunner(
DelayedSearchChanged, UnityConstants.SEARCH_DELAYED_INPUT_ACTION_INTERVAL);
}
internal void Dispose()
{
mFilterAllButton.UnregisterValueChangedCallback(
OnFilterAllToggleChanged);
mFilterModifiedButton.UnregisterValueChangedCallback(
OnFilterModifiedToggleChanged);
mFilterAddedButton.UnregisterValueChangedCallback(
OnFilterAddedToggleChanged);
mFilterRemovedButton.UnregisterValueChangedCallback(
OnFilterRemovedToggleChanged);
mSearchField.UnregisterValueChangedCallback(OnSearchFieldValueChanged);
mGameObjectDropdown.SelectionChanged -= OnGameObjectSelectionChanged;
mTypeDropdown.SelectionChanged -= OnTypeSelectionChanged;
}
internal void UpdateAvailableFilters(
IList<MultiSelectDropdownItem> gameObjects,
IList<MultiSelectDropdownItem> types,
bool show)
{
DisplayStyle display = show ? DisplayStyle.Flex : DisplayStyle.None;
mGameObjectDropdown.style.display = display;
mTypeDropdown.style.display = display;
if (!show)
return;
mGameObjectDropdown.SetItems(gameObjects);
mTypeDropdown.SetItems(types);
}
internal void UpdateFilterButtons(
int modified,
int added,
int removed,
DiffFilter diffFilter)
{
int total = modified + added + removed;
mFilterAllButton.text =
$"{PlasticLocalization.Name.DiffFilterAll.GetString()} ({total})";
mFilterModifiedButton.text =
$"{PlasticLocalization.Name.DiffFilterModified.GetString()} ({modified})";
mFilterAddedButton.text =
$"{PlasticLocalization.Name.DiffFilterAdded.GetString()} ({added})";
mFilterRemovedButton.text =
$"{PlasticLocalization.Name.DiffFilterRemoved.GetString()} ({removed})";
mFilterAllButton.SetEnabled(total > 0);
mFilterModifiedButton.SetEnabled(modified > 0);
mFilterAddedButton.SetEnabled(added > 0);
mFilterRemovedButton.SetEnabled(removed > 0);
mFilterAllButton.SetValueWithoutNotify(diffFilter == DiffFilter.All);
mFilterModifiedButton.SetValueWithoutNotify(diffFilter == DiffFilter.Modified);
mFilterAddedButton.SetValueWithoutNotify(diffFilter == DiffFilter.Added);
mFilterRemovedButton.SetValueWithoutNotify(diffFilter == DiffFilter.Removed);
}
void DelayedSearchChanged()
{
mFilterChanged(mSearchField.value);
}
void CreateGUI()
{
UnityEditor.UIElements.Toolbar toolbar = ControlBuilder.Toolbar.Create();
mFilterAllButton = ControlBuilder.Toolbar.CreateToggle(
PlasticLocalization.Name.DiffFilterAll.GetString(),
PlasticLocalization.Name.DiffFilterAllTooltip.GetString());
mFilterAllButton.RegisterValueChangedCallback(
OnFilterAllToggleChanged);
mFilterModifiedButton = ControlBuilder.Toolbar.CreateToggle(
PlasticLocalization.Name.DiffFilterModified.GetString(),
PlasticLocalization.Name.DiffFilterModifiedTooltip.GetString());
mFilterModifiedButton.RegisterValueChangedCallback(
OnFilterModifiedToggleChanged);
mFilterAddedButton = ControlBuilder.Toolbar.CreateToggle(
PlasticLocalization.Name.DiffFilterAdded.GetString(),
PlasticLocalization.Name.DiffFilterAddedTooltip.GetString());
mFilterAddedButton.RegisterValueChangedCallback(
OnFilterAddedToggleChanged);
mFilterRemovedButton = ControlBuilder.Toolbar.CreateToggleLeft(
PlasticLocalization.Name.DiffFilterRemoved.GetString(),
PlasticLocalization.Name.DiffFilterRemovedTooltip.GetString());
mFilterRemovedButton.RegisterValueChangedCallback(
OnFilterRemovedToggleChanged);
mGameObjectDropdown = ControlBuilder.Toolbar.CreateMultiSelectDropdownLeft(
PlasticLocalization.Name.DiffGameObjectFilterLabel.GetString());
mGameObjectDropdown.SelectionChanged += OnGameObjectSelectionChanged;
mGameObjectDropdown.style.display = DisplayStyle.None;
mTypeDropdown = ControlBuilder.Toolbar.CreateMultiSelectDropdown(
PlasticLocalization.Name.DiffTypeFilterLabel.GetString());
mTypeDropdown.SelectionChanged += OnTypeSelectionChanged;
mTypeDropdown.style.display = DisplayStyle.None;
mSearchField = ControlBuilder.Toolbar.CreateSearchField();
mSearchField.RegisterValueChangedCallback(OnSearchFieldValueChanged);
toolbar.Add(mFilterAllButton);
toolbar.Add(mFilterModifiedButton);
toolbar.Add(mFilterAddedButton);
toolbar.Add(mFilterRemovedButton);
toolbar.Add(mGameObjectDropdown);
toolbar.Add(mTypeDropdown);
VisualElement spacer = new VisualElement();
spacer.style.flexGrow = 1;
toolbar.Add(spacer);
mExpandAllButton = ControlBuilder.Toolbar.CreateButtonLeft(
PlasticLocalization.Name.DiffExpandAllButton.GetString(), mExpandAll);
toolbar.Add(mExpandAllButton);
mCollapseAllButton = ControlBuilder.Toolbar.CreateButton(
PlasticLocalization.Name.DiffCollapseAllButton.GetString(), mCollapseAll);
toolbar.Add(mCollapseAllButton);
toolbar.Add(mSearchField);
Add(toolbar);
}
void OnFilterAllToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.All);
}
void OnFilterModifiedToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.Modified);
}
void OnFilterAddedToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.Added);
}
void OnFilterRemovedToggleChanged(ChangeEvent<bool> evt)
{
if (!evt.newValue)
return;
mSetDiffFilter(DiffFilter.Removed);
}
void OnSearchFieldValueChanged(ChangeEvent<string> evt)
{
mDelayedFilterAction.Run();
}
void OnGameObjectSelectionChanged()
{
mSetGameObjectFilter(mGameObjectDropdown.Selected);
}
void OnTypeSelectionChanged()
{
mSetTypeFilter(mTypeDropdown.Selected);
}
readonly Action<DiffFilter> mSetDiffFilter;
readonly Action<string> mFilterChanged;
readonly Action mExpandAll;
readonly Action mCollapseAll;
readonly Action<HashSet<string>> mSetGameObjectFilter;
readonly Action<HashSet<string>> mSetTypeFilter;
readonly DelayedActionBySecondsRunner mDelayedFilterAction;
ToolbarToggle mFilterAllButton;
ToolbarToggle mFilterModifiedButton;
ToolbarToggle mFilterAddedButton;
ToolbarToggle mFilterRemovedButton;
ToolbarButton mExpandAllButton;
ToolbarButton mCollapseAllButton;
MultiSelectDropdown mGameObjectDropdown;
MultiSelectDropdown mTypeDropdown;
ToolbarSearchField mSearchField;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 694f4474a0854a2bab3e880bbcb004c6
timeCreated: 1778487152
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 9831c3a3f4a4645309f76e99ac9844c2
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,27 @@
using System.Collections.Generic;
namespace Unity.PlasticSCM.Editor.Diff.Asset.Diff.Filtering
{
internal static class ObjectDiffFilters
{
internal static bool PassesGameObjectFilter(
ObjectDiff diff, HashSet<string> selected)
{
if (selected == null)
return true;
string name = diff.GetObjectName();
return name != null && selected.Contains(name);
}
internal static bool PassesTypeFilter(
ObjectDiff diff, HashSet<string> selected)
{
if (selected == null)
return true;
string typeName = diff.GetTypeName();
return typeName != null && selected.Contains(typeName);
}
}
}

Some files were not shown because too many files have changed in this diff Show More