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,8 @@
fileFormatVersion: 2
guid: 936bea4b2545c4a4fad2e623b0f6371f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: cd9c8fc1c8d64d54ab1e22aae9678d84
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,27 @@
{
"name": "UnityEditor.UI.Common.Tests",
"rootNamespace": "",
"references": [
"Unity.TextMeshPro",
"Unity.TextMeshPro.Editor",
"UnityEditor.UI",
"UnityEngine.UI",
"UnityEngine.TestRunner",
"UnityEditor.TestRunner"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": false,
"overrideReferences": true,
"precompiledReferences": [
"nunit.framework.dll"
],
"autoReferenced": false,
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
],
"versionDefines": [],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 05242c3d99f24a74f99cc20369fcb344
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,83 @@
using System;
using System.Linq;
using System.Reflection;
using NUnit.Framework;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
using PackageInfo = UnityEditor.PackageManager.PackageInfo;
internal class VersionTests
{
static string GetHelpURLVersion<T>(string attributeName)
{
var customAttributes = typeof(T).GetCustomAttributes(false);
Assert.NotNull(customAttributes);
var urlAttribute = customAttributes.FirstOrDefault(attribute => attribute.GetType().Name == attributeName);
Assert.NotNull(urlAttribute);
var propertyInfo = GetProperty(urlAttribute.GetType(), "version", BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(propertyInfo);
var version = propertyInfo.GetValue(null) as string;
Assert.NotNull(version);
return version;
PropertyInfo GetProperty (Type type, string propertyName, BindingFlags bindingFlags)
{
var prop = type.GetProperty(propertyName, bindingFlags);
if (prop != null)
return prop;
else if (type.BaseType != null)
return GetProperty(type.BaseType, propertyName, bindingFlags);
return null;
}
}
struct Version
{
public int major;
public int minor;
public int patch;
public Version(string version)
{
major = minor = patch = 0;
var split = version.Split('.');
if (split.Length > 0) int.TryParse(split[0], out major);
if (split.Length > 1) int.TryParse(split[1], out minor);
if (split.Length > 2) int.TryParse(split[2], out patch);
}
public override string ToString()
{
return $"{major}.{minor}.{patch}";
}
public override bool Equals(object obj)
{
if (obj is Version other)
return major == other.major && minor == other.minor;
return false;
}
}
[Test]
public void CheckVersionParity()
{
var baseVersion = GetHelpURLVersion<RectTransform>("UIModuleHelpURL");
Assert.NotNull(baseVersion);
var uguiVersion = GetHelpURLVersion<Button>("UGUIHelpURL");
Assert.NotNull(uguiVersion);
var tmpVersion = GetHelpURLVersion<TextMeshProUGUI>("TMPHelpURL");
Assert.NotNull(tmpVersion);
var baseVersionNumber = new Version(baseVersion);
var uguiVersionNumber = new Version(uguiVersion);
var tmpVersionNumber = new Version(tmpVersion);
Assert.That(baseVersionNumber, Is.EqualTo(uguiVersionNumber).And.EqualTo(tmpVersionNumber));
var uguiPackageInfo = PackageInfo.FindForPackageName("com.unity.ugui");
Assert.NotNull(uguiPackageInfo);
var packageVersionNumber = new Version(uguiPackageInfo.version);
Assert.AreEqual(baseVersionNumber, packageVersionNumber);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 6370fe1d392924d45b0cfd255bf60d2a
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3ddaad49a7bcb4087b403f2225d54840
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,515 @@
using System.Threading;
using UnityEngine;
using UnityEditor;
using NUnit.Framework;
using UnityEngine.TestTools;
using UnityEngine.TextCore;
using UnityEngine.TextCore.LowLevel;
namespace TMPro
{
[Category("Text Parsing & Layout")]
[Ignore("Unstable tests // UUM-133195")]
internal class FontEngineTests
{
[OneTimeSetUp]
public void Setup()
{
// Check if "TextMesh Pro" folder is present in project
string folderPath = AssetDatabase.GUIDToAssetPath("f54d1bd14bd3ca042bd867b519fee8cc");
if (string.IsNullOrEmpty(folderPath))
{
// Import TMP Essential Resources and TMP Examples & Extras
TMP_PackageResourceImporter.ImportResources(true, true, false);
}
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans", "Regular")]
[TestCase("4beb055f07aaff244873dec698d0363e", "Roboto", "Bold")]
[TestCase("997a43b767814dd0a7642ec9b78cba41", "Anton", "Regular")]
public void CreateFontAsset_from_FilePath(string fontFileGUID, string familyName, string styleName)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
TMP_FontAsset fontAsset = TMP_FontAsset.CreateFontAsset(filePath, 0, 90, 9, GlyphRenderMode.SDFAA, 512, 512);
Assert.NotNull(fontAsset);
Assert.AreEqual(fontAsset.faceInfo.familyName, familyName);
Assert.AreEqual(fontAsset.faceInfo.styleName, styleName);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans", "Regular")]
[TestCase("4beb055f07aaff244873dec698d0363e", "Roboto", "Bold")]
[TestCase("997a43b767814dd0a7642ec9b78cba41", "Anton", "Regular")]
public void CreateFontAsset_from_FontObject(string fontFileGUID, string familyName, string styleName)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
Font font = AssetDatabase.LoadAssetAtPath<Font>(filePath);
TMP_FontAsset fontAsset = TMP_FontAsset.CreateFontAsset(font, 90, 9, GlyphRenderMode.SDFAA, 512, 512);
Assert.NotNull(fontAsset);
Assert.AreEqual(fontAsset.faceInfo.familyName, familyName);
Assert.AreEqual(fontAsset.faceInfo.styleName, styleName);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans", "Regular")]
public void TryAddCharacters_SanityCheck(string fontFileGUID, string familyName, string styleName)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
TMP_FontAsset fontAsset = TMP_FontAsset.CreateFontAsset(filePath, 0, 90, 9, GlyphRenderMode.SDFAA, 512, 512);
Assert.NotNull(fontAsset);
fontAsset.TryAddCharacters("abc");
Assert.IsTrue(fontAsset.HasCharacters("abc"));
}
// =============================================
// FONT ENGINE - OPENTYPE TESTS
// =============================================
#if TEXTCORE_FONT_ENGINE_1_5_OR_NEWER
[TestCase("e3265ab4bf004d28a9537516768c1c75", 1)]
[TestCase("4beb055f07aaff244873dec698d0363e", 623)]
[TestCase("24007ea0bd4d6b2418f4caf1b06e2cb4", 43)]
public void GetSingleSubstitutionRecords(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
if (FontEngine.LoadFontFace(filePath, 0, 0, out FontFaceHandle faceHandle) != FontEngineError.Success)
return;
UnityEngine.TextCore.LowLevel.SingleSubstitutionRecord[] records = FontEngine.GetAllSingleSubstitutionRecords(faceHandle);
if (records == null)
return;
Assert.AreEqual(recordCount, records.Length);
}
[TestCase("47a9b34e6f77bbd4d94f512d266bcd0c", 77)] // Inter - Regular
public void GetAlternateSubstitutionRecords(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
if (FontEngine.LoadFontFace(filePath, 0, 0, out FontFaceHandle faceHandle) != FontEngineError.Success)
return;
UnityEngine.TextCore.LowLevel.AlternateSubstitutionRecord[] records = FontEngine.GetAllAlternateSubstitutionRecords(faceHandle);
if (records == null)
return;
Assert.AreEqual(recordCount, records.Length);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", 184)]
[TestCase("4beb055f07aaff244873dec698d0363e", 177)]
[TestCase("c9f6d0e7bc8541498c9a4799ba184ede", 5)]
public void GetLigatures(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
if (FontEngine.LoadFontFace(filePath, 0, 0, out FontFaceHandle faceHandle) != FontEngineError.Success)
return;
UnityEngine.TextCore.LowLevel.LigatureSubstitutionRecord[] records = FontEngine.GetAllLigatureSubstitutionRecords(faceHandle);
if (records == null)
return;
Assert.AreEqual(recordCount, records.Length);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", 2016)]
[TestCase("4beb055f07aaff244873dec698d0363e", 70027)]
[TestCase("c9f6d0e7bc8541498c9a4799ba184ede", 1940)]
public void GetPairAdjustmentRecords(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
if (FontEngine.LoadFontFace(filePath, 0, 0, out FontFaceHandle faceHandle) != FontEngineError.Success)
return;
GlyphPairAdjustmentRecord[] records = FontEngine.GetAllPairAdjustmentRecords(faceHandle);
if (records == null)
return;
Assert.AreEqual(recordCount, records.Length);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", 8911)]
[TestCase("4beb055f07aaff244873dec698d0363e", 0)]
[TestCase("24007ea0bd4d6b2418f4caf1b06e2cb4", 432)]
public void GetMarkToBaseAdjustmentRecords(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
if (FontEngine.LoadFontFace(filePath, 0, 0, out FontFaceHandle faceHandle) != FontEngineError.Success)
return;
UnityEngine.TextCore.LowLevel.MarkToBaseAdjustmentRecord[] records = FontEngine.GetAllMarkToBaseAdjustmentRecords(faceHandle);
if (records == null)
return;
Assert.AreEqual(recordCount, records.Length);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", 0)]
[TestCase("4beb055f07aaff244873dec698d0363e", 0)]
[TestCase("24007ea0bd4d6b2418f4caf1b06e2cb4", 324)]
public void GetMarkToMarkAdjustmentRecords(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
if (FontEngine.LoadFontFace(filePath, 0, 0, out FontFaceHandle faceHandle) != FontEngineError.Success)
return;
UnityEngine.TextCore.LowLevel.MarkToMarkAdjustmentRecord[] records = FontEngine.GetAllMarkToMarkAdjustmentRecords(faceHandle);
if (records == null)
return;
Assert.AreEqual(recordCount, records.Length);
}
// GetOpenTypeFontFeatureList throws NotImplementedException with new FontEngine changes to support FontFeature (TEXTCORE_FONT_ENGINE_1_5_OR_NEWER)
/*
[TestCase("e3265ab4bf004d28a9537516768c1c75", 0)]
[TestCase("4beb055f07aaff244873dec698d0363e", 0)]
[TestCase("24007ea0bd4d6b2418f4caf1b06e2cb4", 324)]
[TestCase("47a9b34e6f77bbd4d94f512d266bcd0c", 324)]
[TestCase("d01f31227e1b4cd49bc293f44aab2253", 324)]
public void GetFontFeatureList(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
if (FontEngine.LoadFontFace(filePath) != FontEngineError.Success)
return;
OpenTypeFeature[] fontFeatureList = FontEngine.GetOpenTypeFontFeatureList();
if (fontFeatureList == null)
return;
Assert.AreEqual(recordCount, fontFeatureList.Length);
} */
#endif
}
#if TEXTCORE_FONT_ENGINE_1_6_OR_NEWER
[Category("Text Parsing & Layout")]
internal class FontFaceHandleTests
{
[OneTimeSetUp]
public void Setup()
{
// These tests load fonts from the TMP Essential Resources and Examples & Extras. Import
// whichever is missing; the prebuild step may already have imported the essentials alone.
bool importEssentials = string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath("f54d1bd14bd3ca042bd867b519fee8cc"));
bool importExamples = string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath("4beb055f07aaff244873dec698d0363e"));
if (importEssentials || importExamples)
TMP_PackageResourceImporter.ImportResources(importEssentials, importExamples, false);
// If the font files these tests depend on still cannot be resolved (resources unavailable
// in this environment), skip the whole fixture rather than failing — but log why so the
// skip is visible in the test output.
if (string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath("e3265ab4bf004d28a9537516768c1c75")))
{
Debug.LogWarning("FontFaceHandleTests skipped: required TMP font resources are not present in the project.");
Assert.Ignore("Required TMP font resources are not present; skipping FontFaceHandle tests.");
}
}
[TestCase("e3265ab4bf004d28a9537516768c1c75")]
[TestCase("4beb055f07aaff244873dec698d0363e")]
public void LoadFontFace_ReturnsValidHandle(string fontFileGUID)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
FontEngineError error = FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle faceHandle);
Assert.AreEqual(FontEngineError.Success, error);
Assert.IsTrue(faceHandle.IsValid);
}
[Test]
public void LoadFontFace_WithInvalidPath_ReturnsErrorAndDefaultHandle()
{
FontEngineError error = FontEngine.LoadFontFace("invalid/path/does_not_exist.ttf", 90, 0, out FontFaceHandle faceHandle);
Assert.AreNotEqual(FontEngineError.Success, error);
Assert.IsFalse(faceHandle.IsValid);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans", "Regular")]
[TestCase("4beb055f07aaff244873dec698d0363e", "Roboto", "Bold")]
public void GetFaceInfo_via_Handle_MatchesGlobalGetFaceInfo(string fontFileGUID, string familyName, string styleName)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
FontEngineError error = FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle faceHandle);
Assert.AreEqual(FontEngineError.Success, error);
FaceInfo infoViaHandle = FontEngine.GetFaceInfo(faceHandle);
FaceInfo infoGlobal = FontEngine.GetFaceInfo();
Assert.AreEqual(familyName, infoViaHandle.familyName);
Assert.AreEqual(styleName, infoViaHandle.styleName);
Assert.AreEqual(infoGlobal.familyName, infoViaHandle.familyName);
Assert.AreEqual(infoGlobal.pointSize, infoViaHandle.pointSize);
}
// Loads two fonts, stashes their handles, then uses each handle to restore the correct face
// without a fresh LoadFontFace call — the core correctness guarantee of FontFaceHandle.
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans", "4beb055f07aaff244873dec698d0363e", "Roboto")]
public void FontFaceHandle_RestoresCorrectFace(string guidA, string familyA, string guidB, string familyB)
{
string pathA = AssetDatabase.GUIDToAssetPath(guidA);
string pathB = AssetDatabase.GUIDToAssetPath(guidB);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(pathA, 90, 0, out FontFaceHandle handleA));
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(pathB, 72, 0, out FontFaceHandle handleB));
// Active face is now B — restore A via its handle.
FaceInfo infoA = FontEngine.GetFaceInfo(handleA);
Assert.AreEqual(familyA, infoA.familyName);
Assert.AreEqual(90, infoA.pointSize);
// Restore B via its handle.
FaceInfo infoB = FontEngine.GetFaceInfo(handleB);
Assert.AreEqual(familyB, infoB.familyName);
Assert.AreEqual(72, infoB.pointSize);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75", 2016)]
[TestCase("4beb055f07aaff244873dec698d0363e", 70027)]
public void GetPairAdjustmentRecords_via_Handle(string fontFileGUID, int recordCount)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
FontEngineError error = FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle faceHandle);
Assert.AreEqual(FontEngineError.Success, error);
GlyphPairAdjustmentRecord[] records = FontEngine.GetAllPairAdjustmentRecords(faceHandle);
Assert.IsNotNull(records);
Assert.AreEqual(recordCount, records.Length);
}
// Exercises the single-pair GPOS lookup whose loop previously used end() as its condition
// (iterating past the end of the records vector) and indexed the cached map via operator[]
// (default-inserting a missing key). Derives a real pair from the font's own records, then
// probes a first glyph against an impossible partner to drive the no-match path that ran
// past the end of the vector.
[TestCase("e3265ab4bf004d28a9537516768c1c75")] // Liberation Sans (has kerning)
public void GetPairAdjustmentRecord_via_Handle(string fontFileGUID)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle faceHandle));
GlyphPairAdjustmentRecord[] all = FontEngine.GetAllPairAdjustmentRecords(faceHandle);
Assert.IsNotNull(all);
Assert.Greater(all.Length, 0);
// A real (first, second) pair taken from the font's own data must resolve to itself.
uint first = all[0].firstAdjustmentRecord.glyphIndex;
uint second = all[0].secondAdjustmentRecord.glyphIndex;
GlyphPairAdjustmentRecord match = FontEngine.GetPairAdjustmentRecord(faceHandle, first, second);
Assert.AreEqual(first, match.firstAdjustmentRecord.glyphIndex);
Assert.AreEqual(second, match.secondAdjustmentRecord.glyphIndex);
// A first glyph that has records, paired with an impossible partner, must scan to the end
// and return an empty record rather than reading past it.
GlyphPairAdjustmentRecord noMatch = FontEngine.GetPairAdjustmentRecord(faceHandle, first, 0xFFFFFFFE);
Assert.AreEqual(0u, noMatch.secondAdjustmentRecord.glyphIndex);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75")]
public void UnloadFontFace_via_Handle_InvalidatesHandle(string fontFileGUID)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle faceHandle));
Assert.IsTrue(faceHandle.IsValid);
Assert.AreEqual(FontEngineError.Success, FontEngine.UnloadFontFace(faceHandle));
// After unloading, operations using the stale handle should fail with InvalidFontFaceHandle.
// The native layer logs a warning when it cannot resolve the stale handle — that is expected here.
LogAssert.Expect(LogType.Warning, "FontEngine: Font face handle no longer resolves to a cached font face.");
FontEngineError result = FontEngine.SetFaceSize(ref faceHandle, 90);
Assert.AreEqual(FontEngineError.Invalid_FontFaceHandle, result);
}
[TestCase("e3265ab4bf004d28a9537516768c1c75")]
public void StaleHandle_OperationsReturnGracefully(string fontFileGUID)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle faceHandle));
Assert.AreEqual(FontEngineError.Success, FontEngine.UnloadFontFace(faceHandle));
// GetFaceInfo — returns a zeroed FaceInfo rather than throwing.
LogAssert.Expect(LogType.Warning, "FontEngine: Font face handle no longer resolves to a cached font face.");
FaceInfo faceInfo = FontEngine.GetFaceInfo(faceHandle);
Assert.AreEqual(0, faceInfo.pointSize);
// TryGetGlyphIndex — returns false rather than throwing.
LogAssert.Expect(LogType.Warning, "FontEngine: Font face handle no longer resolves to a cached font face.");
bool found = FontEngine.TryGetGlyphIndex(faceHandle, 65, out uint glyphIndex);
Assert.IsFalse(found);
Assert.AreEqual(0u, glyphIndex);
// GetGlyphIndex — returns 0 rather than throwing.
LogAssert.Expect(LogType.Warning, "FontEngine: Font face handle no longer resolves to a cached font face.");
uint index = FontEngine.GetGlyphIndex(faceHandle, 65);
Assert.AreEqual(0u, index);
}
// A scalable font requested at two different point sizes resolves to the SAME cached FT_Face
// (MakeFontID excludes pixel size for scalable fonts), so both handles share one face — and
// one per-face lock. Each handle must still operate at, and report, its own size: the handle
// path resolves the face locally and re-applies the requested size under the lock rather than
// relying on whatever size the previous caller left on the shared face.
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans")]
public void SameScalableFont_DifferentSizes_TrackSizePerHandle(string fontFileGUID, string familyName)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle handle90));
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(filePath, 30, 0, out FontFaceHandle handle30));
// Interleave repeatedly; each handle must re-assert its own size every time.
for (int i = 0; i < 4; i++)
{
FaceInfo info90 = FontEngine.GetFaceInfo(handle90);
Assert.AreEqual(familyName, info90.familyName);
Assert.AreEqual(90, info90.pointSize, "handle90 should report size 90 regardless of interleaving");
FaceInfo info30 = FontEngine.GetFaceInfo(handle30);
Assert.AreEqual(familyName, info30.familyName);
Assert.AreEqual(30, info30.pointSize, "handle30 should report size 30 regardless of interleaving");
}
}
// Two distinct faces accessed concurrently must not corrupt each other: with face-threading
// the handle path never touches a shared global current-face, so each thread keeps seeing its
// own font/size. (Distinct FT_Faces are independently safe per the FreeType contract.)
// Faces are loaded on the main thread up front (face creation is not yet concurrency-safe);
// the workers only read through their already-valid handles, which the per-face lock guards.
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans", "4beb055f07aaff244873dec698d0363e", "Roboto")]
public void ConcurrentHandleAccess_DistinctFaces_RemainCorrect(string guidA, string familyA, string guidB, string familyB)
{
string pathA = AssetDatabase.GUIDToAssetPath(guidA);
string pathB = AssetDatabase.GUIDToAssetPath(guidB);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(pathA, 90, 0, out FontFaceHandle handleA));
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(pathB, 72, 0, out FontFaceHandle handleB));
const int iterations = 200;
string failureA = null;
string failureB = null;
var tA = new Thread(() => { failureA = HammerFaceInfo(handleA, familyA, 90, iterations); });
var tB = new Thread(() => { failureB = HammerFaceInfo(handleB, familyB, 72, iterations); });
tA.Start();
tB.Start();
tA.Join();
tB.Join();
Assert.IsNull(failureA, failureA);
Assert.IsNull(failureB, failureB);
}
// Two handles to the SAME scalable font at different sizes contend on one shared FT_Face.
// The per-face lock plus per-handle size re-application must keep each thread's view at its
// own size; without the lock the threads would stomp the shared face's active size and read
// each other's metrics.
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans")]
public void ConcurrentHandleAccess_SameFontDifferentSizes_RemainCorrect(string fontFileGUID, string familyName)
{
string filePath = AssetDatabase.GUIDToAssetPath(fontFileGUID);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(filePath, 90, 0, out FontFaceHandle handle90));
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(filePath, 30, 0, out FontFaceHandle handle30));
const int iterations = 200;
string failure90 = null;
string failure30 = null;
var t90 = new Thread(() => { failure90 = HammerFaceInfo(handle90, familyName, 90, iterations); });
var t30 = new Thread(() => { failure30 = HammerFaceInfo(handle30, familyName, 30, iterations); });
t90.Start();
t30.Start();
t90.Join();
t30.Join();
Assert.IsNull(failure90, failure90);
Assert.IsNull(failure30, failure30);
}
// Exercises FontFaceCacheLock: a worker thread repeatedly resolves a stable handle while the
// main thread churns the font face cache by loading and unloading a DIFFERENT face (insert /
// erase, and the rehash they can trigger). Without the cache lock, the worker's lookup inside
// ResolveFaceLocked would race the main-thread structural mutation of the shared cache. The
// stable face is never unloaded, so the worker must keep reading its correct family.
[TestCase("e3265ab4bf004d28a9537516768c1c75", "Liberation Sans", "4beb055f07aaff244873dec698d0363e")]
public void ConcurrentResolve_WhileCacheChurns_RemainsStable(string stableGuid, string stableFamily, string churnGuid)
{
string stablePath = AssetDatabase.GUIDToAssetPath(stableGuid);
string churnPath = AssetDatabase.GUIDToAssetPath(churnGuid);
Assert.AreEqual(FontEngineError.Success, FontEngine.LoadFontFace(stablePath, 90, 0, out FontFaceHandle stableHandle));
const int iterations = 200;
string failure = null;
var reader = new Thread(() =>
{
for (int i = 0; i < iterations && failure == null; i++)
{
FaceInfo info = FontEngine.GetFaceInfo(stableHandle);
if (info.familyName != stableFamily)
{
failure = $"Expected {stableFamily}, got '{info.familyName}' on iteration {i}";
return;
}
}
});
reader.Start();
// Main-thread cache churn: load + unload another face repeatedly (writers take the cache lock).
for (int i = 0; i < iterations; i++)
{
if (FontEngine.LoadFontFace(churnPath, 72, 0, out FontFaceHandle churnHandle) == FontEngineError.Success)
FontEngine.UnloadFontFace(churnHandle);
}
reader.Join();
Assert.IsNull(failure, failure);
}
// Repeatedly resolves the handle and checks the face reports the expected family/size.
// Returns a description of the first mismatch, or null on success (asserted on the main
// thread after Join — NUnit assertions don't propagate from worker threads).
static string HammerFaceInfo(FontFaceHandle handle, string expectedFamily, int expectedSize, int iterations)
{
for (int i = 0; i < iterations; i++)
{
FaceInfo info = FontEngine.GetFaceInfo(handle);
if (info.familyName != expectedFamily || info.pointSize != expectedSize)
return $"Expected {expectedFamily}@{expectedSize}, got '{info.familyName}'@{info.pointSize} on iteration {i}";
}
return null;
}
}
#endif
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ec4b2559effa72e42a09339d71efef3d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,323 @@
using System.Collections.Generic;
using System.IO;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TextCore;
using Object = UnityEngine.Object;
namespace TMPro
{
/// <summary>
/// Coverage for the source string mapping that SetArraySizes writes into
/// TMP_CharacterInfo.index and TMP_CharacterInfo.stringLength when several code points are
/// folded into a single rendered character - a "cluster". Two constructs produce one:
/// a base character followed by a variation selector, and a ligature.
///
/// The regression these guard against: the VARIATION SELECTOR and LIGATURES blocks advance
/// the text processing index past the elements they consume, and index / stringLength used
/// to be read from textProcessingArray[i] *after* that advance. A cluster therefore
/// reported the span of its LAST consumed element instead of the span of the whole cluster,
/// so index pointed into the middle of the cluster. TMP_InputField derives every caret
/// position and every delete range from those two fields, which is why the first Backspace
/// after typing an Ideographic Variation Sequence appeared to do nothing. The input field
/// half of this is covered by TMP_InputFieldClusterTests.
///
/// Both renderers carry a duplicated copy of SetArraySizes, so every case here runs against
/// TextMeshPro and TextMeshProUGUI.
/// </summary>
[Category("Text Parsing & Layout")]
internal class TMP_CharacterClusterTests: TMPTestSuiteWithEssentialResources
{
// U+FE0F VARIATION SELECTOR-16. A BMP selector: one UTF-16 code unit.
const string k_VariationSelector16 = "\uFE0F";
// U+E0100 VARIATION SELECTOR-17, the first Ideographic Variation Sequence selector.
// It lives in plane 14, so it is encoded as a surrogate pair: two UTF-16 code units.
// This is the construct from the original bug report.
const string k_VariationSelector17 = "\U000E0100";
// U+1F600 GRINNING FACE. A plain surrogate pair with no variation selector, used as the
// regression guard for characters the cluster accounting must leave alone.
const string k_AstralCharacter = "\U0001F600";
// Copy of the default font asset carrying a synthesized 'f' + 'i' ligature record, so the
// ligature case does not depend on which font the test project happens to ship.
TMP_FontAsset m_LigatureFontAsset;
TextMeshPro m_TextComponent;
TextMeshProUGUI m_TextComponentUGUI;
GameObject m_CanvasObject;
[OneTimeSetUp]
public void OneTimeSetUp()
{
GameObject textObject = new GameObject("Text Object");
m_TextComponent = textObject.AddComponent<TextMeshPro>();
m_TextComponent.fontSize = 18;
m_CanvasObject = new GameObject("Canvas Object");
m_CanvasObject.AddComponent<Canvas>();
GameObject textObjectUGUI = new GameObject("Text Object UGUI");
textObjectUGUI.transform.SetParent(m_CanvasObject.transform);
m_TextComponentUGUI = textObjectUGUI.AddComponent<TextMeshProUGUI>();
m_TextComponentUGUI.fontSize = 18;
// The default font asset is static and ships with no ligature records, so no font in this
// project can produce an 'fi' substitution. The accounting under test is pure span arithmetic
// and does not care whether the ligature glyph is the real one, so the fixture synthesizes a
// record on a private copy rather than depending on a font file that may not be imported.
m_LigatureFontAsset = Object.Instantiate(TMP_Settings.defaultFontAsset);
m_LigatureFontAsset.name = "Ligature Test Font Asset";
m_LigatureFontAsset.ReadFontAssetDefinition();
Assert.IsTrue(m_LigatureFontAsset.characterLookupTable.ContainsKey('f') &&
m_LigatureFontAsset.characterLookupTable.ContainsKey('i') &&
m_LigatureFontAsset.characterLookupTable.ContainsKey('x'),
"The default font asset must contain 'f', 'i' and 'x' for the ligature fixture.");
uint fGlyphIndex = m_LigatureFontAsset.characterLookupTable['f'].glyphIndex;
uint iGlyphIndex = m_LigatureFontAsset.characterLookupTable['i'].glyphIndex;
// Reusing a glyph already in the atlas keeps TryAddGlyphInternal on its early-out path
// (TMP_FontAsset.cs:2414), which is what lets a static font asset perform the substitution.
uint ligatureGlyphIndex = m_LigatureFontAsset.characterLookupTable['x'].glyphIndex;
m_LigatureFontAsset.fontFeatureTable.ligatureRecords.Add(new LigatureSubstitutionRecord
{
componentGlyphIDs = new[] { fGlyphIndex, iGlyphIndex },
ligatureGlyphID = ligatureGlyphIndex
});
m_LigatureFontAsset.InitializeLigatureSubstitutionLookupDictionary();
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (m_TextComponentUGUI != null)
{
Object.DestroyImmediate(m_TextComponentUGUI.gameObject);
m_TextComponentUGUI = null;
}
if (m_CanvasObject != null)
{
Object.DestroyImmediate(m_CanvasObject);
m_CanvasObject = null;
}
if (m_TextComponent != null)
{
Object.DestroyImmediate(m_TextComponent.gameObject);
m_TextComponent = null;
}
if (m_LigatureFontAsset != null)
{
m_LigatureFontAsset.atlasTextures = null;
m_LigatureFontAsset.m_AtlasTexture = null;
m_LigatureFontAsset.material = null;
Object.DestroyImmediate(m_LigatureFontAsset);
m_LigatureFontAsset = null;
}
}
/// <summary>
/// The two renderers hold independent copies of SetArraySizes, so each case is asserted
/// against both.
/// </summary>
TMP_Text[] textComponents => new TMP_Text[] { m_TextComponent, m_TextComponentUGUI };
static void AssertCharacterSpan(TMP_Text textComponent, int characterIndex, int expectedIndex, int expectedStringLength)
{
TMP_CharacterInfo characterInfo = textComponent.textInfo.characterInfo[characterIndex];
Assert.AreEqual(expectedIndex, characterInfo.index,
$"[{textComponent.GetType().Name}] characterInfo[{characterIndex}].index should be the first code unit of the cluster.");
Assert.AreEqual(expectedStringLength, characterInfo.stringLength,
$"[{textComponent.GetType().Name}] characterInfo[{characterIndex}].stringLength should cover every code unit of the cluster.");
}
[Test]
public void VariationSelector16_IsFoldedIntoTheSpanOfItsBaseCharacter()
{
// "a" + VS16 renders as one character built from two code units.
const string sourceText = "a" + k_VariationSelector16;
foreach (TMP_Text textComponent in textComponents)
{
textComponent.text = sourceText;
textComponent.ForceMeshUpdate();
Assert.AreEqual(1, textComponent.textInfo.characterCount,
$"[{textComponent.GetType().Name}] A variation selector should not be counted as a character of its own.");
// Before the fix this reported (index 1, stringLength 1) - the selector's own span.
AssertCharacterSpan(textComponent, 0, 0, 2);
}
}
[Test]
public void VariationSelector17_IsFoldedIntoTheSpanOfItsBaseCharacter()
{
// "a" + VS17 renders as one character built from three code units, because the
// selector is a surrogate pair. This is the shape from the original bug report.
const string sourceText = "a" + k_VariationSelector17;
foreach (TMP_Text textComponent in textComponents)
{
textComponent.text = sourceText;
textComponent.ForceMeshUpdate();
Assert.AreEqual(1, textComponent.textInfo.characterCount,
$"[{textComponent.GetType().Name}] A variation selector should not be counted as a character of its own.");
// Before the fix this reported (index 1, stringLength 2) - the selector's own
// span - so TMP_InputField deleted only the surrogate pair and left the base
// character behind, or indexed a stale characterInfo slot entirely.
AssertCharacterSpan(textComponent, 0, 0, 3);
}
}
[Test]
public void VariationSelectorCluster_KeepsTheSpansOfSurroundingCharacters()
{
// 'a' | 'b' + VS17 | 'c' -> three characters over five code units.
const string sourceText = "ab" + k_VariationSelector17 + "c";
foreach (TMP_Text textComponent in textComponents)
{
textComponent.text = sourceText;
textComponent.ForceMeshUpdate();
Assert.AreEqual(3, textComponent.textInfo.characterCount,
$"[{textComponent.GetType().Name}] Unexpected character count.");
AssertCharacterSpan(textComponent, 0, 0, 1);
AssertCharacterSpan(textComponent, 1, 1, 3);
AssertCharacterSpan(textComponent, 2, 4, 1);
}
}
[Test]
public void CharacterSpans_AreContiguousAndCoverTheWholeSourceString()
{
// The invariant TMP_InputField's caret arithmetic depends on: consecutive characters
// describe adjacent, non-overlapping spans that together cover the source string.
// A cluster used to leave a hole here, because its index skipped the base character.
const string sourceText = "ab" + k_VariationSelector17 + "c" + k_VariationSelector16 + "d";
foreach (TMP_Text textComponent in textComponents)
{
textComponent.text = sourceText;
textComponent.ForceMeshUpdate();
TMP_TextInfo textInfo = textComponent.textInfo;
int characterCount = textInfo.characterCount;
Assert.AreEqual(0, textInfo.characterInfo[0].index,
$"[{textComponent.GetType().Name}] The first character should start at the beginning of the source string.");
for (int i = 0; i < characterCount - 1; i++)
{
Assert.AreEqual(textInfo.characterInfo[i].index + textInfo.characterInfo[i].stringLength,
textInfo.characterInfo[i + 1].index,
$"[{textComponent.GetType().Name}] characterInfo[{i}] should end exactly where characterInfo[{i + 1}] begins.");
}
TMP_CharacterInfo lastCharacter = textInfo.characterInfo[characterCount - 1];
Assert.AreEqual(sourceText.Length, lastCharacter.index + lastCharacter.stringLength,
$"[{textComponent.GetType().Name}] The characters together should cover the whole source string.");
}
}
[Test]
public void PlainCharacters_SpansAreUnchanged()
{
// Regression guard: text with no cluster must map one character to one code unit.
const string sourceText = "abc";
foreach (TMP_Text textComponent in textComponents)
{
textComponent.text = sourceText;
textComponent.ForceMeshUpdate();
Assert.AreEqual(3, textComponent.textInfo.characterCount,
$"[{textComponent.GetType().Name}] Unexpected character count.");
AssertCharacterSpan(textComponent, 0, 0, 1);
AssertCharacterSpan(textComponent, 1, 1, 1);
AssertCharacterSpan(textComponent, 2, 2, 1);
}
}
[Test]
public void SurrogatePairWithoutVariationSelector_SpanIsUnchanged()
{
// Regression guard: a surrogate pair is already one character over two code units
// and no cluster block runs for it, so the accounting must not touch it. The default
// font asset does not necessarily carry this glyph, but the span is captured before
// the missing glyph substitution region, so the mapping holds either way.
const string sourceText = "a" + k_AstralCharacter;
foreach (TMP_Text textComponent in textComponents)
{
textComponent.text = sourceText;
textComponent.ForceMeshUpdate();
Assert.AreEqual(2, textComponent.textInfo.characterCount,
$"[{textComponent.GetType().Name}] Unexpected character count.");
AssertCharacterSpan(textComponent, 0, 0, 1);
AssertCharacterSpan(textComponent, 1, 1, 2);
}
}
[Test]
public void Ligature_IsFoldedIntoTheSpanOfItsFirstComponent()
{
const string sourceText = "fi";
foreach (TMP_Text textComponent in textComponents)
{
TMP_FontAsset originalFont = textComponent.font;
List<OTL_FeatureTag> originalFontFeatures = new List<OTL_FeatureTag>(textComponent.fontFeatures);
try
{
textComponent.font = m_LigatureFontAsset;
List<OTL_FeatureTag> fontFeatures = new List<OTL_FeatureTag>(originalFontFeatures);
if (!fontFeatures.Contains(OTL_FeatureTag.liga))
{
// Assign through the property rather than mutating the list in place, so
// the text object is marked dirty the way it would be from user code.
fontFeatures.Add(OTL_FeatureTag.liga);
textComponent.fontFeatures = fontFeatures;
}
textComponent.text = sourceText;
textComponent.ForceMeshUpdate();
Assert.AreEqual(1, textComponent.textInfo.characterCount,
$"[{textComponent.GetType().Name}] 'fi' should be substituted by a single ligature character.");
// Before the fix this reported (index 1, stringLength 1) - the span of the
// last component consumed - so the start of the cluster was lost.
AssertCharacterSpan(textComponent, 0, 0, 2);
}
finally
{
// Leave the shared fixture components as the other tests expect them.
textComponent.fontFeatures = originalFontFeatures;
textComponent.font = originalFont;
textComponent.text = string.Empty;
}
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4bb24419713edc74180cebbba7460c96
@@ -0,0 +1,37 @@
using NUnit.Framework;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
namespace TMPro
{
internal class TMP_ControlTests
{
Scene scene;
[SetUp]
public void Setup()
{
// Create a new scene and open it
scene = EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
}
[TestCase("GameObject/UI (Canvas)/Dropdown - TextMeshPro")]
[TestCase("GameObject/UI (Canvas)/Button - TextMeshPro")]
[TestCase("GameObject/UI (Canvas)/Input Field - TextMeshPro")]
[TestCase("GameObject/UI (Canvas)/Text - TextMeshPro")]
public void TMPControlCreationAndUndoTest(string menuItem)
{
Assert.AreEqual(0, scene.rootCount);
EditorApplication.ExecuteMenuItem(menuItem);
// After creating a TMP control, objects in the scene should be Canvas, EventSystem, and the TMP control
Assert.AreEqual(2, scene.rootCount);
Undo.PerformUndo();
// After undoing, the scene should be back to its original state
Assert.AreEqual(0, scene.rootCount);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5c221dffa89042038c946376c731c918
timeCreated: 1705430351
@@ -0,0 +1,628 @@
using UnityEngine;
using UnityEditor;
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
using Object = UnityEngine.Object;
namespace TMPro
{
[Category("Text Parsing & Layout")]
internal class TMP_EditorTests
{
private TextMeshPro m_TextComponent;
// Characters: 22 Spaces: 4 Words: 5 Lines:
private const string m_TextBlock_00 = "A simple line of text.";
// Characters: 104 Spaces: 14 Words: 15 Lines:
private const string m_TextBlock_01 = "Unity 2017 introduces new features that help teams of artists and developers build experiences together.";
// Characters: 1500 Spaces: 228 Words: 241
private const string m_TextBlock_02 = "The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in their grammar, their pronunciation and their most common words." +
"Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators.To achieve this, it would be necessary to have uniform grammar, pronunciation and more common words.If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages." +
"The new common language will be more simple and regular than the existing European languages.It will be as simple as Occidental; in fact, it will be Occidental.To an English person, it will seem like simplified English, as a skeptical Cambridge friend of mine told me what Occidental is. The European languages are members of the same family." +
"Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary.The languages only differ in their grammar, their pronunciation and their most common words.Everyone realizes why a new common language would be desirable: one could refuse to pay expensive translators.To achieve this, it would be necessary to" +
"have uniform grammar, pronunciation and more common words.If several languages coalesce, the grammar of the resulting language is more simple and regular than that of the individual languages.The new common language will be";
// Characters: 2500 Spaces: 343 Words: 370
private const string m_TextBlock_03 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. " +
"Nullam dictum felis eu pede mollis pretium.Integer tincidunt.Cras dapibus.Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.Phasellus viverra nulla ut metus varius laoreet.Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue.Curabitur ullamcorper ultricies nisi. " +
"Nam eget dui.Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem.Maecenas nec odio et ante tincidunt tempus.Donec vitae sapien ut libero venenatis faucibus.Nullam quis ante.Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. " +
"Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus.Nullam accumsan lorem in dui.Cras ultricies mi eu turpis hendrerit fringilla.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia. Nam pretium turpis et arcu. " +
"Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris.Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris.Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc.Nunc nonummy metus.Vestibulum volutpat pretium libero. Cras id dui.Aenean ut eros et nisl sagittis vestibulum.Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede.Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis. " +
"Etiam imperdiet imperdiet orci. Nunc nec neque.Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi.Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo.Maecenas malesuada. Praesent nan. The end of this of this long block of text.";
// Characters: 3423 Spaces: 453 Words: 500
private const string m_TextBlock_04 = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.Aenean commodo ligula eget dolor.Aenean massa.Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.Nulla consequat massa quis enim.Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu.In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo.Nullam dictum felis eu pede mollis pretium.Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus." +
"Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus.Phasellus viverra nulla ut metus varius laoreet.Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue.Curabitur ullamcorper ultricies nisi. Nam eget dui.Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum.Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem.Maecenas nec odio et ante tincidunt tempus.Donec vitae sapien ut libero venenatis faucibus.Nullam quis ante." +
"Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc, quis gravida magna mi a libero. Fusce vulputate eleifend sapien. Vestibulum purus quam, scelerisque ut, mollis sed, nonummy id, metus.Nullam accumsan lorem in dui.Cras ultricies mi eu turpis hendrerit fringilla.Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ac dui quis mi consectetuer lacinia.Nam pretium turpis et arcu." +
"Duis arcu tortor, suscipit eget, imperdiet nec, imperdiet iaculis, ipsum. Sed aliquam ultrices mauris.Integer ante arcu, accumsan a, consectetuer eget, posuere ut, mauris.Praesent adipiscing. Phasellus ullamcorper ipsum rutrum nunc.Nunc nonummy metus.Vestibulum volutpat pretium libero. Cras id dui.Aenean ut eros et nisl sagittis vestibulum.Nullam nulla eros, ultricies sit amet, nonummy id, imperdiet feugiat, pede.Sed lectus. Donec mollis hendrerit risus. Phasellus nec sem in justo pellentesque facilisis.Etiam imperdiet imperdiet orci. Nunc nec neque." +
"Phasellus leo dolor, tempus non, auctor et, hendrerit quis, nisi.Curabitur ligula sapien, tincidunt non, euismod vitae, posuere imperdiet, leo.Maecenas malesuada. Praesent congue erat at massa.Sed cursus turpis vitae tortor.Donec posuere vulputate arcu. Phasellus accumsan cursus velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed aliquam, nisi quis porttitor congue, elit erat euismod orci, ac placerat dolor lectus quis orci.Phasellus consectetuer vestibulum elit.Aenean tellus metus, bibendum sed, posuere ac, mattis non, nunc.Vestibulum fringilla pede sit amet augue." +
"In turpis. Pellentesque posuere. Praesent turpis. Aenean posuere, tortor sed cursus feugiat, nunc augue blandit nunc, eu sollicitudin urna dolor sagittis lacus. Donec elit libero, sodales nec, volutpat a, suscipit non, turpis.Nullam sagittis. Suspendisse pulvinar, augue ac venenatis condimentum, sem libero volutpat nibh, nec pellentesque velit pede quis nunc. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce id purus.Ut varius tincidunt libero.Phasellus dolor.Maecenas vestibulum mollis";
//
private const string m_TextBlock_05 = "This block of text contains <b>bold</b> and <i>italicized</i> characters.";
private const string m_TextBlock_06 = "<align=center><style=H1><#ffffff><u>Multiple<#80f0ff> Alignment</color> per text object</u></color></style></align><line-height=2em>\n" +
"</line-height> The <<#ffffa0>align</color>> tag in TextMesh<#40a0ff>Pro</color> provides the ability to control the alignment of lines and paragraphs which is essential when working with text.\n" +
"<align=left> You may want some block of text to be<#80f0ff>left aligned</color> <<#ffffa0>align=<#80f0ff>left</color></color>> which is sort of the standard.</align>\n" +
"<style=Quote><#ffffa0>\"Using <#80f0ff>Center Alignment</color> <<#ffffa0>align=<#80f0ff>center</color></color>> for a title or displaying a quote is another good example of text alignment.\"</color></style>\n" +
"<align=right><#80f0ff>Right Alignment</color> <<#ffffa0>align=<#80f0ff>right</color></color>> can be useful to create contrast between lines and paragraphs of text.\n" +
"<align=justified><#80f0ff>Justified Alignment</color> <<#ffffa0>align=<#80f0ff>justified</color></color>> results in text that is flush on both the left and right margins. Used well, justified type can look clean and classy.\n" +
"<style=Quote><align=left><#ffffa0>\"Text formatting and alignment has a huge impact on how people will read and perceive your text.\"</color>\n" +
"<size=65%><align=right> -Stephan Bouchard</style>";
private readonly string[] testStrings = new string[] { m_TextBlock_00, m_TextBlock_01, m_TextBlock_02, m_TextBlock_03, m_TextBlock_04, m_TextBlock_05, m_TextBlock_06 };
private void AssertRenderedText(string expected)
{
expected ??= string.Empty;
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(expected.Length, m_TextComponent.textInfo.characterCount);
for (int i = 0; i < expected.Length; i++)
Assert.AreEqual(expected[i], m_TextComponent.textInfo.characterInfo[i].character, $"Character mismatch at index {i}.");
}
private void AssertCharacterStyle(int index, FontStyles style, bool expected)
{
FontStyles actualStyle = m_TextComponent.textInfo.characterInfo[index].style;
bool hasStyle = (actualStyle & style) == style;
Assert.AreEqual(expected, hasStyle, $"Expected character at index {index} to {(expected ? "have" : "not have")} style {style}.");
}
private void AssertCharacterStyleRange(int startIndex, int length, FontStyles style, bool expected)
{
for (int i = startIndex; i < startIndex + length; i++)
AssertCharacterStyle(i, style, expected);
}
[OneTimeSetUp]
public void OneTimeSetup()
{
if (Directory.Exists(Path.GetFullPath("Assets/TextMesh Pro")) || Directory.Exists(Path.GetFullPath("Packages/com.unity.textmeshpro.tests/TextMesh Pro")))
{
GameObject textObject = new GameObject("Text Object");
m_TextComponent = textObject.AddComponent<TextMeshPro>();
m_TextComponent.fontSize = 18;
}
else
{
Debug.Log("Skipping over Editor tests as TMP Essential Resources are missing from the current test project.");
Assert.Ignore();
}
}
[Test]
[TestCase("/Package Resources/TMP Essential Resources.unitypackage", "ce4ff17ca867d2b48b5c8a4181611901")]
[TestCase("/Package Resources/TMP Examples & Extras.unitypackage", "bc00e25696e4132499f56528d3fed2e3")]
[TestCase("/PackageConversionData.json", "05f5bfd584002f948982a1498890f9a9")]
public void InternalResourceCheck(string filePath, string guid)
{
string packageRelativePath = EditorUtilities.TMP_EditorUtility.packageRelativePath;
string packageFullPath = EditorUtilities.TMP_EditorUtility.packageFullPath;
Assert.AreEqual(AssetDatabase.AssetPathToGUID(packageRelativePath + filePath), guid);
Assert.IsTrue(File.Exists(packageFullPath + filePath));
}
// =============================================
// Font Asset Creation Tests
// =============================================
// =============================================
// Text Parsing and Layout Tests
// =============================================
[Test]
[TestCase(4, 3423, 453, 500, 1)]
[TestCase(3, 2500, 343, 370, 1)]
[TestCase(2, 1500, 228, 241, 1)]
[TestCase(1, 104, 14, 15, 1)]
[TestCase(0, 22, 4, 5, 1)]
public void TextParsing_TextInfoTest_WordWrappingDisabled(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.NoWrap;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(50, 5);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
[Test]
[TestCase(4, 3423, 453, 500, 29)]
[TestCase(3, 2500, 343, 370, 21)]
[TestCase(2, 1500, 228, 241, 13)]
[TestCase(1, 104, 14, 15, 1)]
[TestCase(0, 22, 4, 5, 1)]
public void TextParsing_TextInfoTest_WordWrappingEnabled(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(100, 50);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
[Test]
[TestCase(4, 3423, 453, 500, 27)]
[TestCase(3, 2500, 343, 370, 20)]
[TestCase(2, 1500, 228, 241, 13)]
public void TextParsing_TextInfoTest_TopJustifiedAlignment(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopJustified;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(100, 50);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
[Test]
[TestCase(6, 768, 124, 126, 14)]
[TestCase(5, 59, 8, 9, 1)]
public void TextParsing_TextInfoTest_RichText(int sourceTextIndex, int characterCount, int spaceCount, int wordCount, int lineCount)
{
m_TextComponent.text = testStrings[sourceTextIndex];
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(m_TextComponent.textInfo.characterCount, characterCount);
Assert.AreEqual(m_TextComponent.textInfo.spaceCount, spaceCount);
Assert.AreEqual(m_TextComponent.textInfo.wordCount, wordCount);
Assert.AreEqual(m_TextComponent.textInfo.lineCount, lineCount);
}
// =============================================
// Markup tag specific tests
// =============================================
[Test]
[TestCase("<scale=1.0>ABC</scale>", -35.0f, -33.8069763f, -33.8069763f, -32.6139526f, -32.6139526f, -31.3162785f)]
[TestCase("<scale=0.8>ABC</scale>", -35.0f, -34.0455818f, -34.0455818f, -33.0911636f, -33.0911636f, -32.0530243f)]
[TestCase("<scale=1.2>ABC</scale>", -35.0f, -33.5683708f, -33.5683708f, -32.1367455f, -32.1367455f, -30.5795345f)]
public void MarkupTag_Scale(string sourceText, float origin1, float advance1, float origin2, float advance2, float origin3, float advance3)
{
m_TextComponent.text = sourceText;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(origin1, m_TextComponent.textInfo.characterInfo[0].origin);
Assert.AreEqual(advance1, m_TextComponent.textInfo.characterInfo[0].xAdvance);
Assert.AreEqual(origin2, m_TextComponent.textInfo.characterInfo[1].origin);
Assert.AreEqual(advance2, m_TextComponent.textInfo.characterInfo[1].xAdvance);
Assert.AreEqual(origin3, m_TextComponent.textInfo.characterInfo[2].origin);
Assert.AreEqual(advance3, m_TextComponent.textInfo.characterInfo[2].xAdvance);
}
[Test]
[TestCase("<size=12>ABC</size>", -35.0f, -34.2046509f, -34.2046509f, -33.4093018f, -33.4093018f, -32.5441856f)]
[TestCase("<size=-6>ABC</size>", -35.0f, -34.2046509f, -34.2046509f, -33.4093018f, -33.4093018f, -32.5441856f)]
[TestCase("<size=+6>ABC</size>", -35.0f, -33.4093018f, -33.4093018f, -31.8186054f, -31.8186054f, -30.0883713f)]
[TestCase("<size=50%>ABC</size>", -35.0f, -34.4034882f, -34.4034882f, -33.8069763f, -33.8069763f, -33.1581383f)]
[TestCase("<size=150%>DEF</size>", -35.0f, -33.0534897f, -33.0534897f, -31.2639542f, -31.2639542f, -29.6000004f)]
[TestCase("<size=0.5em>ABC</size>", -35.0f, -34.4034882f, -34.4034882f, -33.8069763f, -33.8069763f, -33.1581383f)]
[TestCase("<size=1.5em>DEF</size>", -35.0f, -33.0534897f, -33.0534897f, -31.2639542f, -31.2639542f, -29.6000004f)]
public void MarkupTag_Size(string sourceText, float origin1, float advance1, float origin2, float advance2, float origin3, float advance3)
{
m_TextComponent.text = sourceText;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(origin1, m_TextComponent.textInfo.characterInfo[0].origin);
Assert.AreEqual(advance1, m_TextComponent.textInfo.characterInfo[0].xAdvance);
Assert.AreEqual(origin2, m_TextComponent.textInfo.characterInfo[1].origin);
Assert.AreEqual(advance2, m_TextComponent.textInfo.characterInfo[1].xAdvance);
Assert.AreEqual(origin3, m_TextComponent.textInfo.characterInfo[2].origin);
Assert.AreEqual(advance3, m_TextComponent.textInfo.characterInfo[2].xAdvance);
}
[Test]
[TestCase("<cspace=30>ABC</cspace>", -35.0f, -30.8069763f, -30.8069763f, -26.6139526f, -26.6139526f, -25.3162804f)]
[TestCase("<cspace=2em>ABC</cspace>", -35.0f, -30.2069759f, -30.2069759f, -25.4139519f, -25.4139519f, -24.1162796f)]
public void MarkupTag_Cspace(string sourceText, float origin1, float advance1, float origin2, float advance2, float origin3, float advance3)
{
m_TextComponent.text = sourceText;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(origin1, m_TextComponent.textInfo.characterInfo[0].origin);
Assert.AreEqual(advance1, m_TextComponent.textInfo.characterInfo[0].xAdvance);
Assert.AreEqual(origin2, m_TextComponent.textInfo.characterInfo[1].origin);
Assert.AreEqual(advance2, m_TextComponent.textInfo.characterInfo[1].xAdvance);
Assert.AreEqual(origin3, m_TextComponent.textInfo.characterInfo[2].origin);
Assert.AreEqual(advance3, m_TextComponent.textInfo.characterInfo[2].xAdvance);
}
[Test]
[TestCase("<mspace=30>ABC</mspace>", -34.0965118f, -32.0f, -31.1279068f, -29.0f, -28.1593018f, -26.0f)]
[TestCase("<mspace=2em>ABC</mspace>", -33.7965126f, -31.3999996f, -30.2279072f, -27.7999992f, -26.6593018f, -24.2000008f)]
public void MarkupTag_Mspace(string sourceText, float origin1, float advance1, float origin2, float advance2, float origin3, float advance3)
{
m_TextComponent.text = sourceText;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(origin1, m_TextComponent.textInfo.characterInfo[0].origin);
Assert.AreEqual(advance1, m_TextComponent.textInfo.characterInfo[0].xAdvance);
Assert.AreEqual(origin2, m_TextComponent.textInfo.characterInfo[1].origin);
Assert.AreEqual(advance2, m_TextComponent.textInfo.characterInfo[1].xAdvance);
Assert.AreEqual(origin3, m_TextComponent.textInfo.characterInfo[2].origin);
Assert.AreEqual(advance3, m_TextComponent.textInfo.characterInfo[2].xAdvance);
}
[Test]
[TestCase("A<space=18>B<space=18>C", -35.0f, -33.8069763f, -32.0069771f, -30.8139534f, -29.0139542f, -27.7162781f)]
[TestCase("A<space=1em>B<space=1em>C", -35.0f, -33.8069763f, -32.0069771f, -30.8139534f, -29.0139542f, -27.7162781f)]
public void MarkupTag_Space(string sourceText, float origin1, float advance1, float origin2, float advance2, float origin3, float advance3)
{
m_TextComponent.text = sourceText;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(origin1, m_TextComponent.textInfo.characterInfo[0].origin);
Assert.AreEqual(advance1, m_TextComponent.textInfo.characterInfo[0].xAdvance);
Assert.AreEqual(origin2, m_TextComponent.textInfo.characterInfo[1].origin);
Assert.AreEqual(advance2, m_TextComponent.textInfo.characterInfo[1].xAdvance);
Assert.AreEqual(origin3, m_TextComponent.textInfo.characterInfo[2].origin);
Assert.AreEqual(advance3, m_TextComponent.textInfo.characterInfo[2].xAdvance);
}
[Test]
[TestCase("A<pos=10%>B<pos=20%>C", -35.0f, -33.8069763f, -28.0f, -26.8069763f, -21.0f, -19.7023258f)]
[TestCase("A<pos=70>B<pos=140>C", -35.0f, -33.8069763f, -28.0f, -26.8069763f, -21.0f, -19.7023258f)]
[TestCase("A<pos=1.5em>B<pos=3em>CC", -35.0f, -33.8069763f, -32.2999992f, -31.1069775f, -29.6000004f, -28.3023262f)]
public void MarkupTag_Pos(string sourceText, float origin1, float advance1, float origin2, float advance2, float origin3, float advance3)
{
m_TextComponent.text = sourceText;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(origin1, m_TextComponent.textInfo.characterInfo[0].origin);
Assert.AreEqual(advance1, m_TextComponent.textInfo.characterInfo[0].xAdvance);
Assert.AreEqual(origin2, m_TextComponent.textInfo.characterInfo[1].origin);
Assert.AreEqual(advance2, m_TextComponent.textInfo.characterInfo[1].xAdvance);
Assert.AreEqual(origin3, m_TextComponent.textInfo.characterInfo[2].origin);
Assert.AreEqual(advance3, m_TextComponent.textInfo.characterInfo[2].xAdvance);
}
[Test]
[TestCase("<indent=18>ABC", -33.2000008f, -32.0069771f, -32.0069771f, -30.8139534f, -30.8139534f, -29.5162792f)]
[TestCase("<indent=1em>ABC", -33.2000008f, -32.0069771f, -32.0069771f, -30.8139534f, -30.8139534f, -29.5162792f)]
[TestCase("<indent=2.5%>ABC", -33.25f, -32.0569763f, -32.0569763f, -30.8639526f, -30.8639526f, -29.5662804f)]
public void MarkupTag_Indent(string sourceText, float origin1, float advance1, float origin2, float advance2, float origin3, float advance3)
{
m_TextComponent.text = sourceText;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.alignment = TextAlignmentOptions.TopLeft;
// Size the RectTransform
m_TextComponent.rectTransform.sizeDelta = new Vector2(70, 35);
// Force text generation to populate the TextInfo data structure.
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(origin1, m_TextComponent.textInfo.characterInfo[0].origin);
Assert.AreEqual(advance1, m_TextComponent.textInfo.characterInfo[0].xAdvance);
Assert.AreEqual(origin2, m_TextComponent.textInfo.characterInfo[1].origin);
Assert.AreEqual(advance2, m_TextComponent.textInfo.characterInfo[1].xAdvance);
Assert.AreEqual(origin3, m_TextComponent.textInfo.characterInfo[2].origin);
Assert.AreEqual(advance3, m_TextComponent.textInfo.characterInfo[2].xAdvance);
}
#if TMP_TEST_RESOURCES
const string k_SpriteAssetPath = "Assets/TextMesh Pro/Resources/Sprite Assets/MixedIndexTest.asset";
[Test]
public void SpriteAssetIndexAreValidAfterReordering()
{
var spriteAsset = AssetDatabase.LoadAssetAtPath<TMP_SpriteAsset>(k_SpriteAssetPath);
if (spriteAsset == null)
{
Debug.LogError("Failed to load Sprite Asset at path: " + k_SpriteAssetPath);
return;
}
string text = $"<sprite name=\"cta_obsidianjade\">";
m_TextComponent.spriteAsset = spriteAsset;
m_TextComponent.text = text;
m_TextComponent.ForceMeshUpdate();
Assert.AreEqual(203, m_TextComponent.textInfo.characterInfo[0].textElement.glyphIndex, $"Mismatch between sprite index. Expected 203 but was {m_TextComponent.textInfo.characterInfo[0].textElement.glyphIndex}");
}
#endif
// =============================================
// SetText Tests
// =============================================
[Test]
public void SetText_String_Null_ClearsText()
{
m_TextComponent.SetText("Previously assigned text.");
m_TextComponent.ForceMeshUpdate();
Assert.Greater(m_TextComponent.textInfo.characterCount, 0);
m_TextComponent.SetText((string)null);
AssertRenderedText(string.Empty);
}
[Test]
public void SetText_CharArray_Null_ClearsText()
{
m_TextComponent.SetText("Previously assigned text.");
m_TextComponent.ForceMeshUpdate();
Assert.Greater(m_TextComponent.textInfo.characterCount, 0);
m_TextComponent.SetText((char[])null);
AssertRenderedText(string.Empty);
}
[Test]
public void SetText_StringBuilder_Null_ClearsText()
{
m_TextComponent.SetText("Previously assigned text.");
m_TextComponent.ForceMeshUpdate();
Assert.Greater(m_TextComponent.textInfo.characterCount, 0);
m_TextComponent.SetText((StringBuilder)null);
AssertRenderedText(string.Empty);
}
[Test]
public void SetText_ReadOnlySpan_Empty_ClearsText()
{
m_TextComponent.SetText("Previously assigned text.");
m_TextComponent.ForceMeshUpdate();
Assert.Greater(m_TextComponent.textInfo.characterCount, 0);
m_TextComponent.SetText(ReadOnlySpan<char>.Empty);
AssertRenderedText(string.Empty);
}
[Test]
[TestCase("")]
[TestCase("A")]
[TestCase("A simple line of text.")]
[TestCase("The quick brown fox jumps over the lazy dog while TextMesh Pro lays out the generated characters.")]
public void SetText_String_PlainText_RendersExpectedCharacters(string sourceText)
{
m_TextComponent.SetText(sourceText);
AssertRenderedText(sourceText);
}
[Test]
[TestCase("")]
[TestCase("A")]
[TestCase("Character array input with enough length to exercise more than a trivial copy.")]
public void SetText_CharArray_PlainText_RendersExpectedCharacters(string sourceText)
{
m_TextComponent.SetText(sourceText.ToCharArray());
AssertRenderedText(sourceText);
}
[Test]
[TestCase("")]
[TestCase("A")]
[TestCase("StringBuilder input with a longer sentence to validate characterInfo output.")]
public void SetText_StringBuilder_PlainText_RendersExpectedCharacters(string sourceText)
{
m_TextComponent.SetText(new StringBuilder(sourceText));
AssertRenderedText(sourceText);
}
[Test]
[TestCase("")]
[TestCase("A")]
[TestCase("ReadOnlySpan input with a longer sentence to validate characterInfo output.")]
public void SetText_ReadOnlySpan_PlainText_RendersExpectedCharacters(string sourceText)
{
m_TextComponent.SetText(sourceText.AsSpan());
AssertRenderedText(sourceText);
}
[Test]
public void SetText_ReadOnlySpan_Range_CopiesExpectedSubstring()
{
const string sourceText = "0123456789";
m_TextComponent.SetText(sourceText.AsSpan(), 2, 4);
AssertRenderedText("2345");
}
[Test]
public void SetText_ReadOnlySpan_Range_ClampsStartAndLength()
{
const string sourceText = "abcdef";
m_TextComponent.SetText(sourceText.AsSpan(), 4, 10);
AssertRenderedText("ef");
}
[Test]
[TestCase("This block contains <b>bold</b> and <i>italicized</i> characters.", "This block contains bold and italicized characters.")]
[TestCase("A <u>underlined</u> word and a <s>struck</s> word.", "A underlined word and a struck word.")]
[TestCase("Nested <b><i>bold italic</i></b> text returns to normal.", "Nested bold italic text returns to normal.")]
[TestCase("A <color=#ff0000>red</color> word renders without color tags.", "A red word renders without color tags.")]
public void SetText_String_RichTextTags_RendersExpectedCharacters(string sourceText, string expectedText)
{
m_TextComponent.SetText(sourceText);
AssertRenderedText(expectedText);
}
[Test]
[TestCase("A <style=H1>heading</style> B", "A *heading* B")]
[TestCase("A <style=Quote>quote</style> B", "A quote B")]
public void SetText_String_StyleTags_RendersExpectedCharacters(string sourceText, string expectedText)
{
m_TextComponent.SetText(sourceText);
AssertRenderedText(expectedText);
}
[Test]
public void SetText_String_BoldTag_SetsAndClearsBoldStyle()
{
m_TextComponent.SetText("A <b>bold</b> B");
AssertRenderedText("A bold B");
AssertCharacterStyleRange(0, 2, FontStyles.Bold, false);
AssertCharacterStyleRange(2, 4, FontStyles.Bold, true);
AssertCharacterStyleRange(6, 2, FontStyles.Bold, false);
}
[Test]
public void SetText_String_ItalicTag_SetsAndClearsItalicStyle()
{
m_TextComponent.SetText("A <i>italic</i> B");
AssertRenderedText("A italic B");
AssertCharacterStyleRange(0, 2, FontStyles.Italic, false);
AssertCharacterStyleRange(2, 6, FontStyles.Italic, true);
AssertCharacterStyleRange(8, 2, FontStyles.Italic, false);
}
[Test]
public void SetText_String_NestedBoldItalicTags_SetAndClearExpectedStyles()
{
m_TextComponent.SetText("A <b><i>BI</i></b> C");
AssertRenderedText("A BI C");
AssertCharacterStyleRange(0, 2, FontStyles.Bold, false);
AssertCharacterStyleRange(0, 2, FontStyles.Italic, false);
AssertCharacterStyleRange(2, 2, FontStyles.Bold, true);
AssertCharacterStyleRange(2, 2, FontStyles.Italic, true);
AssertCharacterStyleRange(4, 2, FontStyles.Bold, false);
AssertCharacterStyleRange(4, 2, FontStyles.Italic, false);
}
[Test]
public void SetText_String_UnderlineAndStrikethroughTags_SetAndClearExpectedStyles()
{
m_TextComponent.SetText("A <u>U</u> <s>S</s> Z");
AssertRenderedText("A U S Z");
AssertCharacterStyle(2, FontStyles.Underline, true);
AssertCharacterStyle(4, FontStyles.Strikethrough, true);
AssertCharacterStyleRange(0, 2, FontStyles.Underline, false);
AssertCharacterStyleRange(3, 4, FontStyles.Underline, false);
AssertCharacterStyleRange(0, 4, FontStyles.Strikethrough, false);
AssertCharacterStyleRange(5, 2, FontStyles.Strikethrough, false);
}
// Add tests that check position of individual characters in a complex block of text.
// These test also use the data contained inside the TMP_TextInfo class.
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (m_TextComponent != null)
{
Object.DestroyImmediate(m_TextComponent.gameObject);
m_TextComponent = null;
}
// // Remove TMP Essential Resources if they were imported in the project as a result of running tests.
// if (TMPro_EventManager.temporaryResourcesImported == true)
// {
// if (Directory.Exists(Path.GetFullPath("Assets/TextMesh Pro")))
// {
// AssetDatabase.DeleteAsset("Assets/TextMesh Pro");
// TMPro_EventManager.temporaryResourcesImported = false;
// }
// }
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 592f7288ed0df2c4b884e2cd9baac023
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,117 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.IO;
using Object = UnityEngine.Object;
namespace TMPro
{
[Category("Text Parsing & Layout")]
internal class TMP_TextTests
{
private TextMeshPro m_TextComponent;
GameObject m_canvasObject;
private TextMeshProUGUI m_TextComponentUGUI;
[OneTimeSetUp]
public void OneTimeSetUp()
{
if (Directory.Exists(Path.GetFullPath("Assets/TextMesh Pro")) || Directory.Exists(Path.GetFullPath("Packages/com.unity.textmeshpro.tests/TextMesh Pro")))
{
GameObject textObject = new GameObject("Text Object");
m_TextComponent = textObject.AddComponent<TextMeshPro>();
m_canvasObject = new GameObject("Canvas Object");
m_canvasObject.AddComponent<Canvas>();
GameObject textObjectUGUI = new GameObject("Text Object UGUI");
textObjectUGUI.transform.SetParent(m_canvasObject.transform);
m_TextComponentUGUI = textObjectUGUI.AddComponent<TextMeshProUGUI>();
}
else
{
Debug.Log("Skipping over Editor tests as TMP Essential Resources are missing from the current test project.");
Assert.Ignore();
}
}
[OneTimeTearDown]
public void OneTimeTearDown()
{
if (m_TextComponent != null)
{
Object.DestroyImmediate(m_TextComponent.gameObject);
Object.DestroyImmediate(m_TextComponentUGUI.gameObject);
Object.DestroyImmediate(m_canvasObject);
m_TextComponent = null;
m_TextComponentUGUI = null;
}
}
[Test]
public void Text3D_EllipsisOverflow_DoesNotThrow_WhenMaterialAtQuadCap()
{
// (UUM-134477) Reproduction for the IndexOutOfRangeException thrown when a TMP
// text with Overflow=Ellipsis is rendered and the ellipsis font
// asset's material has already filled its 16383-quad submesh.
m_TextComponent.rectTransform.sizeDelta = new Vector2(10, 15);
m_TextComponent.text = new string('A', 20000);
m_TextComponent.fontSize = 1f;
m_TextComponent.textWrappingMode = TextWrappingModes.Normal;
m_TextComponent.overflowMode = TextOverflowModes.Ellipsis;
Assert.DoesNotThrow(() => m_TextComponent.ForceMeshUpdate(ignoreActiveState: true, forceTextReparsing: true));
LogAssert.NoUnexpectedReceived();
// Sanity check: the fixture must produce more than 16383 visible
// characters before truncation — otherwise the test passes for the
// wrong reason (the cap was never reached and the bug not exercised).
Assert.IsTrue(m_TextComponent.isTextOverflowing, "Test fixture did not cause text to overflow. Tune rect/font/text to ensure overflow occurs and ellipsis insertion is triggered.");
Assert.Greater(m_TextComponent.textInfo.characterCount, 16384, "Test fixture did not push enough characters into the mesh to exercise the 16383-quad cap. Tune rect/font/text to fit more characters.");
}
[Test]
public void TextUGUI_EllipsisOverflow_DoesNotThrow_WhenMaterialAtQuadCap()
{
// (UUM-134477) Reproduction for the IndexOutOfRangeException thrown when a TMP
// text with Overflow=Ellipsis is rendered and the ellipsis font
// asset's material has already filled its 16383-quad submesh.
m_TextComponentUGUI.rectTransform.sizeDelta = new Vector2(100, 150);
m_TextComponentUGUI.text = new string('A', 20000);
m_TextComponentUGUI.fontSize = 1f;
m_TextComponentUGUI.textWrappingMode = TextWrappingModes.Normal;
m_TextComponentUGUI.overflowMode = TextOverflowModes.Ellipsis;
Assert.DoesNotThrow(() => m_TextComponentUGUI.ForceMeshUpdate(ignoreActiveState: true, forceTextReparsing: true));
LogAssert.NoUnexpectedReceived();
// Sanity check: the fixture must produce more than 16383 visible
// characters before truncation — otherwise the test passes for the
// wrong reason (the cap was never reached and the bug not exercised).
Assert.IsTrue(m_TextComponentUGUI.isTextOverflowing, "Test fixture did not cause text to overflow. Tune rect/font/text to ensure overflow occurs and ellipsis insertion is triggered.");
Assert.Greater(m_TextComponentUGUI.textInfo.characterCount, 16384, "Test fixture did not push enough characters into the mesh to exercise the 16383-quad cap. Tune rect/font/text to fit more characters.");
}
[Test]
public void TextUGUI_GetPreferredValues_HyphenPrecededByWhitespaceAtNarrowWidth_Terminates()
{
// (UUM-152921) Measure read line numbers left over from the previous layout and looped forever on " -".
TextOverflowModes previousOverflowMode = m_TextComponentUGUI.overflowMode;
try
{
m_TextComponentUGUI.fontSize = 36;
m_TextComponentUGUI.textWrappingMode = TextWrappingModes.Normal;
m_TextComponentUGUI.overflowMode = TextOverflowModes.Overflow;
m_TextComponentUGUI.rectTransform.sizeDelta = new Vector2(25, 50);
m_TextComponentUGUI.text = "New Text";
m_TextComponentUGUI.ForceMeshUpdate(ignoreActiveState: true, forceTextReparsing: true);
m_TextComponentUGUI.text = "a -N";
Assert.Greater(m_TextComponentUGUI.GetPreferredValues(25, 0).y, 0);
m_TextComponentUGUI.ForceMeshUpdate(ignoreActiveState: true, forceTextReparsing: true);
Assert.Greater(m_TextComponentUGUI.textInfo.lineCount, 1);
}
finally
{
m_TextComponentUGUI.overflowMode = previousOverflowMode;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d082183c35deb87489e26f9c7ba8e41f
@@ -0,0 +1,18 @@
{
"name": "Unity.TextMeshPro.Editor.Tests",
"references": [
"Unity.TextMeshPro",
"Unity.TextMeshPro.Editor",
"Unity.TextMeshPro.Tests"
],
"optionalUnityReferences": [
"TestAssemblies"
],
"defineConstraints": [
"UNITY_INCLUDE_TESTS"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": []
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 656e461844099ae43a609ff6109b0877
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fae3ac1997e164d1eba5fa5c417cbefd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: b86b117346968ac4d9cc63e4385becb7
folderAsset: yes
timeCreated: 1459501450
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,40 @@
using NUnit.Framework;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.TestTools;
using UnityEditor.SceneManagement;
using UnityEditor;
internal class AssertionFailureOnOutputVertexCount
{
const string scenePath = "Assets/AssertionFailureOnOutputVertexCountTestScene.unity";
[Test]
public void AssertionFailureOnOutputVertexCountTest()
{
var newScene = EditorSceneManager.NewScene(UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects, UnityEditor.SceneManagement.NewSceneMode.Single);
var canvasMaster = new GameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
var canvasChild = new GameObject("Canvas Child", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
canvasChild.transform.SetParent(canvasMaster.transform);
var panel1 = new GameObject("Panel", typeof(CanvasRenderer), typeof(UnityEngine.UI.Image));
panel1.transform.SetParent(canvasMaster.transform);
var panel2 = new GameObject("Panel", typeof(CanvasRenderer), typeof(UnityEngine.UI.Image));
panel2.transform.SetParent(canvasChild.transform);
// Saving a scene would trigger the error case 893551
EditorSceneManager.SaveScene(newScene, scenePath);
Debug.Log("Success");
LogAssert.Expect(LogType.Log, "Success");
}
[TearDown]
public void TearDown()
{
#if UNITY_EDITOR
AssetDatabase.DeleteAsset(scenePath);
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bede4033d9f359b41878c4cda6a910b3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,56 @@
using NUnit.Framework;
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UI;
internal class CanvasElementsMaintainValidPositionsWhenCameraOrthoSizeIsZero
{
GameObject image;
GameObject canvas;
GameObject camera;
[SetUp]
public void TestSetup()
{
canvas = new GameObject("Canvas", typeof(Canvas));
image = new GameObject("Image", typeof(Image));
image.transform.SetParent(canvas.transform);
camera = new GameObject("Camera", typeof(Camera));
var cameraComponent = camera.GetComponent<Camera>();
cameraComponent.orthographic = true;
var canvasComponent = canvas.GetComponent<Canvas>();
canvasComponent.worldCamera = camera.GetComponent<Camera>();
canvasComponent.renderMode = RenderMode.ScreenSpaceCamera;
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(canvas);
GameObject.DestroyImmediate(camera);
}
[UnityTest]
public IEnumerator TestCanvasElementsMaintainValidPositionsWhenCameraOrthoSizeIsZero()
{
var cameraComponent = camera.GetComponent<Camera>();
cameraComponent.orthographicSize = 0;
yield return null;
Assert.AreNotEqual(image.transform.position.x, float.NaN);
Assert.AreNotEqual(image.transform.position.y, float.NaN);
cameraComponent.orthographicSize = 2;
yield return null;
Assert.AreEqual(image.transform.position.x, 0.0f);
Assert.AreEqual(image.transform.position.y, 0.0f);
Assert.Pass();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 35a0d10199de49f4db0128003bfd3bda
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,39 @@
using NUnit.Framework;
using UnityEngine;
[Category("Canvas")]
internal class CanvasUseReflectionProbes : TestBehaviourBase<UnityEngine.Canvas>
{
[Test]
public void OnlyWorldSpaceCanvasCanUseReflectionProbes()
{
m_TestObject.useReflectionProbes = true;
m_TestObject.renderMode = RenderMode.ScreenSpaceOverlay;
Assert.False(m_TestObject.useReflectionProbes);
m_TestObject.renderMode = RenderMode.ScreenSpaceCamera;
Assert.False(m_TestObject.useReflectionProbes);
m_TestObject.renderMode = RenderMode.WorldSpace;
Assert.True(m_TestObject.useReflectionProbes);
}
[Test]
public void ProvidesNormals()
{
var dummyChannels = AdditionalCanvasShaderChannels.TexCoord1 | AdditionalCanvasShaderChannels.Tangent;
m_TestObject.renderMode = RenderMode.WorldSpace;
m_TestObject.additionalShaderChannels = dummyChannels;
m_TestObject.useReflectionProbes = false;
Assert.AreEqual(m_TestObject.additionalShaderChannels, dummyChannels);
m_TestObject.useReflectionProbes = true;
Assert.AreEqual(m_TestObject.additionalShaderChannels, dummyChannels | AdditionalCanvasShaderChannels.Normal);
m_TestObject.useReflectionProbes = false;
Assert.AreEqual(m_TestObject.additionalShaderChannels, dummyChannels);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 3cbc4280d63720c448a3c6fee4b1ec88
@@ -0,0 +1,47 @@
using UnityEngine;
using NUnit.Framework;
using UnityEngine.UI;
[TestFixture]
[Category("RegressionTest")]
[Description("CoveredBugID = 913932")]
internal class CanvasWidthAssertionErrorWithRectTransform
{
GameObject m_CanvasMaster;
GameObject m_CanvasChild;
[SetUp]
public void TestSetup()
{
m_CanvasMaster = new GameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
m_CanvasChild = new GameObject("Canvas", typeof(Canvas), typeof(CanvasScaler), typeof(GraphicRaycaster));
}
[Test]
public void CanvasWidthAssertionErrorCheckOnModifyingRectTransform()
{
// Creating canvas and child canvas
m_CanvasChild.transform.SetParent(m_CanvasMaster.transform);
// Getting the rect Transform and modifying it
RectTransform rt = m_CanvasChild.GetComponent<RectTransform>();
rt.anchorMin = new Vector2(0, 0);
rt.anchorMax = new Vector2(1, 1);
rt.offsetMin = new Vector2(rt.offsetMin.x, 1000);
rt.offsetMax = new Vector2(rt.offsetMax.x, 200);
rt.offsetMin = new Vector2(rt.offsetMin.y, 1);
rt.offsetMax = new Vector2(rt.offsetMax.y, 0);
//Assertion failed: Assertion failed on expression: 'width >= 0 should not happen
Assert.Pass();
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CanvasMaster);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4585b5feb801bdb44b0e5eafdd95a3be
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,131 @@
using NUnit.Framework;
using UnityEngine;
using UnityEngine.UI;
[Category("Canvas")]
internal class RootCanvasTests : TestBehaviourBase<UnityEngine.Canvas>
{
// A simple nested canvas hierarchy
// m_TestObject
// └ rootCanvasChild
// └ emptyChildGameObject
// └ baseCanvas
private UnityEngine.Canvas rootCanvasChild;
private GameObject emptyChildGameObject;
private UnityEngine.Canvas baseCanvas;
[SetUp]
public override void TestSetup()
{
base.TestSetup();
var rootChildGO = new GameObject("root child");
rootCanvasChild = rootChildGO.AddComponent<Canvas>();
emptyChildGameObject = new GameObject("empty");
var baseGO = new GameObject("base");
baseCanvas = baseGO.AddComponent<Canvas>();
baseCanvas.transform.SetParent(emptyChildGameObject.transform);
emptyChildGameObject.transform.SetParent(rootChildGO.transform);
rootChildGO.transform.SetParent(m_TestObject.transform);
}
[Test]
public void IsRootCanvasTest()
{
Assert.IsFalse(baseCanvas.isRootCanvas);
Assert.IsFalse(rootCanvasChild.isRootCanvas);
Assert.IsTrue(m_TestObject.isRootCanvas);
}
[Test]
public void CorrectRootCanvasReturned()
{
Assert.AreEqual(m_TestObject, m_TestObject.rootCanvas);
Assert.AreEqual(m_TestObject, rootCanvasChild.rootCanvas);
Assert.AreEqual(m_TestObject, baseCanvas.rootCanvas);
}
[Test]
public void NotRootCanvasAnchorsDontGetReset()
{
var rect = rootCanvasChild.GetComponent<RectTransform>();
rect.anchorMin = Vector2.zero;
rect.anchorMax = Vector2.one;
Assert.IsTrue(rect.anchorMin == Vector2.zero);
Assert.IsTrue(rect.anchorMax == Vector2.one);
m_TestObject.gameObject.SetActive(false);
Assert.IsTrue(rect.anchorMin == Vector2.zero);
Assert.IsTrue(rect.anchorMax == Vector2.one);
}
[Test]
public void ChildOfDisabledCanvasCantReceiveClicks()
{
rootCanvasChild.gameObject.AddComponent<Image>();
var raycasts = GraphicRegistry.GetRaycastableGraphicsForCanvas(rootCanvasChild);
Assert.IsTrue(raycasts.Count == 1);
m_TestObject.gameObject.SetActive(false);
raycasts = GraphicRegistry.GetRaycastableGraphicsForCanvas(rootCanvasChild);
Assert.IsTrue(raycasts.Count == 0);
}
[Test]
public void ChildrenInheritRootCanvasReflectionProbeProperties()
{
m_TestObject.useReflectionProbes = true;
m_TestObject.renderMode = RenderMode.WorldSpace;
// rootCanvasChild inherits properties from root
Assert.AreEqual(
rootCanvasChild.useReflectionProbes,
m_TestObject.useReflectionProbes);
Assert.AreEqual(
rootCanvasChild.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal,
m_TestObject.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal);
// baseCanvas inherits properties from root
Assert.AreEqual(
baseCanvas.useReflectionProbes,
m_TestObject.useReflectionProbes);
Assert.AreEqual(
baseCanvas.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal,
m_TestObject.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal);
}
[Test]
public void CannotOverrideRootCanvasReflectionProbeProperties()
{
m_TestObject.useReflectionProbes = true;
m_TestObject.renderMode = RenderMode.WorldSpace;
rootCanvasChild.useReflectionProbes = false;
rootCanvasChild.renderMode = RenderMode.ScreenSpaceOverlay;
rootCanvasChild.additionalShaderChannels = AdditionalCanvasShaderChannels.None;
// rootCanvasChild inherits properties from root
Assert.AreEqual(
rootCanvasChild.useReflectionProbes,
m_TestObject.useReflectionProbes);
Assert.AreEqual(
rootCanvasChild.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal,
m_TestObject.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal);
// baseCanvas inherits properties from root
Assert.AreEqual(
baseCanvas.useReflectionProbes,
m_TestObject.useReflectionProbes);
Assert.AreEqual(
baseCanvas.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal,
m_TestObject.additionalShaderChannels & AdditionalCanvasShaderChannels.Normal);
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 798968d841703b54bb9d08b1da6bc52f
timeCreated: 1459501500
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,14 @@
using UnityEngine;
using NUnit.Framework;
namespace Tests
{
internal class UISystemProfilerAddMarkerWithNullObjectDoesNotCrash
{
[Test]
public void AddMarkerShouldNotCrashWithNullObject()
{
UISystemProfilerApi.AddMarker("Test", null);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0ca81982e37e893498abf804c12a22c7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: ae242449e9279d44789513b922d3178a
folderAsset: yes
timeCreated: 1493922593
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,41 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEditor.SceneManagement;
internal class ChangingHierarchyOfCanvasRenderer
{
[Test]
public void ChangingHierarchyOfCanvasRenderer_DoesntCrash()
{
// Canvas
// - Middle
// - Renderer
// OtherCanvas
var canvasObject = new GameObject("Canvas");
canvasObject.AddComponent<Canvas>();
var otherCanvasObject = new GameObject("OtherCanvas");
otherCanvasObject.AddComponent<Canvas>();
var middleObject = new GameObject("Middle");
middleObject.transform.parent = canvasObject.transform;
var renderObject = new GameObject("Render");
renderObject.AddComponent<CanvasRenderer>();
renderObject.transform.parent = middleObject.transform;
renderObject.SetActive(false);
// Translation causes IgnoreNextTransformChanged to be set on Renderer
canvasObject.transform.Translate(1, 1, 1);
// Reparenting after ignore
middleObject.transform.parent = otherCanvasObject.transform;
// Destroy the original canvas, and create a new scene to force destruction of everything else
GameObject.DestroyImmediate(canvasObject);
EditorSceneManager.NewScene(NewSceneSetup.EmptyScene);
Assert.Pass();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c825bad77a42dd341a8f0a5ef9cd5f4c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,58 @@
using UnityEngine;
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
using UnityEngine.UI;
internal class ParentCanvasIsSane
{
GameObject rootCanvas;
GameObject rootObject;
GameObject child1;
CanvasGroup c1CanvasGroup;
GameObject child2;
GameObject child3;
[SetUp]
public void TestSetup()
{
// root GO
// root Canvas
// L child1 GO (RectTransform, CanvasGroup)
// L child2 GO (RectTransform)
// L child3 GO (Image)
rootCanvas = new GameObject("root Canvas");
rootCanvas.AddComponent<Canvas>();
rootCanvas.AddComponent<CanvasScaler>();
rootObject = new GameObject("root GO");
child1 = new GameObject("child1 GO");
child1.AddComponent<RectTransform>();
c1CanvasGroup = child1.AddComponent<CanvasGroup>();
child2 = new GameObject("child2 GO");
child2.AddComponent<RectTransform>();
child3 = new GameObject("child3 GO");
child3.AddComponent<Image>();
child3.transform.SetParent(child2.transform);
child2.transform.SetParent(child1.transform);
child1.transform.SetParent(rootCanvas.transform);
}
[UnityTest]
public IEnumerator RecalculatingAlphaOnReparentedInactiveObjectsDoesNotCrash()
{
Assert.IsNotNull(child3.GetComponent<CanvasRenderer>());
c1CanvasGroup.alpha = 0.5f;
child1.SetActive(false);
child1.transform.SetParent(rootObject.transform, true);
// This will crash if child3.GetComponent<CanvasRenderer>().m_ParentCanvas is not null.
yield return null;
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: dcb49b07db5e5f64e876b498105314f1
timeCreated: 1493922633
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1f71aeacc4a9f1a40b22a1a590331f6b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,34 @@
using System.Collections;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEditor;
using NUnit.Framework;
internal class DropdownOptionsListDrawer : WrapperWindowFixture
{
internal class Fixture : MonoBehaviour
{
public Dropdown.OptionDataList options = new Dropdown.OptionDataList();
}
[UnityTest]
public IEnumerator PropertyDrawerDoesNotThrowExceptionWhenObjectIsDisposed()
{
var go = new GameObject();
var component = go.AddComponent<Fixture>();
var so = new SerializedObject(component);
var win = GetWindow((wnd) => {
Assert.DoesNotThrow(() => EditorGUILayout.PropertyField(so.FindProperty("options")));
so.Dispose();
so = new SerializedObject(component);
Assert.DoesNotThrow(() => EditorGUILayout.PropertyField(so.FindProperty("options")));
return true;
});
while (win.TestCompleted == false)
{
yield return null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b180d0cec21671c45a32a9ce99bff2f5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 98d14ab1acf42df4f88a0561822ac807
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
using NUnit.Framework;
using UnityEngine;
using UnityEngine.EventSystems;
internal class EventTriggerRemoveDuringExecution
{
[Test]
[Description("ArgumentOutOfRange Exception is thrown when removing handler in callback in EventTrigger (case 1401557)")]
public void EventTrigger_DoesNotThrowExceptionWhenRemovingEventDuringExecution()
{
var go = new GameObject();
var eventTrigger = go.AddComponent<EventTrigger>();
var eventSystem = go.AddComponent<EventSystem>();
var entry1 = new EventTrigger.Entry { eventID = EventTriggerType.PointerDown };
var entry2 = new EventTrigger.Entry { eventID = EventTriggerType.PointerDown };
bool executed1 = false;
bool executed2 = false;
entry1.callback.AddListener(e =>
{
executed1 = true;
eventTrigger.triggers.Remove(entry2);
});
entry2.callback.AddListener(e => executed2 = true);
eventTrigger.triggers.Add(entry1);
eventTrigger.triggers.Add(entry2);
Assert.DoesNotThrow(() => eventTrigger.OnPointerDown(new PointerEventData(eventSystem)));
Assert.True(executed1, "Expected Event 1 to be called but it was not.");
Assert.False(executed2, "Expected Event 2 to not be called as it was removed by event 1.");
Assert.That(eventTrigger.triggers, Does.Not.Contains(entry2));
Assert.That(eventTrigger.triggers, Does.Contain(entry1));
Object.DestroyImmediate(go);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4adb1f65bbae8004a88d8f5bc3523298
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,55 @@
using NUnit.Framework;
using UnityEngine;
using UnityEditor.EventSystems;
using UnityEngine.EventSystems;
[TestFixture]
internal class InputModuleTests
{
private EventSystem m_EventSystem;
[SetUp]
public void Setup()
{
m_EventSystem = new GameObject("EventSystem").AddComponent<EventSystem>();
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_EventSystem.gameObject);
}
[Test]
public void InputModuleComponentFactory_AddComponent_CanBeOverriden()
{
// Reset the current override
var current = InputModuleComponentFactory.InputModuleComponentOverride;
InputModuleComponentFactory.SetInputModuleComponentOverride(null);
// First call creates a StandaloneInputModule
var inputModule = InputModuleComponentFactory.AddInputModule(m_EventSystem.gameObject);
Assert.IsInstanceOf<StandaloneInputModule>(inputModule);
Object.DestroyImmediate(inputModule);
// After setting the override to a custom type, further calls use the custom type
InputModuleComponentFactory.SetInputModuleComponentOverride(go => go.AddComponent<TestInputModule>());
inputModule = InputModuleComponentFactory.AddInputModule(m_EventSystem.gameObject);
Assert.IsInstanceOf<TestInputModule>(inputModule);
Object.DestroyImmediate(inputModule);
// After setting the override to null, further calls use the StandaloneInputModule again
InputModuleComponentFactory.SetInputModuleComponentOverride(null);
inputModule = InputModuleComponentFactory.AddInputModule(m_EventSystem.gameObject);
Assert.IsInstanceOf<StandaloneInputModule>(inputModule);
Object.DestroyImmediate(inputModule);
// Set it back to it's original value
InputModuleComponentFactory.SetInputModuleComponentOverride(current);
}
internal class TestInputModule : BaseInputModule
{
public override void Process() { }
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 03fb1af6e1585964a8d5c2437a191324
@@ -0,0 +1,82 @@
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using UnityEngine.EventSystems;
using UnityEditor;
using NUnit.Framework;
#if UNITY_6000_5_OR_NEWER
using UnityEngine.Assemblies;
#endif
internal class InterceptedEventsPreviewTests
{
[Test]
public void InterceptedEventsPreviewCacheUsingTypeCacheReturnsSameTypes()
{
var typeCacheEventInterfaces = new List<Type>();
TypeCache.TypeCollection types = TypeCache.GetTypesDerivedFrom<IEventSystemHandler>();
foreach (var type in types)
{
if (!type.IsInterface)
continue;
typeCacheEventInterfaces.Add(type);
}
var appDomainEventInterfaces = new List<Type>();
foreach (var type in GetAccessibleTypesInLoadedAssemblies())
{
if (!type.IsInterface)
continue;
appDomainEventInterfaces.Add(type);
}
Assert.AreNotEqual(typeCacheEventInterfaces.Count, appDomainEventInterfaces.Count, "Did not find the same number of EventInterface types");
for (int i = 0; i < typeCacheEventInterfaces.Count; ++i)
{
Assert.Contains(typeCacheEventInterfaces[i], appDomainEventInterfaces);
}
}
private static IEnumerable<Type> GetAccessibleTypesInLoadedAssemblies()
{
#if UNITY_6000_5_OR_NEWER
var assemblies = CurrentAssemblies.GetLoadedAssemblies().ToArray();
#else
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
#endif
for (var i = 0; i < assemblies.Length; ++i)
{
Type[] types;
var assembly = assemblies[i];
if (assembly == null)
continue;
try
{
types = assembly.GetTypes();
}
catch (ReflectionTypeLoadException e)
{
// assembly.GetTypes() might fail in case the Assembly cannot resolve all its references,
// or in case it was built targetting a newer version of .NET.
// In case the resolution fails for some types, we can still access the ones that have been
// properly loaded.
types = e.Types;
}
for (var j = 0; j < types.Length; ++j)
{
var type = types[j];
if (type == null)
continue;
yield return type;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2aff4fada0516c64a8537a20bfe1b699
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c16c54fe03afb5740bcc0a2a295cb79d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,45 @@
using NUnit.Framework;
namespace Core.InputField
{
internal class CharacterLimitValidation : TestBehaviourBase<UnityEngine.UI.InputField>
{
[Test]
public void LimitCanNotBeNegative()
{
const int testValue = -1;
m_TestObject.characterLimit = testValue;
Assert.AreNotEqual(testValue, m_TestObject.characterLimit);
}
[Test]
public void TextLengthShorterThanLimit()
{
const string testValue = "Test";
m_TestObject.characterLimit = 10;
m_TestObject.text = testValue;
Assert.AreEqual(testValue, m_TestObject.text);
}
[Test]
public void TextLengthEqualToLimit()
{
const string testValue = "0123456789";
m_TestObject.characterLimit = 10;
m_TestObject.text = testValue;
Assert.AreEqual(testValue, m_TestObject.text);
}
[Test]
public void TextLengthGreaterThanLimit()
{
m_TestObject.characterLimit = 10;
m_TestObject.text = "01234567891234567890";
Assert.AreEqual(10, m_TestObject.text.Length);
Assert.AreEqual("0123456789", m_TestObject.text);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4b8be68229770db4ea3c78ab0d854325
timeCreated: 1456921340
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,93 @@
using NUnit.Framework;
using ContentType = UnityEngine.UI.InputField.ContentType;
namespace Core.InputField
{
internal class ContentValidation : TestBehaviourBase<UnityEngine.UI.InputField>
{
[Test]
[TestCase(ContentType.Alphanumeric, "0", "0")]
[TestCase(ContentType.Alphanumeric, "1", "1")]
[TestCase(ContentType.Alphanumeric, "123456", "123456")]
[TestCase(ContentType.Alphanumeric, "0123456", "0123456")]
[TestCase(ContentType.Alphanumeric, "111110123456", "111110123456")]
[TestCase(ContentType.Alphanumeric, "-1.0", "10")]
[TestCase(ContentType.Alphanumeric, "-00.45", "0045")]
[TestCase(ContentType.Alphanumeric, "-1111101.23456", "111110123456")]
[TestCase(ContentType.Alphanumeric, "Test", "Test")]
[TestCase(ContentType.Alphanumeric, "-1-", "1")]
[TestCase(ContentType.Alphanumeric, "--1", "1")]
[TestCase(ContentType.Alphanumeric, "123456abc", "123456abc")]
[TestCase(ContentType.Alphanumeric, "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789", "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789")]
[TestCase(ContentType.DecimalNumber, "0", "0")]
[TestCase(ContentType.DecimalNumber, "1", "1")]
[TestCase(ContentType.DecimalNumber, "123456", "123456")]
[TestCase(ContentType.DecimalNumber, "0123456", "0123456")]
[TestCase(ContentType.DecimalNumber, "111110123456", "111110123456")]
//[TestCase(ContentType.DecimalNumber, "3.14", "3.14")]
//[TestCase(ContentType.DecimalNumber, "1.23", "1.23")]
//[TestCase(ContentType.DecimalNumber, "1.0", "1.0")]
//[TestCase(ContentType.DecimalNumber, "00.45", "00.45")]
//[TestCase(ContentType.DecimalNumber, "1111101.23456", "1111101.23456")]
//[TestCase(ContentType.DecimalNumber, "-1", "-1")]
[TestCase(ContentType.DecimalNumber, "-123456", "-123456")]
[TestCase(ContentType.DecimalNumber, "-0123456", "-0123456")]
[TestCase(ContentType.DecimalNumber, "-111110123456", "-111110123456")]
//[TestCase(ContentType.DecimalNumber, "-3.14", "-3.14")]
//[TestCase(ContentType.DecimalNumber, "-1.23", "-1.23")]
//[TestCase(ContentType.DecimalNumber, "-1.0", "-1.0")]
//[TestCase(ContentType.DecimalNumber, "-00.45", "-00.45")]
//[TestCase(ContentType.DecimalNumber, "-1111101.23456", "-1111101.23456")]
[TestCase(ContentType.DecimalNumber, "Test", "")]
[TestCase(ContentType.DecimalNumber, "-1-", "-1")]
//[TestCase(ContentType.DecimalNumber, "-0", "0")]
[TestCase(ContentType.DecimalNumber, "--1", "-1")]
[TestCase(ContentType.DecimalNumber, "123456abc", "123456")]
//[TestCase(ContentType.DecimalNumber, "12.34.5#6abc", "12.3456")]
[TestCase(ContentType.EmailAddress, "name@domain.com", "name@domain.com")]
[TestCase(ContentType.EmailAddress, "name@@@domain.com", "name@domain.com")]
[TestCase(ContentType.EmailAddress, "name@domain.co.uk", "name@domain.co.uk")]
[TestCase(ContentType.EmailAddress, "name.other@domain-site.co.uk", "name.other@domain-site.co.uk")]
[TestCase(ContentType.EmailAddress, "name!#$%&'*+-/=?^_`{|}~@domain.com", "name!#$%&'*+-/=?^_`{|}~@domain.com")]
[TestCase(ContentType.IntegerNumber, "0", "0")]
[TestCase(ContentType.IntegerNumber, "1", "1")]
[TestCase(ContentType.IntegerNumber, "123456", "123456")]
[TestCase(ContentType.IntegerNumber, "0123456", "0123456")]
[TestCase(ContentType.IntegerNumber, "111110123456", "111110123456")]
[TestCase(ContentType.IntegerNumber, "-1", "-1")]
[TestCase(ContentType.IntegerNumber, "-123456", "-123456")]
[TestCase(ContentType.IntegerNumber, "-0123456", "-0123456")]
[TestCase(ContentType.IntegerNumber, "-111110123456", "-111110123456")]
[TestCase(ContentType.IntegerNumber, "3.14", "314")]
[TestCase(ContentType.IntegerNumber, "Test", "")]
[TestCase(ContentType.IntegerNumber, "-1-", "-1")]
//[TestCase(ContentType.IntegerNumber, "-0", "0")]
//[TestCase(ContentType.IntegerNumber, "-0", "")]
[TestCase(ContentType.IntegerNumber, "--1", "-1")]
[TestCase(ContentType.IntegerNumber, "123456abc", "123456")]
[TestCase(ContentType.IntegerNumber, "12.34.5#6abc", "123456")]
[TestCase(ContentType.Name, "john smith", "John Smith")]
[TestCase(ContentType.Name, "mary jane", "Mary Jane")]
[TestCase(ContentType.Name, "jOHn smIth", "John Smith")]
[TestCase(ContentType.Name, "john123 smith123", "John Smith")]
[TestCase(ContentType.Name, "Bucky O'Hare", "Bucky O'Hare")]
[TestCase(ContentType.Name, "bucky o'Har'e", "Bucky O'Hare")]
[TestCase(ContentType.Name, "first second third", "First Second Third")]
[TestCase(ContentType.Pin, "012345", "012345")]
[TestCase(ContentType.Pin, "012345abc", "012345")]
[TestCase(ContentType.Pin, "0a1b2c3#45", "012345")]
[TestCase(ContentType.Pin, "-012345", "-012345")]
[TestCase(ContentType.Pin, " 012345", "012345")]
public void ValueIsValidatedCorrectly(ContentType type, string testValue, string expected)
{
m_TestObject.contentType = type;
m_TestObject.text = testValue;
Assert.AreEqual(expected, m_TestObject.text);
}
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 5a2e98b03511c6f43bc645238cd40857
timeCreated: 1457018121
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e191a1662a374793b8c6b74f0d60ca39
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,166 @@
using NUnit.Framework;
using UnityEngine;
using UnityEngine.UI;
namespace UnityEditor.UI.Tests
{
internal class LayoutUtilitySourceTests
{
GameObject m_GameObject;
RectTransform m_RectTransform;
LayoutElement m_FirstElement;
LayoutElement m_SecondElement;
[SetUp]
public void SetUp()
{
m_GameObject = new GameObject("LayoutElement", typeof(RectTransform));
m_RectTransform = (RectTransform)m_GameObject.transform;
m_FirstElement = m_GameObject.AddComponent<LayoutElement>();
m_SecondElement = m_GameObject.AddComponent<LayoutElement>();
}
[TearDown]
public void TearDown()
{
Object.DestroyImmediate(m_GameObject);
}
// Two same-priority elements with a min each resolve to the larger min, from its element.
[Test]
public void MinSize_SamePriorityElements_ReportsLargestMinAndItsElement()
{
m_FirstElement.minWidth = 100;
m_FirstElement.minHeight = 40;
m_SecondElement.minWidth = 50;
m_SecondElement.minHeight = 20;
float minWidth = LayoutUtility.GetMinWidth(m_RectTransform, out var widthSource);
float minHeight = LayoutUtility.GetMinHeight(m_RectTransform, out var heightSource);
Assert.AreEqual(LayoutUtility.GetMinWidth(m_RectTransform), minWidth, "Min Width should match the value layout uses.");
Assert.AreEqual(LayoutUtility.GetMinHeight(m_RectTransform), minHeight, "Min Height should match the value layout uses.");
Assert.AreEqual(100f, minWidth, "Min Width should be the larger min.");
Assert.AreEqual(40f, minHeight, "Min Height should be the larger min.");
Assert.AreSame(m_FirstElement, widthSource, "Min Width source should be the element with the larger min.");
Assert.AreSame(m_FirstElement, heightSource, "Min Height source should be the element with the larger min.");
}
// With no max size enabled, max resolves to Infinity with no source element.
[Test]
public void MaxSize_WithoutMaxEnabled_ReportsInfinityAndNoSource()
{
m_FirstElement.preferredWidth = 100;
float maxWidth = LayoutUtility.GetMaxWidth(m_RectTransform, out var widthSource);
float maxHeight = LayoutUtility.GetMaxHeight(m_RectTransform, out var heightSource);
Assert.AreEqual(float.PositiveInfinity, maxWidth, "Max Width should default to Infinity when unset.");
Assert.AreEqual(float.PositiveInfinity, maxHeight, "Max Height should default to Infinity when unset.");
Assert.IsNull(widthSource, "Max Width should have no source when unset.");
Assert.IsNull(heightSource, "Max Height should have no source when unset.");
}
// Two same-priority elements with a max each resolve to the smaller max, from its element.
[Test]
public void MaxSize_SamePriorityElements_ReportsSmallestMaxAndItsElement()
{
m_FirstElement.maxWidth = 300;
m_FirstElement.maxHeight = 80;
m_SecondElement.maxWidth = 200;
m_SecondElement.maxHeight = 50;
float maxWidth = LayoutUtility.GetMaxWidth(m_RectTransform, out var widthSource);
float maxHeight = LayoutUtility.GetMaxHeight(m_RectTransform, out var heightSource);
Assert.AreEqual(LayoutUtility.GetMaxWidth(m_RectTransform), maxWidth, "Max Width should match the value layout uses.");
Assert.AreEqual(LayoutUtility.GetMaxHeight(m_RectTransform), maxHeight, "Max Height should match the value layout uses.");
Assert.AreEqual(200f, maxWidth, "Max Width should be the smaller max.");
Assert.AreEqual(50f, maxHeight, "Max Height should be the smaller max.");
Assert.AreSame(m_SecondElement, widthSource, "Max Width source should be the element with the smaller max.");
Assert.AreSame(m_SecondElement, heightSource, "Max Height source should be the element with the smaller max.");
}
// A preferred size inside the min/max bounds is reported as is, from its own element.
[Test]
public void PreferredSize_WithinBounds_ReportsPreferredAndItsElement()
{
m_FirstElement.minWidth = 10;
m_FirstElement.minHeight = 10;
m_FirstElement.maxWidth = 500;
m_FirstElement.maxHeight = 500;
m_SecondElement.preferredWidth = 120;
m_SecondElement.preferredHeight = 60;
float preferredWidth = LayoutUtility.GetPreferredWidth(m_RectTransform, out var widthSource);
float preferredHeight = LayoutUtility.GetPreferredHeight(m_RectTransform, out var heightSource);
Assert.AreEqual(LayoutUtility.GetPreferredWidth(m_RectTransform), preferredWidth, "Preferred Width should match the value layout uses.");
Assert.AreEqual(LayoutUtility.GetPreferredHeight(m_RectTransform), preferredHeight, "Preferred Height should match the value layout uses.");
Assert.AreEqual(120f, preferredWidth, "Preferred Width should be unchanged inside the bounds.");
Assert.AreEqual(60f, preferredHeight, "Preferred Height should be unchanged inside the bounds.");
Assert.AreSame(m_SecondElement, widthSource, "Preferred Width source should be the element supplying the preferred size.");
Assert.AreSame(m_SecondElement, heightSource, "Preferred Height source should be the element supplying the preferred size.");
}
// A preferred size below the min resolves to the min, from the min's element.
[Test]
public void PreferredSize_BelowMin_ReportsMinAndMinElement()
{
m_FirstElement.minWidth = 100;
m_FirstElement.minHeight = 40;
m_SecondElement.preferredWidth = 50;
m_SecondElement.preferredHeight = 20;
float preferredWidth = LayoutUtility.GetPreferredWidth(m_RectTransform, out var widthSource);
float preferredHeight = LayoutUtility.GetPreferredHeight(m_RectTransform, out var heightSource);
Assert.AreEqual(LayoutUtility.GetPreferredWidth(m_RectTransform), preferredWidth, "Preferred Width should match the value layout uses.");
Assert.AreEqual(LayoutUtility.GetPreferredHeight(m_RectTransform), preferredHeight, "Preferred Height should match the value layout uses.");
Assert.AreEqual(100f, preferredWidth, "Preferred Width should be raised to the min.");
Assert.AreEqual(40f, preferredHeight, "Preferred Height should be raised to the min.");
Assert.AreSame(m_FirstElement, widthSource, "Preferred Width source should be the element supplying the min.");
Assert.AreSame(m_FirstElement, heightSource, "Preferred Height source should be the element supplying the min.");
}
// A preferred size above the max resolves to the max, from the max's element.
[Test]
public void PreferredSize_AboveMax_ReportsMaxAndMaxElement()
{
m_FirstElement.preferredWidth = 300;
m_FirstElement.preferredHeight = 90;
m_SecondElement.maxWidth = 200;
m_SecondElement.maxHeight = 50;
float preferredWidth = LayoutUtility.GetPreferredWidth(m_RectTransform, out var widthSource);
float preferredHeight = LayoutUtility.GetPreferredHeight(m_RectTransform, out var heightSource);
Assert.AreEqual(LayoutUtility.GetPreferredWidth(m_RectTransform), preferredWidth, "Preferred Width should match the value layout uses.");
Assert.AreEqual(LayoutUtility.GetPreferredHeight(m_RectTransform), preferredHeight, "Preferred Height should match the value layout uses.");
Assert.AreEqual(200f, preferredWidth, "Preferred Width should be clamped to the max.");
Assert.AreEqual(50f, preferredHeight, "Preferred Height should be clamped to the max.");
Assert.AreSame(m_SecondElement, widthSource, "Preferred Width source should be the element supplying the max.");
Assert.AreSame(m_SecondElement, heightSource, "Preferred Height source should be the element supplying the max.");
}
// Two same-priority elements with a flexible size each resolve to the larger one, from its element.
[Test]
public void FlexibleSize_SamePriorityElements_ReportsLargestFlexibleAndItsElement()
{
m_FirstElement.flexibleWidth = 1;
m_FirstElement.flexibleHeight = 1;
m_SecondElement.flexibleWidth = 3;
m_SecondElement.flexibleHeight = 2;
float flexibleWidth = LayoutUtility.GetFlexibleWidth(m_RectTransform, out var widthSource);
float flexibleHeight = LayoutUtility.GetFlexibleHeight(m_RectTransform, out var heightSource);
Assert.AreEqual(LayoutUtility.GetFlexibleWidth(m_RectTransform), flexibleWidth, "Flexible Width should match the value layout uses.");
Assert.AreEqual(LayoutUtility.GetFlexibleHeight(m_RectTransform), flexibleHeight, "Flexible Height should match the value layout uses.");
Assert.AreEqual(3f, flexibleWidth, "Flexible Width should be the larger flexible size.");
Assert.AreEqual(2f, flexibleHeight, "Flexible Height should be the larger flexible size.");
Assert.AreSame(m_SecondElement, widthSource, "Flexible Width source should be the element with the larger flexible size.");
Assert.AreSame(m_SecondElement, heightSource, "Flexible Height source should be the element with the larger flexible size.");
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 20aa4b11d3234ba388103659e9e2e310
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 305ca32be1aa5504aa182f583895dfe4
folderAsset: yes
timeCreated: 1458135852
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,42 @@
using NUnit.Framework;
using UnityEngine;
using UnityEngine.UI;
internal class RectMask2DCulling : TestBehaviourBase<UnityEngine.Canvas>
{
[Test]
public void CullFlagNotResetWhenReparented740604()
{
var noMaskGameObject = new GameObject("noMaskGO");
noMaskGameObject.AddComponent<RectTransform>();
var maskGameObject = new GameObject("MaskGO");
var rectMask2D = maskGameObject.AddComponent<RectMask2D>();
noMaskGameObject.transform.SetParent(m_TestObject.transform);
maskGameObject.transform.SetParent(m_TestObject.transform);
noMaskGameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(800, 800);
maskGameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(400, 400);
var imageGameObject = new GameObject("ImageGO");
var image = imageGameObject.AddComponent<Image>();
imageGameObject.transform.SetParent(maskGameObject.transform);
imageGameObject.GetComponent<RectTransform>().sizeDelta = new Vector2(100, 100);
// Start with image inside RectMask2D area so that it's no culled
rectMask2D.PerformClipping();
Assert.IsFalse(image.canvasRenderer.cull);
// Move image outside of RectMask2D so that it is culled
imageGameObject.GetComponent<RectTransform>().position = new Vector2(275, 275);
rectMask2D.PerformClipping();
Assert.IsTrue(image.canvasRenderer.cull);
// Change parent to noMask so that it's unaffected by RectMask2D and isn't culled
imageGameObject.transform.SetParent(noMaskGameObject.transform);
rectMask2D.PerformClipping();
Assert.IsFalse(image.canvasRenderer.cull);
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 4402dcee6e9969549bf5b33f11533208
timeCreated: 1458135886
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,18 @@
using UnityEngine;
using NUnit.Framework;
internal class RectTransformPosition
{
[Test]
public void SettingPositionBeforeGameObjectIsActivatedWorks_953409()
{
var positionToSet = new Vector3(1, 2, 3);
var go = new GameObject("RectTransform", typeof(RectTransform));
go.SetActive(false);
go.transform.position = positionToSet;
go.SetActive(true);
Assert.AreEqual(positionToSet, go.transform.position, "Expected RectTransform position to be set but it was not.");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fb660d86885d89a499a31c6ab6f26269
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 16c7d1f4783e4042b974149dd463f76e
timeCreated: 1779078712
@@ -0,0 +1,223 @@
using System.Reflection;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UI;
namespace SafeAreaTests
{
internal class SafeAreaDrivenOwnershipTests
{
// EditMode tests don't tick the player loop, so SafeArea.Update never fires on its own.
// Invoke it directly to exercise the reclaim-on-poll path.
private static readonly MethodInfo s_SafeAreaUpdate =
typeof(SafeArea).GetMethod("Update", BindingFlags.NonPublic | BindingFlags.Instance);
private GameObject _canvasGo;
private GameObject _parentGo;
private RectTransform _parentRect;
private GameObject _targetGo;
private RectTransform _targetRect;
private SafeArea _safeArea;
[SetUp]
public void SetUp()
{
_canvasGo = new GameObject("Canvas", typeof(RectTransform), typeof(Canvas));
_parentGo = new GameObject("Parent", typeof(RectTransform));
_parentGo.transform.SetParent(_canvasGo.transform, false);
_parentRect = _parentGo.GetComponent<RectTransform>();
_targetGo = new GameObject("Target", typeof(RectTransform), typeof(SafeArea));
_targetGo.transform.SetParent(_parentGo.transform, false);
_targetRect = _targetGo.GetComponent<RectTransform>();
_safeArea = _targetGo.GetComponent<SafeArea>();
}
[TearDown]
public void TearDown()
{
if (_canvasGo != null)
Object.DestroyImmediate(_canvasGo);
}
private void TickSafeAreaUpdate() => s_SafeAreaUpdate.Invoke(_safeArea, null);
[Test]
public void ContentSizeFitter_DrivesRect_SafeAreaDoesNotHijack_AndReclaimsWhenFitterDisabled()
{
var fitter = _targetGo.AddComponent<ContentSizeFitter>();
fitter.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
fitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
LayoutRebuilder.ForceRebuildLayoutImmediate(_targetRect);
Assert.AreEqual(fitter, _targetRect.drivenByObject);
_safeArea.enabled = false;
_safeArea.enabled = true;
Assert.AreEqual(fitter, _targetRect.drivenByObject, "SafeArea should not hijack driven ownership while ContentSizeFitter is driving.");
fitter.enabled = false;
TickSafeAreaUpdate();
Assert.AreEqual(_safeArea, _targetRect.drivenByObject, "SafeArea should reclaim driven ownership after ContentSizeFitter is disabled.");
}
[Test]
public void ParentLayoutGroup_DrivesRect_SafeAreaDoesNotHijack_AndReclaimsWhenLayoutDisabled()
{
var layout = _parentGo.AddComponent<HorizontalLayoutGroup>();
LayoutRebuilder.ForceRebuildLayoutImmediate(_parentRect);
Assert.AreEqual(layout, _targetRect.drivenByObject);
_safeArea.enabled = false;
_safeArea.enabled = true;
Assert.AreEqual(layout, _targetRect.drivenByObject, "SafeArea should not hijack driven ownership while parent layout group is driving.");
layout.enabled = false;
TickSafeAreaUpdate();
Assert.AreEqual(_safeArea, _targetRect.drivenByObject, "SafeArea should reclaim driven ownership after parent layout group is disabled.");
}
[Test]
public void Scrollbar_DrivesRect_SafeAreaDoesNotHijack_AndReclaimsWhenScrollbarDisabled()
{
var scrollbarGo = new GameObject("ScrollbarHost", typeof(RectTransform), typeof(Image), typeof(Scrollbar));
scrollbarGo.transform.SetParent(_canvasGo.transform, false);
var scrollbar = scrollbarGo.GetComponent<Scrollbar>();
scrollbar.handleRect = _targetRect;
Assert.AreEqual(scrollbar, _targetRect.drivenByObject);
_safeArea.enabled = false;
_safeArea.enabled = true;
Assert.AreEqual(scrollbar, _targetRect.drivenByObject, "SafeArea should not hijack driven ownership while Scrollbar is driving.");
scrollbar.enabled = false;
TickSafeAreaUpdate();
Assert.AreEqual(_safeArea, _targetRect.drivenByObject, "SafeArea should reclaim driven ownership after Scrollbar is disabled.");
Object.DestroyImmediate(scrollbarGo);
}
[Test]
public void ReEnablingSafeArea_DoesNotHijack_WhenAnotherDriverExists_OnSameObject()
{
var fitter = _targetGo.AddComponent<ContentSizeFitter>();
fitter.horizontalFit = ContentSizeFitter.FitMode.PreferredSize;
fitter.verticalFit = ContentSizeFitter.FitMode.PreferredSize;
LayoutRebuilder.ForceRebuildLayoutImmediate(_targetRect);
Assert.AreEqual(fitter, _targetRect.drivenByObject);
_safeArea.enabled = false;
_safeArea.enabled = true;
Assert.AreEqual(fitter, _targetRect.drivenByObject);
}
[Test]
public void ReEnablingSafeArea_DoesNotHijack_WhenAnotherDriverExists_OnParent()
{
var layout = _parentGo.AddComponent<VerticalLayoutGroup>();
LayoutRebuilder.ForceRebuildLayoutImmediate(_parentRect);
Assert.AreEqual(layout, _targetRect.drivenByObject);
_safeArea.enabled = false;
_safeArea.enabled = true;
Assert.AreEqual(layout, _targetRect.drivenByObject);
}
[Test]
public void ReEnablingSafeArea_DoesNotHijack_WhenAnotherDriverExists_OnAnotherObject()
{
var scrollbarGo = new GameObject("ScrollbarHost", typeof(RectTransform), typeof(Image), typeof(Scrollbar));
scrollbarGo.transform.SetParent(_canvasGo.transform, false);
var scrollbar = scrollbarGo.GetComponent<Scrollbar>();
scrollbar.handleRect = _targetRect;
Assert.AreEqual(scrollbar, _targetRect.drivenByObject);
_safeArea.enabled = false;
_safeArea.enabled = true;
Assert.AreEqual(scrollbar, _targetRect.drivenByObject);
Object.DestroyImmediate(scrollbarGo);
}
[Test]
public void AddingSecondSafeArea_DoesNotHijackDrivenOwnership()
{
Assert.AreEqual(_safeArea, _targetRect.drivenByObject);
LogAssert.Expect(LogType.Log, $"Can't add 'SafeArea' to {_targetGo.name} because a 'SafeArea' is already added to the game object!");
var secondSafeArea = _targetGo.AddComponent<SafeArea>();
Assert.IsNull(secondSafeArea, "DisallowMultipleComponent should prevent a second SafeArea.");
Assert.AreEqual(_safeArea, _targetRect.drivenByObject, "Original SafeArea should retain ownership.");
}
[Test]
public void SafeArea_ReclaimsOwnership_WhenDriverReleasesWithoutDisable()
{
var scrollbarGo = new GameObject("ScrollbarHost", typeof(RectTransform), typeof(Image), typeof(Scrollbar));
scrollbarGo.transform.SetParent(_canvasGo.transform, false);
var scrollbar = scrollbarGo.GetComponent<Scrollbar>();
scrollbar.handleRect = _targetRect;
Assert.AreEqual(scrollbar, _targetRect.drivenByObject);
scrollbar.handleRect = null;
TickSafeAreaUpdate();
Assert.AreEqual(_safeArea, _targetRect.drivenByObject, "SafeArea should reclaim ownership once external driver releases the rect.");
Object.DestroyImmediate(scrollbarGo);
}
[Test]
public void ReEnable_ClaimsRectTransformDrivenOwnership()
{
_safeArea.enabled = true;
Assert.AreEqual(_safeArea, _targetRect.drivenByObject, "SafeArea should claim RectTransform driven ownership when enabled");
_safeArea.enabled = false;
Assert.IsNull(_targetRect.drivenByObject, "SafeArea should not claim RectTransform driven ownership when disabled");
_safeArea.enabled = true;
Assert.AreEqual(_safeArea, _targetRect.drivenByObject, "SafeArea should reclaim RectTransform driven ownership when enabled");
}
[Test]
public void Destroy_ClearsRectTransformDrivenOwnership()
{
_safeArea.enabled = true;
Assert.AreEqual(_safeArea, _targetRect.drivenByObject);
Assert.DoesNotThrow(() =>
{
Object.DestroyImmediate(_safeArea);
});
Assert.IsNull(_targetRect.drivenByObject);
_safeArea = null;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 05d51b1b98bf446529d00e99fbdd33b9
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 4cfe5ade9a1375e40aed87618b92bd12
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,54 @@
using NUnit.Framework;
using UnityEngine.UI;
using UnityEngine;
[Category("Slider")]
internal class SliderRectRefernces : Behaviour
{
private Slider slider;
private GameObject emptyGO;
private GameObject rootGO;
[SetUp]
public void TestSetup()
{
rootGO = new GameObject("root child");
rootGO.AddComponent<Canvas>();
var sliderGameObject = new GameObject("Slider");
slider = sliderGameObject.AddComponent<Slider>();
emptyGO = new GameObject("base", typeof(RectTransform));
sliderGameObject.transform.SetParent(rootGO.transform);
emptyGO.transform.SetParent(sliderGameObject.transform);
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(rootGO);
}
[Test]
public void AssigningSelfResultsInNullReferenceField()
{
slider.fillRect = (RectTransform)slider.transform;
Assert.IsNull(slider.fillRect);
slider.handleRect = (RectTransform)slider.transform;
Assert.IsNull(slider.handleRect);
}
[Test]
public void AssigningOtherObjectResultsInCorrectReferenceField()
{
slider.fillRect = (RectTransform)emptyGO.transform;
Assert.IsNotNull(slider.fillRect);
Assert.AreEqual(slider.fillRect, (RectTransform)emptyGO.transform);
slider.handleRect = (RectTransform)emptyGO.transform;
Assert.IsNotNull(slider.handleRect);
Assert.AreEqual(slider.handleRect, (RectTransform)emptyGO.transform);
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 373b4c78c0396334288fa5ff8e7b7350
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
using NUnit.Framework;
using UnityEngine;
internal class TestBehaviourBase<T> where T : Behaviour
{
protected T m_TestObject;
[SetUp]
public virtual void TestSetup()
{
var gameObject = new GameObject();
m_TestObject = gameObject.AddComponent<T>();
}
[TearDown]
public virtual void Teardown()
{
GameObject.DestroyImmediate(m_TestObject.gameObject);
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 393b15da08c88194dbbcacd6ee15a89c
timeCreated: 1456926887
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 4f9ac6e545d53f94b9f09c85b9576f36
folderAsset: yes
timeCreated: 1485515713
licenseType: Pro
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,60 @@
using System;
using NUnit.Framework;
using UnityEngine;
[Category("Text")]
internal class FontCreatedByScript
{
static Font CreateDefaultFontWithOneCharacter(int character)
{
var font = new Font();
CharacterInfo[] characterInfo = new CharacterInfo[1];
characterInfo[0].index = character;
font.characterInfo = characterInfo;
return font;
}
[Test]
public static void GetCharacterInfo_FindsCharacterInfoThatIsInSet()
{
char character = 'A';
int charIndex = Convert.ToInt32(character);
var font = CreateDefaultFontWithOneCharacter(charIndex);
CharacterInfo result = new CharacterInfo();
Assert.IsTrue(font.GetCharacterInfo(character, out result), "Could not find character info for '" + character + "' even though the Font contains it.");
Assert.AreEqual(charIndex, result.index, "Incorrect character info was returned for " + character);
}
[Test]
public static void GetCharacterInfo_DoesNotFindCharacterInfoThatIsNotInSet()
{
char character = 'A';
char characterNotInSet = 'X';
int charIndex = Convert.ToInt32(character);
var font = CreateDefaultFontWithOneCharacter(charIndex);
CharacterInfo result;
Assert.IsFalse(font.GetCharacterInfo(characterNotInSet, out result), "Found character info for '" + characterNotInSet + "' even though the Font does not contain it.");
}
[Test]
public static void HasCharacterReturns8BitChars()
{
char character = 'A';
int charIndex = Convert.ToInt32(character);
var font = CreateDefaultFontWithOneCharacter(charIndex);
Assert.IsTrue(font.HasCharacter(character), "HasCharacter returned false even though it should have " + character);
}
[Test]
public static void HasCharacterReturns16BitChars()
{
char character = '\u03A9';
int charIndex = Convert.ToInt32(character);
var font = CreateDefaultFontWithOneCharacter(charIndex);
Assert.IsTrue(font.HasCharacter(character), "HasCharacter returned false even though it should have " + character);
}
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 812aaaefaab404448a3e4db49dfa5206
timeCreated: 1485515717
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e7689eda3a8b1a847a8b197dbe90d9a6
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,267 @@
using System.Collections;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEngine.UIElements;
using Toggle = UnityEngine.UIElements.Toggle;
namespace UnityEditor.UI.Tests
{
internal class LayoutElementEditorTests
{
static readonly string[] k_FloatFieldLabels =
{
"Min Width", "Min Height",
"Max Width", "Max Height",
"Preferred Width", "Preferred Height",
"Flexible Width", "Flexible Height"
};
GameObject m_GameObject;
LayoutElement m_LayoutElement;
Editor m_Editor;
EditorWindow m_Window;
VisualElement m_Root;
[SetUp]
public void SetUp()
{
VisualTreeBindingsUpdater.disableBindingsThrottling = true;
m_GameObject = new GameObject("LayoutElement", typeof(RectTransform));
m_LayoutElement = m_GameObject.AddComponent<LayoutElement>();
m_Editor = Editor.CreateEditor(m_LayoutElement);
m_Root = m_Editor.CreateInspectorGUI();
m_Window = EditorWindow.CreateWindow<EditorWindow>();
m_Window.rootVisualElement.Add(m_Root);
m_Window.Show();
}
[TearDown]
public void TearDown()
{
VisualTreeBindingsUpdater.disableBindingsThrottling = false;
if (m_Window != null)
m_Window.Close();
if (m_Editor != null)
Object.DestroyImmediate(m_Editor);
if (m_GameObject != null)
Object.DestroyImmediate(m_GameObject);
}
(Toggle toggle, FloatField field, Label labelElement) RowFor(string label)
{
var labelElement = m_Root.Query<Label>().Where(l => l.text == label).First();
var row = labelElement.parent;
return (row.Q<Toggle>(), row.Q<FloatField>(), labelElement);
}
float PersistedValue(string label)
{
switch (label)
{
case "Min Width": return m_LayoutElement.minWidth;
case "Min Height": return m_LayoutElement.minHeight;
case "Max Width": return m_LayoutElement.maxWidth;
case "Max Height": return m_LayoutElement.maxHeight;
case "Preferred Width": return m_LayoutElement.preferredWidth;
case "Preferred Height": return m_LayoutElement.preferredHeight;
case "Flexible Width": return m_LayoutElement.flexibleWidth;
case "Flexible Height": return m_LayoutElement.flexibleHeight;
default: throw new System.ArgumentException($"Unknown label '{label}'", nameof(label));
}
}
[UnityTest]
public IEnumerator NegativeValue_IsClampedToZero([ValueSource(nameof(k_FloatFieldLabels))] string label)
{
var (toggle, field, _) = RowFor(label);
toggle.value = true;
yield return null;
field.Focus();
yield return null;
field.value = -1f;
yield return null;
Assert.That(PersistedValue(label), Is.EqualTo(0f),
$"Negative '{label}' should be clamped to 0 in the LayoutElement.");
Assert.That(field.value, Is.EqualTo(0f),
$"The '{label}' field should display the clamped value rather than the rejected one.");
}
// Disabling a field stores a sentinel (-1, or +Infinity for Max fields); it should stay
// disabled rather than be clamped into the enabled range.
[UnityTest]
public IEnumerator DisablingField_DoesNotClampToEnabledValue([ValueSource(nameof(k_FloatFieldLabels))] string label)
{
var (toggle, field, _) = RowFor(label);
toggle.value = true;
field.value = 5f;
yield return null;
Assume.That(PersistedValue(label), Is.EqualTo(5f));
toggle.value = false;
yield return null;
yield return null;
float value = PersistedValue(label);
bool isEnabledValue = value >= 0f && value < LayoutUtility.DefaultMaxSize;
Assert.That(isEnabledValue, Is.False,
$"Disabling '{label}' should leave it disabled, but it was clamped to an enabled value ({value}).");
}
[UnityTest]
public IEnumerator BindingDrivenDisable_SyncsToggleAndVisibility([ValueSource(nameof(k_FloatFieldLabels))] string label)
{
var (toggle, field, _) = RowFor(label);
toggle.value = true;
yield return null;
Assume.That(toggle.value, Is.True);
// Setting the value without focusing the field simulates a binding push (Undo/Reset/external).
field.value = -1f;
yield return null;
Assert.That(toggle.value, Is.False,
$"A binding-driven disable of '{label}' should uncheck the toggle.");
Assert.That(field.style.display.value, Is.EqualTo(DisplayStyle.None),
$"A binding-driven disable of '{label}' should hide the field.");
}
[UnityTest]
public IEnumerator UndoAfterClampingNegative_DoesNotExposeRejectedValue([ValueSource(nameof(k_FloatFieldLabels))] string label)
{
var (toggle, field, _) = RowFor(label);
toggle.value = true;
yield return null;
field.Focus();
yield return null;
field.value = 5f;
yield return null;
field.Blur();
yield return null;
Assume.That(PersistedValue(label), Is.EqualTo(5f));
field.Focus();
yield return null;
field.value = -1f;
yield return null;
field.Blur();
yield return null;
Assume.That(PersistedValue(label), Is.EqualTo(0f));
Undo.PerformUndo();
yield return null;
yield return null;
Assert.That(PersistedValue(label), Is.GreaterThanOrEqualTo(0f),
$"Undo after clamping a negative '{label}' must not expose the rejected negative value.");
}
[UnityTest]
public IEnumerator NegativeValueWhileDragging_IsClampedToZero([ValueSource(nameof(k_FloatFieldLabels))] string label)
{
var (toggle, field, labelElement) = RowFor(label);
toggle.value = true;
yield return null;
// The dragger captures the pointer on the label for the duration of a drag.
labelElement.CaptureMouse();
yield return null;
field.value = -1f;
yield return null;
labelElement.ReleaseMouse();
yield return null;
Assert.That(PersistedValue(label), Is.EqualTo(0f),
$"A negative '{label}' produced while dragging should be clamped to 0.");
Assert.That(field.value, Is.EqualTo(0f));
}
// When multiple objects with differing field values are selected, the row's enable toggle and field
// show the mixed-value indicator rather than a single object's value.
[UnityTest]
public IEnumerator MultiObject_DivergentField_ShowsMixedValue()
{
var goA = new GameObject("LayoutElementA", typeof(RectTransform));
var goB = new GameObject("LayoutElementB", typeof(RectTransform));
var layoutA = goA.AddComponent<LayoutElement>();
var layoutB = goB.AddComponent<LayoutElement>();
layoutA.minWidth = 100f; // enabled
layoutB.minWidth = -1f; // disabled sentinel -> the two selections diverge
var editor = Editor.CreateEditor(new Object[] { layoutA, layoutB });
var root = editor.CreateInspectorGUI();
m_Window.rootVisualElement.Add(root);
yield return null;
yield return null;
var labelElement = root.Query<Label>().Where(l => l.text == "Min Width").First();
var row = labelElement.parent;
var toggle = row.Q<Toggle>();
var field = row.Q<FloatField>();
Assert.That(toggle.showMixedValue, Is.True,
"Multi-selecting LayoutElements with a divergent 'Min Width' should show the mixed-value indicator on the toggle.");
Assert.That(field.showMixedValue, Is.True,
"A divergent 'Min Width' should also display the mixed-value indicator on the field.");
root.RemoveFromHierarchy();
Object.DestroyImmediate(editor);
Object.DestroyImmediate(goA);
Object.DestroyImmediate(goB);
}
// When selected objects share the enabled/disabled state but hold different numbers (both enabled,
// 100 vs 200), the enable toggle controls something they agree on, so it must NOT be mixed - only the
// field, which shows the raw number, is mixed.
[UnityTest]
public IEnumerator MultiObject_SameEnabledStateDifferentValues_MixedOnFieldOnly()
{
var goA = new GameObject("LayoutElementA", typeof(RectTransform));
var goB = new GameObject("LayoutElementB", typeof(RectTransform));
var layoutA = goA.AddComponent<LayoutElement>();
var layoutB = goB.AddComponent<LayoutElement>();
layoutA.minWidth = 100f; // enabled
layoutB.minWidth = 200f; // enabled, different value -> only the number diverges
var editor = Editor.CreateEditor(new Object[] { layoutA, layoutB });
var root = editor.CreateInspectorGUI();
m_Window.rootVisualElement.Add(root);
yield return null;
yield return null;
var labelElement = root.Query<Label>().Where(l => l.text == "Min Width").First();
var row = labelElement.parent;
var toggle = row.Q<Toggle>();
var field = row.Q<FloatField>();
Assert.That(toggle.showMixedValue, Is.False,
"Objects that are all enabled should not show the toggle as mixed, even if their values differ.");
Assert.That(toggle.value, Is.True,
"The toggle should read enabled when every selected object is enabled.");
Assert.That(field.showMixedValue, Is.True,
"Differing 'Min Width' values should still show the mixed-value indicator on the field.");
root.RemoveFromHierarchy();
Object.DestroyImmediate(editor);
Object.DestroyImmediate(goA);
Object.DestroyImmediate(goB);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4130b277c1a94612a9dc40631c012775
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,187 @@
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using Toggle = UnityEngine.UIElements.Toggle;
namespace UnityEditor.UI.Tests
{
// These assert the state the row is built with, which the inspector applies synchronously - hence no frames and
// no EditorWindow. LayoutElementEditorTests covers the binding-driven re-sync path.
internal class LayoutElementInspectorMixedValueTests
{
const string k_MinWidth = "Min Width";
const string k_MaxWidth = "Max Width";
readonly List<GameObject> m_GameObjects = new List<GameObject>();
Editor m_Editor;
VisualElement m_Root;
[TearDown]
public void TearDown()
{
if (m_Editor != null)
Object.DestroyImmediate(m_Editor);
m_Editor = null;
m_Root = null;
foreach (var gameObject in m_GameObjects)
{
if (gameObject != null)
Object.DestroyImmediate(gameObject);
}
m_GameObjects.Clear();
}
LayoutElement CreateLayoutElement()
{
var gameObject = new GameObject("LayoutElement", typeof(RectTransform));
m_GameObjects.Add(gameObject);
return gameObject.AddComponent<LayoutElement>();
}
void CreateInspectorFor(params LayoutElement[] elements)
{
var targets = new Object[elements.Length];
for (int i = 0; i < elements.Length; i++)
targets[i] = elements[i];
m_Editor = Editor.CreateEditor(targets);
Assume.That(m_Editor, Is.Not.Null, "Failed to create an editor for the LayoutElement selection.");
m_Root = m_Editor.CreateInspectorGUI();
Assume.That(m_Root, Is.Not.Null, "The LayoutElement inspector should be built with UI Toolkit.");
}
(Toggle toggle, FloatField field) RowFor(string label)
{
var labelElement = m_Root.Query<Label>().Where(l => l.text == label).First();
Assume.That(labelElement, Is.Not.Null, $"No '{label}' row found in the LayoutElement inspector.");
var row = labelElement.parent;
return (row.Q<Toggle>(), row.Q<FloatField>());
}
[Test]
public void SingleObject_EnabledField_ShowsFieldWithoutMixedIndicator()
{
var element = CreateLayoutElement();
element.minWidth = 100f;
CreateInspectorFor(element);
var (toggle, field) = RowFor(k_MinWidth);
Assert.That(toggle.value, Is.True, "A LayoutElement with a usable 'Min Width' should show the row as enabled.");
Assert.That(toggle.showMixedValue, Is.False, "A single selected object can never be mixed.");
Assert.That(field.showMixedValue, Is.False, "A single selected object can never be mixed.");
Assert.That(field.style.display.value, Is.EqualTo(DisplayStyle.Flex), "An enabled 'Min Width' should show its float field.");
}
[Test]
public void SingleObject_DisabledField_HidesFieldWithoutMixedIndicator()
{
var element = CreateLayoutElement();
element.minWidth = -1f;
CreateInspectorFor(element);
var (toggle, field) = RowFor(k_MinWidth);
Assert.That(toggle.value, Is.False, "The disabled sentinel should show the row as disabled.");
Assert.That(toggle.showMixedValue, Is.False, "A single selected object can never be mixed.");
Assert.That(field.showMixedValue, Is.False, "A single selected object can never be mixed.");
Assert.That(field.style.display.value, Is.EqualTo(DisplayStyle.None), "A disabled 'Min Width' should hide its float field.");
}
[Test]
public void MultiObject_DivergentEnabledState_ShowsMixedToggleAndKeepsFieldVisible()
{
var disabled = CreateLayoutElement();
var enabled = CreateLayoutElement();
disabled.minWidth = -1f;
enabled.minWidth = 100f;
CreateInspectorFor(disabled, enabled);
var (toggle, field) = RowFor(k_MinWidth);
Assert.That(toggle.showMixedValue, Is.True,
"Selecting an enabled and a disabled 'Min Width' should mark the toggle as mixed.");
Assert.That(field.showMixedValue, Is.True,
"Divergent 'Min Width' values should mark the field as mixed.");
Assert.That(field.style.display.value, Is.EqualTo(DisplayStyle.Flex),
"The field must stay visible when the enabled state is mixed, otherwise the mixed indicator is hidden from the user.");
}
[Test]
public void MultiObject_AllDisabled_HidesFieldWithoutMixedIndicator()
{
var first = CreateLayoutElement();
var second = CreateLayoutElement();
first.minWidth = -1f;
second.minWidth = -1f;
CreateInspectorFor(first, second);
var (toggle, field) = RowFor(k_MinWidth);
Assert.That(toggle.value, Is.False, "Objects that are all disabled should read as disabled.");
Assert.That(toggle.showMixedValue, Is.False, "Objects that agree on being disabled are not mixed.");
Assert.That(field.showMixedValue, Is.False, "Objects holding the same value are not mixed.");
Assert.That(field.style.display.value, Is.EqualTo(DisplayStyle.None),
"A field that is disabled across the whole selection should stay hidden.");
}
[Test]
public void MultiObject_DivergentEnabledStateOnMaxField_ShowsMixedToggle()
{
var disabled = CreateLayoutElement();
var enabled = CreateLayoutElement();
disabled.maxWidth = LayoutUtility.DefaultMaxSize;
enabled.maxWidth = 250f;
CreateInspectorFor(disabled, enabled);
var (toggle, field) = RowFor(k_MaxWidth);
Assert.That(toggle.showMixedValue, Is.True,
"An unbounded and a bounded 'Max Width' disagree about the enabled state and should mark the toggle as mixed.");
Assert.That(field.style.display.value, Is.EqualTo(DisplayStyle.Flex),
"The field must stay visible when the enabled state is mixed.");
}
[Test]
public void MultiObject_DivergenceInThirdObject_ShowsMixedToggle()
{
var first = CreateLayoutElement();
var second = CreateLayoutElement();
var third = CreateLayoutElement();
first.minWidth = 100f;
second.minWidth = 200f;
third.minWidth = -1f;
CreateInspectorFor(first, second, third);
var (toggle, field) = RowFor(k_MinWidth);
Assert.That(toggle.showMixedValue, Is.True,
"A divergent enabled state anywhere in the selection should mark the toggle as mixed.");
Assert.That(field.showMixedValue, Is.True,
"Divergent 'Min Width' values should mark the field as mixed.");
}
[Test]
public void MultiObject_SameEnabledStateDifferentValues_MixesFieldOnly()
{
var first = CreateLayoutElement();
var second = CreateLayoutElement();
first.minWidth = 100f;
second.minWidth = 200f;
CreateInspectorFor(first, second);
var (toggle, field) = RowFor(k_MinWidth);
Assert.That(toggle.showMixedValue, Is.False,
"Objects that are all enabled agree about the toggle, even when their values differ.");
Assert.That(toggle.value, Is.True, "The toggle should read enabled when every selected object is enabled.");
Assert.That(field.showMixedValue, Is.True, "Differing 'Min Width' values should mark the field as mixed.");
Assert.That(field.style.display.value, Is.EqualTo(DisplayStyle.Flex), "An enabled field stays visible.");
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8c25ee90b3284383bfbd87d30f331df5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,215 @@
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools.Utils;
using UnityEngine.UI;
namespace UnityEditor.UI.Tests
{
// Covers the reach of the Undo registration in LayoutGroup.Reset: the whole subtree, including the group's own
// RectTransform. ScrollRectLayoutUndoTests covers the per-layout-group-type cases.
internal class LayoutGroupAddUndoTests
{
GameObject m_Canvas;
GameObject m_Root;
static readonly Vector2EqualityComparer k_Vector2Comparer = new Vector2EqualityComparer(0.01f);
[SetUp]
public void SetUp()
{
m_Canvas = new GameObject("Canvas", typeof(Canvas));
Undo.ClearAll();
}
[TearDown]
public void TearDown()
{
Undo.ClearAll();
if (m_Root != null)
Object.DestroyImmediate(m_Root);
if (m_Canvas != null)
Object.DestroyImmediate(m_Canvas);
}
struct RectState
{
public Vector2 anchorMin, anchorMax, anchoredPosition, sizeDelta;
}
static Dictionary<RectTransform, RectState> Snapshot(Transform root, bool includeRoot)
{
var map = new Dictionary<RectTransform, RectState>();
foreach (var rect in root.GetComponentsInChildren<RectTransform>(true))
{
if (!includeRoot && rect.transform == root)
continue;
map[rect] = new RectState
{
anchorMin = rect.anchorMin,
anchorMax = rect.anchorMax,
anchoredPosition = rect.anchoredPosition,
sizeDelta = rect.sizeDelta
};
}
return map;
}
static bool Matches(RectTransform rect, RectState state)
{
return k_Vector2Comparer.Equals(rect.anchorMin, state.anchorMin)
&& k_Vector2Comparer.Equals(rect.anchorMax, state.anchorMax)
&& k_Vector2Comparer.Equals(rect.anchoredPosition, state.anchoredPosition)
&& k_Vector2Comparer.Equals(rect.sizeDelta, state.sizeDelta);
}
static void AssertRestored(Dictionary<RectTransform, RectState> before, Dictionary<RectTransform, RectState> afterAdd)
{
foreach (var kvp in before)
{
var rect = kvp.Key;
Assert.That(rect != null, "A RectTransform was unexpectedly destroyed by the undo.");
var state = kvp.Value;
string name = rect.name;
string context = afterAdd.TryGetValue(rect, out var added)
? $" (post-add was anchoredPosition {added.anchoredPosition}, sizeDelta {added.sizeDelta})"
: string.Empty;
Assert.That(rect.anchorMin, Is.EqualTo(state.anchorMin).Using(k_Vector2Comparer), $"{name}.anchorMin not restored{context}");
Assert.That(rect.anchorMax, Is.EqualTo(state.anchorMax).Using(k_Vector2Comparer), $"{name}.anchorMax not restored{context}");
Assert.That(rect.anchoredPosition, Is.EqualTo(state.anchoredPosition).Using(k_Vector2Comparer), $"{name}.anchoredPosition not restored{context}");
Assert.That(rect.sizeDelta, Is.EqualTo(state.sizeDelta).Using(k_Vector2Comparer), $"{name}.sizeDelta not restored{context}");
}
}
static void AssertAnyChanged(Dictionary<RectTransform, RectState> before, string what)
{
foreach (var kvp in before)
{
if (!Matches(kvp.Key, kvp.Value))
return;
}
Assert.Fail($"Adding {what} left every tracked RectTransform unchanged, so this test would pass without exercising the undo registration.");
}
static void Rebuild(RectTransform rect)
{
Canvas.ForceUpdateCanvases();
LayoutRebuilder.ForceRebuildLayoutImmediate(rect);
}
static RectTransform AddChild(Transform parent, string name, Vector2 anchoredPosition, Vector2 size)
{
var child = new GameObject(name, typeof(RectTransform), typeof(LayoutElement));
child.transform.SetParent(parent, false);
var rect = (RectTransform)child.transform;
rect.anchorMin = rect.anchorMax = new Vector2(0.5f, 0.5f);
rect.anchoredPosition = anchoredPosition;
rect.sizeDelta = size;
var element = child.GetComponent<LayoutElement>();
element.preferredWidth = size.x;
element.preferredHeight = size.y;
return rect;
}
RectTransform CreateRoot(string name, Transform parent)
{
var gameObject = new GameObject(name, typeof(RectTransform));
var rect = (RectTransform)gameObject.transform;
rect.SetParent(parent, false);
rect.anchorMin = rect.anchorMax = new Vector2(0.5f, 0.5f);
rect.anchoredPosition = new Vector2(120f, 80f);
rect.sizeDelta = new Vector2(400f, 300f);
if (m_Root == null)
m_Root = gameObject;
return rect;
}
static Dictionary<RectTransform, RectState> AddLayoutGroupThenUndo<T>(GameObject target, RectTransform rebuildRoot,
Dictionary<RectTransform, RectState> before, Transform snapshotRoot, bool includeRoot) where T : Component
{
Undo.IncrementCurrentGroup();
int undoGroup = Undo.GetCurrentGroup();
// This is the path that makes the Editor invoke LayoutGroup.Reset.
ObjectFactory.AddComponent<T>(target);
Rebuild(rebuildRoot);
AssertAnyChanged(before, typeof(T).Name);
var afterAdd = Snapshot(snapshotRoot, includeRoot);
Undo.CollapseUndoOperations(undoGroup);
Undo.PerformUndo();
Rebuild(rebuildRoot);
return afterAdd;
}
[Test]
public void UndoAddLayoutGroup_RestoresNestedDescendantRectTransforms()
{
var outerRect = CreateRoot("Outer", m_Canvas.transform);
AddChild(outerRect, "Child0", new Vector2(-60f, 40f), new Vector2(80f, 40f));
AddChild(outerRect, "Child1", new Vector2(70f, -30f), new Vector2(90f, 50f));
var nestedRect = CreateRoot("Nested", outerRect);
nestedRect.anchoredPosition = new Vector2(-20f, -90f);
nestedRect.sizeDelta = new Vector2(180f, 70f);
nestedRect.gameObject.AddComponent<LayoutElement>();
var nestedGroup = nestedRect.gameObject.AddComponent<HorizontalLayoutGroup>();
nestedGroup.padding = new RectOffset(4, 4, 4, 4);
AddChild(nestedRect, "GrandChild0", new Vector2(-40f, 0f), new Vector2(50f, 30f));
AddChild(nestedRect, "GrandChild1", new Vector2(45f, 0f), new Vector2(60f, 30f));
Rebuild(outerRect);
var before = Snapshot(outerRect, includeRoot: false);
Assume.That(before.Count, Is.GreaterThanOrEqualTo(5),
"Expected the nested hierarchy to contribute grandchildren to the snapshot.");
var afterAdd = AddLayoutGroupThenUndo<VerticalLayoutGroup>(outerRect.gameObject, outerRect, before, outerRect, includeRoot: false);
Assert.That(outerRect.GetComponent<VerticalLayoutGroup>(), Is.Null,
"A single undo should remove the added VerticalLayoutGroup.");
AssertRestored(before, afterAdd);
}
[Test]
public void UndoAddNestedLayoutGroup_RestoresItsOwnRectTransform()
{
var outerRect = CreateRoot("Outer", m_Canvas.transform);
var outerGroup = outerRect.gameObject.AddComponent<VerticalLayoutGroup>();
outerGroup.childControlWidth = true;
outerGroup.childControlHeight = true;
outerGroup.childForceExpandWidth = false;
outerGroup.childForceExpandHeight = false;
var innerRect = CreateRoot("Inner", outerRect);
innerRect.gameObject.AddComponent<LayoutElement>();
AddChild(innerRect, "GrandChild0", new Vector2(-30f, 0f), new Vector2(50f, 30f));
AddChild(innerRect, "GrandChild1", new Vector2(35f, 0f), new Vector2(60f, 30f));
Rebuild(outerRect);
var before = Snapshot(innerRect, includeRoot: true);
Assume.That(before.ContainsKey(innerRect), "The snapshot should include the inner group's own RectTransform.");
var afterAdd = AddLayoutGroupThenUndo<HorizontalLayoutGroup>(innerRect.gameObject, outerRect, before, innerRect, includeRoot: true);
Assert.That(innerRect.GetComponent<HorizontalLayoutGroup>(), Is.Null,
"A single undo should remove the added HorizontalLayoutGroup.");
AssertRestored(before, afterAdd);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3d96cc7adb6c4531998652ab1f09a983
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 24333a116497b144f9782b1160984b57
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,120 @@
using System;
using NUnit.Framework;
using System.Collections;
using System.Linq;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.TestTools;
using UnityEngine.UI;
using UnityEngine.UIElements;
using UnityEngine.Search;
[Timeout(360000)]
internal class PropertyDrawerTests
{
class PropertyDrawerTestsWindow : EditorWindow
{
public Navigation navigation;
public SpriteState spriteState;
public Dropdown.OptionDataList optionDataList;
[SearchContext("t:gameObject is:gameObject", "gameObject")]
public GameObject searchContext;
SerializedObject serializedObject;
void CreateGUI()
{
serializedObject = new SerializedObject(this);
Add(nameof(navigation));
Add(nameof(spriteState));
Add(nameof(optionDataList));
Add(nameof(searchContext));
rootVisualElement.Bind(serializedObject);
// Forces visual tree update
Rebuild();
}
void Add(string propertyName)
{
rootVisualElement.Add(new PropertyField() { bindingPath = propertyName });
}
public SerializedProperty Property(string propertyName) => serializedObject.FindProperty(propertyName);
public void Rebuild() => rootVisualElement.Bind(serializedObject);
}
static PropertyDrawerTestsWindow window;
[UnitySetUp]
[MenuItem("Tests/Open Property Drawer Test Window")]
public static IEnumerator SetUp()
{
VisualTreeBindingsUpdater.disableBindingsThrottling = true;
window = EditorWindow.GetWindow<PropertyDrawerTestsWindow>();
window.Repaint();
window.Show();
yield return null;
}
[TearDown]
public void TearDown()
{
VisualTreeBindingsUpdater.disableBindingsThrottling = false;
window.Close();
}
[UnityTest]
public IEnumerator NavigationDrawer_IsVisible()
{
yield return null;
Assert.IsNotNull(window.rootVisualElement.Query<VisualElement>("Navigation").Build().First());
}
[UnityTest]
public IEnumerator SpriteStateDrawer_IsVisible()
{
yield return null;
Assert.IsNotNull(window.rootVisualElement.Q("SpriteState"));
}
[UnityTest]
[Ignore("UUM-18482")]
public IEnumerator DropdownOptionDataListDrawer_IsVisible()
{
yield return null;
Assert.IsNotNull(window.rootVisualElement.Q("DropdownOptionDataList"), $"Item is null. Root object count: {window.rootVisualElement.childCount}");
}
[UnityTest]
public IEnumerator SearchContextDrawer_IsVisible()
{
yield return null;
Assert.IsNotNull(window.rootVisualElement.Q("SearchContext"));
}
// Fake expected result in order to make TestCaseAttribute to work with UnityTest
[UnityTest]
[TestCase(new object[] { Navigation.Mode.None, 0}, ExpectedResult = null)]
[TestCase(new object[] { Navigation.Mode.Horizontal, 1 }, ExpectedResult = null)]
[TestCase(new object[] { Navigation.Mode.Vertical, 1 }, ExpectedResult = null)]
[TestCase(new object[] { Navigation.Mode.Automatic, 0 }, ExpectedResult = null)]
[TestCase(new object[] { Navigation.Mode.Explicit, 4 }, ExpectedResult = null)]
[TestCase(new object[] { (Navigation.Mode.Explicit | Navigation.Mode.Horizontal), 0 }, ExpectedResult = null)]
[TestCase(new object[] { (Navigation.Mode.Automatic | Navigation.Mode.Explicit), 0 }, ExpectedResult = null)]
public static IEnumerator NavigationDrawer_ShowsCorrectAdditionalControlCount(Enum mode, int expectedCount)
{
var field = window.rootVisualElement.Q<EnumFlagsField>("unity-input-navigation.m_Mode");
field.value = mode;
yield return null;
var indent = window.rootVisualElement.Q<VisualElement>("Navigation").Q<VisualElement>("Indent");
var visibleChildren = indent.Children().Count(child => child.resolvedStyle.display != DisplayStyle.None);
Assert.AreEqual(expectedCount, visibleChildren, $"{expectedCount} additional Navigation object properties should be " +
$"visible when 'Mode' is set to '{(Navigation.Mode)window.Property("navigation.m_Mode").enumValueFlag}'");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 433d3b96b2a40a5479d3d7d8495882ed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,155 @@
using System.Collections.Generic;
using NUnit.Framework;
using UnityEngine;
using UnityEngine.TestTools.Utils;
using UnityEngine.UI;
namespace UnityEditor.UI.Tests
{
// Adding a layout group to a Scroll View repositions its children (and descendants such as the scrollbar
// handles); undoing the "Add Component" must restore every descendant RectTransform to its pre-add state.
// (UUM-144838)
internal class ScrollRectLayoutUndoTests
{
GameObject m_Canvas;
GameObject m_ScrollView;
static readonly Vector2EqualityComparer k_Vector2Comparer = new Vector2EqualityComparer(0.01f);
[SetUp]
public void SetUp()
{
m_Canvas = new GameObject("Canvas", typeof(Canvas));
m_ScrollView = DefaultControls.CreateScrollView(new DefaultControls.Resources());
var scrollRT = (RectTransform)m_ScrollView.transform;
scrollRT.SetParent(m_Canvas.transform, false);
// Off-origin, where any leftover offset is most visible.
scrollRT.anchorMin = scrollRT.anchorMax = new Vector2(0.5f, 0.5f);
scrollRT.anchoredPosition = new Vector2(300, 200);
Canvas.ForceUpdateCanvases();
LayoutRebuilder.ForceRebuildLayoutImmediate(scrollRT);
}
[TearDown]
public void TearDown()
{
if (m_ScrollView != null)
Object.DestroyImmediate(m_ScrollView);
if (m_Canvas != null)
Object.DestroyImmediate(m_Canvas);
}
struct RectState
{
public Vector2 anchorMin, anchorMax, anchoredPosition, sizeDelta;
}
static Dictionary<RectTransform, RectState> SnapshotDescendants(Transform root)
{
var map = new Dictionary<RectTransform, RectState>();
foreach (var rt in root.GetComponentsInChildren<RectTransform>(true))
{
if (rt == root) // only descendants are recorded
continue;
map[rt] = new RectState
{
anchorMin = rt.anchorMin,
anchorMax = rt.anchorMax,
anchoredPosition = rt.anchoredPosition,
sizeDelta = rt.sizeDelta
};
}
return map;
}
static void AssertRestored(Dictionary<RectTransform, RectState> before)
{
foreach (var kvp in before)
{
var rt = kvp.Key;
Assert.That(rt != null, $"'{kvp.Key}' was unexpectedly destroyed by undo.");
var state = kvp.Value;
string name = rt.name;
Assert.That(rt.anchorMin, Is.EqualTo(state.anchorMin).Using(k_Vector2Comparer), $"{name}.anchorMin not restored");
Assert.That(rt.anchorMax, Is.EqualTo(state.anchorMax).Using(k_Vector2Comparer), $"{name}.anchorMax not restored");
Assert.That(rt.anchoredPosition, Is.EqualTo(state.anchoredPosition).Using(k_Vector2Comparer), $"{name}.anchoredPosition not restored");
Assert.That(rt.sizeDelta, Is.EqualTo(state.sizeDelta).Using(k_Vector2Comparer), $"{name}.sizeDelta not restored");
}
}
static void AssertAnyChanged(Dictionary<RectTransform, RectState> before, string layoutGroupName)
{
foreach (var kvp in before)
{
var rt = kvp.Key;
var state = kvp.Value;
if (!k_Vector2Comparer.Equals(rt.anchorMin, state.anchorMin)
|| !k_Vector2Comparer.Equals(rt.anchorMax, state.anchorMax)
|| !k_Vector2Comparer.Equals(rt.anchoredPosition, state.anchoredPosition)
|| !k_Vector2Comparer.Equals(rt.sizeDelta, state.sizeDelta))
return;
}
Assert.Fail($"Adding {layoutGroupName} left every descendant RectTransform unchanged, so this test would pass without exercising the undo.");
}
static void AddLayoutGroupThenUndo<T>(GameObject target, RectTransform scrollRT, Dictionary<RectTransform, RectState> before) where T : Component
{
Undo.IncrementCurrentGroup();
int group = Undo.GetCurrentGroup();
// ObjectFactory.AddComponent matches the Inspector's "Add Component" button.
ObjectFactory.AddComponent<T>(target);
Canvas.ForceUpdateCanvases();
LayoutRebuilder.ForceRebuildLayoutImmediate(scrollRT);
AssertAnyChanged(before, typeof(T).Name);
Undo.CollapseUndoOperations(group);
Undo.PerformUndo();
Canvas.ForceUpdateCanvases();
LayoutRebuilder.ForceRebuildLayoutImmediate(scrollRT);
}
[Test]
public void UndoAddVerticalLayoutGroup_RestoresScrollViewDescendants()
{
var scrollRT = (RectTransform)m_ScrollView.transform;
var before = SnapshotDescendants(scrollRT);
AddLayoutGroupThenUndo<VerticalLayoutGroup>(m_ScrollView, scrollRT, before);
Assert.That(m_ScrollView.GetComponent<VerticalLayoutGroup>(), Is.Null,
"A single Undo should remove the added VerticalLayoutGroup.");
AssertRestored(before);
}
[Test]
public void UndoAddHorizontalLayoutGroup_RestoresScrollViewDescendants()
{
var scrollRT = (RectTransform)m_ScrollView.transform;
var before = SnapshotDescendants(scrollRT);
AddLayoutGroupThenUndo<HorizontalLayoutGroup>(m_ScrollView, scrollRT, before);
Assert.That(m_ScrollView.GetComponent<HorizontalLayoutGroup>(), Is.Null);
AssertRestored(before);
}
[Test]
public void UndoAddGridLayoutGroup_RestoresScrollViewDescendants()
{
var scrollRT = (RectTransform)m_ScrollView.transform;
var before = SnapshotDescendants(scrollRT);
AddLayoutGroupThenUndo<GridLayoutGroup>(m_ScrollView, scrollRT, before);
Assert.That(m_ScrollView.GetComponent<GridLayoutGroup>(), Is.Null);
AssertRestored(before);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e76469fb3bb994083898a5bc426ca60d
@@ -0,0 +1,14 @@
{
"name": "UnityEditor.UI.EditorTests",
"references": [
"UnityEditor.UI",
"UnityEngine.UI"
],
"optionalUnityReferences": [
"TestAssemblies"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": []
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7c04f0dfa9243c04681a55d90d3ff3fc
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e90cc37a5ccf4a44dbecc5b7172ec512
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,83 @@
using NUnit.Framework;
using UnityEditor.Events;
using UnityEngine;
using UnityEngine.Events;
internal class UnityEventInvoke
{
class SimpleCounter : MonoBehaviour
{
public int m_Count = 0;
public void Add()
{
++m_Count;
}
public void NoOp(int i)
{
}
}
GameObject m_CounterObject;
SimpleCounter Counter { get; set; }
[SetUp]
public void TestSetup()
{
m_CounterObject = new GameObject("Counter");
Counter = m_CounterObject.AddComponent<SimpleCounter>();
}
[TearDown]
public void TearDown()
{
GameObject.DestroyImmediate(m_CounterObject);
}
[Test]
[Description("Using a CachedInvokableCall in a UnityEvent should not go re-trigger all the calls stored in the UnityEvent. Case-950588")]
public void UnityEvent_InvokeCallsListenerOnce()
{
var _event = new UnityEvent();
UnityEventTools.AddPersistentListener(_event, new UnityAction(Counter.Add));
_event.SetPersistentListenerState(0, UnityEventCallState.EditorAndRuntime);
_event.Invoke();
Assert.AreEqual(1, Counter.m_Count);
for (int i = 1; i < 5; ++i)
{
UnityEventTools.AddIntPersistentListener(_event, new UnityAction<int>(Counter.NoOp), i);
_event.SetPersistentListenerState(i, UnityEventCallState.EditorAndRuntime);
}
_event.Invoke();
Assert.AreEqual(2, Counter.m_Count);
}
[Test]
[Description("Using a CachedInvokableCall in a UnityEvent should not go re-trigger all the calls stored in the UnityEvent. Case-950588")]
public void UnityEvent_EditMode_InvokeDoesNotCallRuntimeListener()
{
var _event = new UnityEvent();
UnityEventTools.AddPersistentListener(_event, new UnityAction(Counter.Add));
Assert.AreEqual(UnityEventCallState.RuntimeOnly, _event.GetPersistentListenerState(0));
Assert.False(Application.isPlaying);
_event.Invoke();
Assert.AreEqual(0, Counter.m_Count, "Expected Event to not be called when not in play mode and event is marked as Runtime only");
for (int i = 1; i < 5; ++i)
{
UnityEventTools.AddIntPersistentListener(_event, new UnityAction<int>(Counter.NoOp), i);
}
_event.Invoke();
Assert.AreEqual(0, Counter.m_Count, "Expected Event to not be called when not in play mode and event is marked as Runtime only");
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 977190a4db46de442aed27279d247df4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,65 @@
using System;
using System.Collections;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
internal class WrapperWindowFixture
{
private static WrapperWindow s_MostRecentWrapperWindow;
internal class WrapperWindow : EditorWindow
{
// Return true to end the test
public Func<WrapperWindow, bool> onGUIDelegate;
public bool TestCompleted { get; set; }
public void OnGUI()
{
if (onGUIDelegate != null)
{
TestCompleted = onGUIDelegate.Invoke(this);
if (TestCompleted)
onGUIDelegate = null;
}
}
}
public static WrapperWindow GetWindow(Func<WrapperWindow, bool> onGUIDelegate, bool utility = false)
{
return GetWindow(onGUIDelegate, 800, 600, utility);
}
public static WrapperWindow GetWindow(Func<WrapperWindow, bool> onGUIDelegate, int width, int height, bool utility = false)
{
WrapperWindow window;
if (utility)
window = EditorWindow.GetWindow<WrapperWindow>(true);
else
{
window = ScriptableObject.CreateInstance<WrapperWindow>();
window.hideFlags = HideFlags.DontSave;
}
window.onGUIDelegate = onGUIDelegate;
window.position = new Rect(0, 0, width, height);
window.Show();
s_MostRecentWrapperWindow = window;
return window;
}
[TearDown]
public void CloseMostRecentWrapperWindow()
{
if (s_MostRecentWrapperWindow == null)
return;
s_MostRecentWrapperWindow.Close();
s_MostRecentWrapperWindow = null;
}
protected static void RegisterWrapperWindow(WrapperWindow window)
{
s_MostRecentWrapperWindow = window;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fc31799bd6dc1f74a8adfee1acd05a9b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c545241cf2e56ec4997d7677f01ef43d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 914613548ded44a43a59eb9852503f18
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.TextMeshPro.Editor.Tests")]
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 06b06f5f5563e9a43b274eadc5373cc0
@@ -0,0 +1,52 @@
using UnityEngine.TestTools;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace TMPro
{
/// <summary>
/// Imports the TMP Essential Resources into the test project before the test run starts, so that
/// fixtures relying on TMP_Settings and the default font asset have them available.
/// </summary>
/// <remarks>
/// This runs in the Editor for Edit Mode and Play Mode runs alike, and ahead of a player build,
/// which is why it lives in the Play Mode assembly with an editor-only body.
///
/// To reduce boilerplate derive from <see cref="TMPTestSuiteWithEssentialResources"/> rather than referencing this
/// directly.
/// </remarks>
internal class TMPEssentialResourcesImporter : IPrebuildSetup
{
/// <summary>
/// GUID of the "TextMesh Pro" folder that importing the Essential Resources creates.
/// </summary>
const string k_EssentialResourcesFolderGUID = "f54d1bd14bd3ca042bd867b519fee8cc";
/// <summary>
/// GUID for Roboto-Bold.ttf, which ships in Examples and Extras rather than the Essential Resources.
/// </summary>
internal const string k_ExampleFontGUID = "4beb055f07aaff244873dec698d0363e";
public virtual void Setup()
{
Import(essentials: true, examples: false);
}
protected static void Import(bool essentials, bool examples)
{
#if UNITY_EDITOR
var importEssentials = essentials
&& string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath(k_EssentialResourcesFolderGUID));
var importExamples = examples
&& string.IsNullOrEmpty(AssetDatabase.GUIDToAssetPath(k_ExampleFontGUID));
if (!importEssentials && !importExamples)
return;
TMP_PackageResourceImporter.ImportResources(importEssentials, importExamples, false);
AssetDatabase.Refresh();
#endif
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2b3c35f9f9f3cb04b96b5cd06fc548bd
@@ -0,0 +1,25 @@
using NUnit.Framework;
using UnityEngine.TestTools;
namespace TMPro
{
/// <summary>
/// Base fixture for TMP tests that need the TMP Essential Resources.
/// </summary>
[PrebuildSetup(typeof(TMPEssentialResourcesImporter))]
internal abstract class TMPTestSuiteWithEssentialResources
{
/// <summary>
/// Checks that the resources arrived before any test in the fixture runs. Override to add
/// fixture-specific setup, ensuring to call base.OneTimeSetup().
/// </summary>
[OneTimeSetUp]
public virtual void OneTimeSetup()
{
Assert.IsNotNull(TMP_Settings.instance,
$"TMP_Settings could not be loaded, so {nameof(TMPEssentialResourcesImporter)} did not make the TMP Essential Resources available to this fixture.");
Assert.IsNotNull(TMP_Settings.defaultFontAsset,
$"TMP_Settings has no default font asset, so {nameof(TMPEssentialResourcesImporter)} did not make the TMP Essential Resources available to this fixture.");
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 897920160c2045844a3119a3a3d937fb
@@ -0,0 +1,47 @@
using UnityEngine;
using NUnit.Framework;
using System.IO;
namespace TMPro
{
internal class TMP_CanvasTests
{
[OneTimeSetUp]
public void OneTimeSetUp()
{
if (!Directory.Exists(Path.GetFullPath("Assets/TextMesh Pro")))
{
Debug.Log("Skipping over Editor tests as TMP Essential Resources are missing from the current test project.");
Assert.Ignore();
return;
}
}
[Test]
public void EnablingAndDisablingCanvasDoesNotRegenerateText() // (UUM-45320)
{
var go = new GameObject();
var canvas = go.AddComponent<Canvas>();
var goChild = new GameObject();
var text = goChild.AddComponent<TextMeshProUGUI>();
goChild.transform.SetParent(go.transform);
// Force text to be generated
text.text = "Hello World";
text.ForceMeshUpdate();
Assert.IsFalse(text.havePropertiesChanged, "Text should not have changed yet");
canvas.enabled = false;
canvas.enabled = true;
Assert.IsFalse(text.havePropertiesChanged, "Text should not have changed after enabling / disabling canvas");
// Cleanup
Object.DestroyImmediate(go);
}
}
}

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