text stringlengths 7 35.3M | id stringlengths 11 185 | metadata dict | __index_level_0__ int64 0 2.14k |
|---|---|---|---|
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Text.RegularExpressions;
namespace UnityEditor.Search
{
static partial class Parsers
{
static readonly Regex s_SelectorPattern = new Regex(@"^[@$][^><=!:\s]+");
static readonly SearchExpressionEvaluator s_SelectorEvaluator = EvaluatorManager.GetConstantEvaluatorByName("selector");
[SearchExpressionParser("selector", BuiltinParserPriority.String)]
internal static SearchExpression SelectorParser(StringView outerText)
{
var text = ParserUtils.SimplifyExpression(outerText);
if (!s_SelectorPattern.IsMatch(text.ToString()))
return null;
return new SearchExpression(SearchExpressionType.Selector, outerText, text.Substring(1), s_SelectorEvaluator);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/SelectorExpressionParser.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/SelectorExpressionParser.cs",
"repo_id": "UnityCsReference",
"token_count": 356
} | 447 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
//#define DEBUG_SEARCH_MONITOR
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEditor.SceneManagement;
using UnityEditorInternal;
using UnityEngine;
namespace UnityEditor.Search
{
public readonly struct AssetIndexChangeSet
{
static readonly string[] s_EmptyStrings = new string[0];
internal static readonly AssetIndexChangeSet s_Empty = new AssetIndexChangeSet(null, null);
public readonly string[] updated;
public readonly string[] removed;
public AssetIndexChangeSet(string[] updated, string[] removed)
{
this.removed = removed ?? s_EmptyStrings;
this.updated = updated ?? s_EmptyStrings;
}
public AssetIndexChangeSet(IEnumerable<string> updated, IEnumerable<string> removed, IEnumerable<string> moved, Func<string, bool> predicate)
: this(updated.Concat(moved).Distinct(), removed, predicate)
{
}
public AssetIndexChangeSet(IEnumerable<string> updated, IEnumerable<string> removed, Func<string, bool> predicate)
{
this.updated = updated.Except(removed).Where(predicate).ToArray();
this.removed = removed.Distinct().Where(predicate).ToArray();
}
public bool empty => updated == null || removed == null || (updated.Length == 0 && removed.Length == 0);
public IEnumerable<string> all => updated?.Concat(removed ?? new string[0]).Distinct() ?? Enumerable.Empty<string>();
}
class AssetChangedListener : AssetPostprocessor
{
internal static void OnPostprocessAllAssets(string[] imported, string[] deleted, string[] movedTo, string[] movedFrom)
{
if (!Utils.IsMainProcess())
return;
SearchMonitor.RaiseContentRefreshed(imported, deleted.Concat(movedFrom).Distinct().ToArray(), movedTo);
}
}
public struct SearchMonitorView : IDisposable
{
static ConcurrentDictionary<int, SearchMonitorView> s_PropertyDatabaseViews = new ConcurrentDictionary<int, SearchMonitorView>();
internal IPropertyDatabaseView propertyDatabaseView { get; }
internal IPropertyDatabaseView propertyAliasesView { get; }
bool m_Disposed;
bool m_NeedsDispose;
public SearchMonitorView(PropertyDatabase propertyDatabase, PropertyDatabase propertyAliases, bool delayedSync = false)
{
m_Disposed = false;
if (s_PropertyDatabaseViews.TryGetValue(Thread.CurrentThread.ManagedThreadId, out var currentViews))
{
propertyDatabaseView = currentViews.propertyDatabaseView;
propertyAliasesView = currentViews.propertyAliasesView;
m_NeedsDispose = false;
}
else
{
propertyDatabaseView = propertyDatabase.GetView(delayedSync);
propertyAliasesView = propertyAliases.GetView(delayedSync);
m_NeedsDispose = true;
s_PropertyDatabaseViews.TryAdd(Thread.CurrentThread.ManagedThreadId, this);
}
}
public void Dispose()
{
if (m_Disposed || !m_NeedsDispose)
return;
s_PropertyDatabaseViews.TryRemove(Thread.CurrentThread.ManagedThreadId, out _);
propertyDatabaseView.Dispose();
propertyAliasesView.Dispose();
m_Disposed = true;
}
public bool TryLoadProperty(ulong documentKey, string propertyName, out PropertyDatabaseRecordKey recordKey, out object value, out string alias)
{
var propertyHash = PropertyDatabase.CreatePropertyHash(propertyName);
recordKey = PropertyDatabase.CreateRecordKey(documentKey, propertyHash);
if (!propertyAliasesView.TryLoad(recordKey, out object aliasObj))
{
value = null;
alias = propertyName;
SearchMonitor.Log($"<color=red>Failed</color> to load {propertyName} without alias", recordKey, propertyName);
return false;
}
alias = (aliasObj as string) ?? propertyName;
if (propertyDatabaseView.TryLoad(recordKey, out value))
{
SearchMonitor.Log($"Load property {propertyName}", recordKey, value);
return true;
}
SearchMonitor.Log($"<color=red>Failed</color> to load property {propertyName}", recordKey, propertyName);
return false;
}
public bool TryLoadProperty(PropertyDatabaseRecordKey recordKey, out object data)
{
if (propertyDatabaseView.TryLoad(recordKey, out data))
{
SearchMonitor.Log("Load property", recordKey, data);
return true;
}
SearchMonitor.Log("<color=red>Failed</color> to load property", recordKey);
return false;
}
public void StoreProperty(PropertyDatabaseRecordKey recordKey, object value)
{
propertyDatabaseView.Store(recordKey, value);
SearchMonitor.Log("Store property", recordKey, value);
}
public void StoreProperty(PropertyDatabaseRecordKey recordKey, object value, string alias)
{
StoreProperty(recordKey, value);
StoreAlias(recordKey, alias);
}
public bool TryLoadAlias(PropertyDatabaseRecordKey recordKey, out string alias)
{
if (!propertyAliasesView.TryLoad(recordKey, out object aliasObj))
{
SearchMonitor.Log("<color=red>Failed</color> to load alias", recordKey);
alias = null;
return false;
}
alias = aliasObj as string;
SearchMonitor.Log("Load alias", recordKey, alias);
return alias != null;
}
public void StoreAlias(PropertyDatabaseRecordKey key, string alias)
{
propertyAliasesView.Store(key, alias);
SearchMonitor.Log("Store alias", key, alias);
}
public void InvalidateDocument(ulong documentKey)
{
SearchMonitor.Log("Invalidate document", documentKey);
propertyDatabaseView.Invalidate(documentKey);
propertyAliasesView.Invalidate(documentKey);
}
public void InvalidateDocument(string documentKey)
{
SearchMonitor.Log("Invalidate document");
propertyDatabaseView.Invalidate(documentKey);
propertyAliasesView.Invalidate(documentKey);
}
public void Invalidate(PropertyDatabaseRecordKey recordKey)
{
SearchMonitor.Log("Invalidate record", recordKey);
propertyDatabaseView.Invalidate(recordKey);
propertyAliasesView.Invalidate(recordKey);
}
}
[InitializeOnLoad]
public static class SearchMonitor
{
static volatile bool s_Initialize = false;
static bool s_ContentRefreshedEnabled;
static readonly HashSet<string> s_UpdatedItems = new HashSet<string>();
static readonly HashSet<string> s_RemovedItems = new HashSet<string>();
static readonly HashSet<string> s_MovedItems = new HashSet<string>();
static Action s_ContentRefreshOff;
static Delayer s_DelayedInvalidate;
static readonly HashSet<ulong> s_DocumentsToInvalidate = new HashSet<ulong>();
public static bool pending => s_UpdatedItems.Count > 0 || s_RemovedItems.Count > 0 || s_MovedItems.Count > 0;
internal static bool enabled => InternalEditorUtility.isHumanControllingUs || File.Exists("Assets/Editor/test_search_monitor.txt");
public static event Action sceneChanged;
public static event ObjectChangeEvents.ObjectChangeEventsHandler objectChanged;
public static event Action documentsInvalidated;
const string k_TransactionDatabasePath = "Library/Search/transactions.db";
static TransactionManager s_TransactionManager;
private static PropertyDatabase propertyDatabase;
private static PropertyDatabase propertyAliases;
static readonly object s_ContentRefreshedLock = new object();
static event Action<string[], string[], string[]> s_ContentRefreshed;
public static event Action<string[], string[], string[]> contentRefreshed
{
add
{
lock (s_ContentRefreshedLock)
{
EnableContentRefresh();
s_ContentRefreshed -= value;
s_ContentRefreshed += value;
}
}
remove
{
lock (s_ContentRefreshedLock)
{
s_ContentRefreshed -= value;
if (s_ContentRefreshed == null || s_ContentRefreshed.GetInvocationList().Length == 0)
DisableContentRefresh();
}
}
}
static double refreshContentDelay
{
get
{
if (Utils.runningTests)
return 0d;
return 1d;
}
}
static SearchMonitor()
{
if (!Utils.IsMainProcess() || !enabled)
return;
if (!EditorApplication.isPlayingOrWillChangePlaymode)
Init();
else
Utils.CallDelayed(Init);
}
static void Init()
{
if (s_Initialize)
return;
Log("Initialize search monitor", 0UL);
s_TransactionManager = new TransactionManager(k_TransactionDatabasePath);
s_TransactionManager.Init();
propertyDatabase = new PropertyDatabase("Library/Search/propertyDatabase.db", true);
propertyAliases = new PropertyDatabase("Library/Search/propertyAliases.db", true);
EditorApplication.quitting += OnQuitting;
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
EditorSceneManager.activeSceneChangedInEditMode += (_, __) => InvalidateCurrentScene();
EditorSceneManager.sceneOpened += (scene, mode) => InvalidateCurrentScene();
EditorSceneManager.sceneClosed += scene => InvalidateCurrentScene();
PrefabStage.prefabStageOpened += _ => InvalidateCurrentScene();
PrefabStage.prefabStageClosing += _ => InvalidateCurrentScene();
EditorApplication.playModeStateChanged += _ => InvalidateCurrentScene();
s_DelayedInvalidate = Delayer.Debounce(_ => InvalidateDocuments());
ObjectChangeEvents.changesPublished += OnObjectChanged;
EditorApplication.playModeStateChanged += OnPlayModeChanged;
s_Initialize = true;
}
public static AssetIndexChangeSet GetDiff(long timestamp, IEnumerable<string> deletedAssets, Func<string, bool> predicate)
{
if (s_TransactionManager == null)
return AssetIndexChangeSet.s_Empty;
var updated = new HashSet<string>();
var moved = new HashSet<string>();
var removed = new HashSet<string>(deletedAssets);
var transactions = s_TransactionManager.Read(TimeRange.From(DateTime.FromBinary(timestamp).ToUniversalTime(), false));
foreach (var t in transactions)
{
var state = (AssetModification)t.state;
var assetPath = AssetDatabase.GUIDToAssetPath(t.guid.ToString());
if ((state & AssetModification.Updated) == AssetModification.Updated)
updated.Add(assetPath);
else if ((state & AssetModification.Moved) == AssetModification.Moved)
moved.Add(assetPath);
else if ((state & AssetModification.Removed) == AssetModification.Removed)
removed.Add(assetPath);
}
return new AssetIndexChangeSet(updated, removed, moved, predicate);
}
public static void RaiseContentRefreshed(string[] updated, string[] removed, string[] moved)
{
UpdateTransactionManager(updated, removed, moved);
InvalidatePropertyDatabase(updated, removed, moved);
if (!s_ContentRefreshedEnabled)
return;
s_UpdatedItems.UnionWith(updated);
s_RemovedItems.UnionWith(removed);
s_MovedItems.UnionWith(moved);
if (s_UpdatedItems.Count > 0 || s_RemovedItems.Count > 0 || s_MovedItems.Count > 0)
{
Log("Content changed", (ulong)(s_UpdatedItems.Count + s_RemovedItems.Count + s_MovedItems.Count));
s_ContentRefreshOff?.Invoke();
s_ContentRefreshOff = Utils.CallDelayed(RaiseContentRefreshed, refreshContentDelay);
}
}
internal static Task TriggerPropertyDatabaseBackgroundUpdate()
{
return Task.WhenAll(propertyDatabase.TriggerBackgroundUpdate(), propertyAliases.TriggerBackgroundUpdate());
}
internal static void PrintInfo()
{
var sb = new StringBuilder();
sb.Append(propertyDatabase.GetInfo());
sb.Append(propertyAliases.GetInfo());
sb.Append(s_TransactionManager.GetInfo());
Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, sb.ToString());
}
public static SearchMonitorView GetView(bool delayedSync = false)
{
if (!s_Initialize)
Init();
return new SearchMonitorView(propertyDatabase, propertyAliases, delayedSync);
}
static void OnPlayModeChanged(PlayModeStateChange playMode)
{
if (playMode == PlayModeStateChange.EnteredPlayMode)
{
EditorApplication.hierarchyChanged += OnHierarchyChanged;
}
else
{
EditorApplication.hierarchyChanged -= OnHierarchyChanged;
}
}
static void OnHierarchyChanged()
{
InvalidateCurrentScene();
}
static void DisableContentRefresh()
{
s_ContentRefreshedEnabled = false;
}
static void EnableContentRefresh()
{
if (!Utils.IsMainProcess())
return;
s_ContentRefreshedEnabled = true;
}
static void OnObjectChanged(ref ObjectChangeEventStream stream)
{
HandleObjectChanged(ref stream);
var handler = objectChanged;
handler?.Invoke(ref stream);
}
static void InvalidateCurrentScene()
{
var handler = sceneChanged;
handler?.Invoke();
Log("Invalidate scene", 0UL);
}
static void OnQuitting()
{
s_ContentRefreshedEnabled = false;
s_TransactionManager?.Shutdown();
propertyDatabase?.Dispose();
propertyAliases?.Dispose();
}
static void OnBeforeAssemblyReload()
{
s_TransactionManager?.Shutdown();
propertyDatabase?.Dispose();
propertyAliases?.Dispose();
}
static void RaiseContentRefreshed()
{
s_ContentRefreshOff = null;
if (s_UpdatedItems.Count == 0 && s_RemovedItems.Count == 0 && s_MovedItems.Count == 0)
return;
Log("Content refreshed", (ulong)(s_UpdatedItems.Count + s_RemovedItems.Count + s_MovedItems.Count));
s_ContentRefreshed?.Invoke(s_UpdatedItems.ToArray(), s_RemovedItems.ToArray(), s_MovedItems.ToArray());
s_UpdatedItems.Clear();
s_RemovedItems.Clear();
s_MovedItems.Clear();
}
static void UpdateTransactionManager(string[] updated, string[] removed, string[] moved)
{
if (s_TransactionManager != null && s_TransactionManager.Initialized)
{
var timestamp = DateTime.UtcNow.ToBinary();
var transactions = updated.Select(path => new Transaction(AssetDatabase.AssetPathToGUID(path), AssetModification.Updated, timestamp))
.Concat(removed.Select(path => new Transaction(AssetDatabase.AssetPathToGUID(path), AssetModification.Removed, timestamp)))
.Concat(moved.Select(path => new Transaction(AssetDatabase.AssetPathToGUID(path), AssetModification.Moved, timestamp))).ToList();
s_TransactionManager.Write(transactions);
}
}
static void InvalidatePropertyDatabase(string[] updated, string[] removed, string[] moved)
{
foreach (var assetPath in updated.Concat(removed).Concat(moved))
InvalidateDocument(AssetDatabase.AssetPathToGUID(assetPath));
}
static void HandleObjectChanged(ref ObjectChangeEventStream stream)
{
for (int i = 0; i < stream.length; ++i)
{
var eventType = stream.GetEventType(i);
switch (eventType)
{
case ObjectChangeKind.None:
case ObjectChangeKind.ChangeScene:
case ObjectChangeKind.ChangeAssetObjectProperties:
case ObjectChangeKind.CreateAssetObject:
case ObjectChangeKind.DestroyAssetObject:
break;
case ObjectChangeKind.DestroyGameObjectHierarchy:
{
stream.GetDestroyGameObjectHierarchyEvent(i, out var e);
InvalidateObject(e.instanceId);
}
break;
case ObjectChangeKind.CreateGameObjectHierarchy:
{
stream.GetCreateGameObjectHierarchyEvent(i, out var e);
InvalidateObject(e.instanceId);
}
break;
case ObjectChangeKind.ChangeGameObjectStructureHierarchy:
{
stream.GetChangeGameObjectStructureHierarchyEvent(i, out var e);
InvalidateObject(e.instanceId);
}
break;
case ObjectChangeKind.ChangeGameObjectStructure:
{
stream.GetChangeGameObjectStructureEvent(i, out var e);
InvalidateObject(e.instanceId);
}
break;
case ObjectChangeKind.ChangeGameObjectParent:
{
stream.GetChangeGameObjectParentEvent(i, out var e);
InvalidateObject(e.instanceId);
}
break;
case ObjectChangeKind.ChangeGameObjectOrComponentProperties:
{
stream.GetChangeGameObjectOrComponentPropertiesEvent(i, out var e);
InvalidateObject(e.instanceId);
}
break;
case ObjectChangeKind.UpdatePrefabInstances:
{
stream.GetUpdatePrefabInstancesEvent(i, out var e);
for (int idIndex = 0; idIndex < e.instanceIds.Length; ++idIndex)
InvalidateObject(e.instanceIds[idIndex]);
}
break;
}
}
}
public static void Reset()
{
propertyDatabase?.Clear();
propertyAliases?.Clear();
s_TransactionManager?.ClearAll();
}
private static void InvalidateObject(int instanceId)
{
var obj = EditorUtility.InstanceIDToObject(instanceId);
var documentKey = SearchUtils.GetDocumentKey(obj);
InvalidateDocument(documentKey);
}
private static void InvalidateDocument(string documentId)
{
InvalidateDocument(documentId.GetHashCode64());
}
private static void InvalidateDocument(ulong documentKey)
{
s_DocumentsToInvalidate.Add(documentKey);
s_DelayedInvalidate?.Execute();
}
private static void InvalidateDocuments()
{
using (var view = GetView(true))
{
foreach (var k in s_DocumentsToInvalidate)
view.InvalidateDocument(k);
}
s_DocumentsToInvalidate.Clear();
documentsInvalidated?.Invoke();
}
[System.Diagnostics.Conditional("DEBUG_SEARCH_MONITOR")]
public static void Log(string message, ulong documentKey = 0UL)
{
Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, $"{message}: <b>{documentKey}</b>");
}
[System.Diagnostics.Conditional("DEBUG_SEARCH_MONITOR")]
internal static void Log(string message, PropertyDatabaseRecordKey recordKey, object value = null)
{
Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, $"{message}: <b>{recordKey.documentKey}</b>, {recordKey.propertyKey}={value}");
}
}
static class AssetDatabaseAPI
{
public static bool IsAssetImportWorkerProcess()
{
return AssetDatabase.IsAssetImportWorkerProcess();
}
public static void RegisterCustomDependency(string name, Hash128 hash)
{
AssetDatabase.RegisterCustomDependency(name, hash);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/SearchMonitor.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchMonitor.cs",
"repo_id": "UnityCsReference",
"token_count": 9918
} | 448 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
static class PropertySelectors
{
[SearchSelector(@"#(?<propertyPath>[\w\d\.\[\]]+)", 9999, printable: false)]
[SearchSelector("SerializedProperty/(?<propertyPath>.+)", 9999, printable: false)]
public static object GetSerializedPropertyValue(SearchSelectorArgs args)
{
if (!(args["propertyPath"] is string propertyPath))
return null;
return GetSerializedPropertyValue(args.current, propertyPath);
}
internal static object GetSerializedPropertyValue(SearchItem item, string propertyPath)
{
object value = null;
var property = GetSerializedProperty(item, propertyPath, out var so);
if (property != null)
value = GetSerializedPropertyValue(property);
property?.Dispose();
so?.Dispose();
return value;
}
internal static SerializedProperty GetSerializedProperty(SearchItem item, SearchColumn column, out SerializedObject so)
{
foreach (var m in SelectorManager.Match(column.selector, item.provider?.type))
{
var selectorArgs = new SearchSelectorArgs(m, item);
if (selectorArgs.name == null)
continue;
var property = GetSerializedProperty(item, selectorArgs.name, out so);
if (property == null)
{
so?.Dispose();
continue;
}
so.UpdateIfRequiredOrScript();
return property;
}
so = null;
return null;
}
internal static SerializedProperty GetSerializedProperty(SearchItem item, string propertyPath, out SerializedObject so)
{
var go = item.ToObject<GameObject>();
if (go)
{
foreach (var c in go.GetComponents<Component>())
{
var v = FindProperty(c, propertyPath, out so);
if (v != null)
return v;
}
}
return FindProperty(item.ToObject<AssetImporter>(), propertyPath, out so) ??
FindProperty(item.ToObject(), propertyPath, out so);
}
public static SerializedProperty FindProperty(UnityEngine.Object obj, string propertyPath, out SerializedObject so)
{
if (!obj)
{
so = null;
return null;
}
so = new SerializedObject(obj);
var property = so.FindProperty(propertyPath);
if (property != null)
return property;
using (var view = SearchMonitor.GetView())
{
var documentKey = SearchUtils.GetDocumentKey(obj);
var recordKey = PropertyDatabase.CreateRecordKey(documentKey, PropertyDatabase.CreatePropertyHash($"{obj.GetType().Name}.{propertyPath}"));
if (view.TryLoadAlias(recordKey, out var resolvedPropertyPath))
{
if (string.IsNullOrEmpty(resolvedPropertyPath))
{
so?.Dispose();
return null;
}
var resolvedProperty = so.FindProperty(resolvedPropertyPath);
if (resolvedProperty != null)
return resolvedProperty;
}
property = so.FindProperty($"m_{propertyPath}");
if (property != null)
{
view.StoreAlias(recordKey, property.propertyPath);
return property;
}
property = so.GetIterator();
var next = property.NextVisible(true);
while (next)
{
if (property.name.EndsWith(propertyPath, StringComparison.OrdinalIgnoreCase) ||
(property.name.Contains(" ") && property.name.Replace(" ", "").EndsWith(propertyPath, StringComparison.OrdinalIgnoreCase)))
{
view.StoreAlias(recordKey, property.propertyPath);
return property;
}
next = property.NextVisible(property.hasChildren);
}
view.StoreAlias(recordKey, string.Empty);
so?.Dispose();
so = null;
return null;
}
}
internal static string GetEnumValue(SerializedProperty p)
{
return p.enumNames[p.enumValueIndex].Replace(" ", "");
}
internal static string GetEnumValue(Type type, SerializedProperty p)
{
return type.GetEnumValues().GetValue(p.intValue).ToString().Replace(" ", "");
}
internal static object GetSerializedPropertyValue(SerializedProperty p)
{
switch (p.propertyType)
{
case SerializedPropertyType.Character:
case SerializedPropertyType.ArraySize:
case SerializedPropertyType.Integer:
return p.intValue;
case SerializedPropertyType.Boolean: return p.boolValue;
case SerializedPropertyType.Float: return p.floatValue;
case SerializedPropertyType.String: return p.stringValue;
case SerializedPropertyType.Enum: return GetEnumValue(p);
case SerializedPropertyType.Bounds: return p.boundsValue.size.magnitude;
case SerializedPropertyType.BoundsInt: return p.boundsIntValue.size.magnitude;
case SerializedPropertyType.Color: return p.colorValue;
case SerializedPropertyType.FixedBufferSize: return p.fixedBufferSize;
case SerializedPropertyType.Rect: return Utils.ToString(p.rectValue);
case SerializedPropertyType.RectInt: return Utils.ToString(p.rectIntValue);
case SerializedPropertyType.Vector2: return Utils.ToString(p.vector2Value, 2);
case SerializedPropertyType.Vector3: return Utils.ToString(p.vector3Value, 3);
case SerializedPropertyType.Vector4: return Utils.ToString(p.vector4Value, 4);
case SerializedPropertyType.Vector2Int: return Utils.ToString(p.vector2IntValue);
case SerializedPropertyType.Vector3Int: return Utils.ToString(p.vector3IntValue);
case SerializedPropertyType.AnimationCurve: return p.animationCurveValue.ToString();
case SerializedPropertyType.Quaternion: return Utils.ToString(p.quaternionValue.eulerAngles);
case SerializedPropertyType.ObjectReference: return p.objectReferenceValue;
case SerializedPropertyType.ExposedReference: return p.exposedReferenceValue;
case SerializedPropertyType.Gradient: return p.gradientValue.ToString();
case SerializedPropertyType.LayerMask: return p.layerMaskBits;
case SerializedPropertyType.RenderingLayerMask: return p.layerMaskBits;
case SerializedPropertyType.Hash128: return p.hash128Value.ToString();
case SerializedPropertyType.ManagedReference:
case SerializedPropertyType.Generic:
break;
}
if (p.isArray)
return p.arraySize;
return null;
}
public static IEnumerable<SearchColumn> Enumerate(IEnumerable<SearchItem> items)
{
var descriptors = new List<SearchColumn>();
var templates = SearchUtils.GetTemplates(items.Where(e => e != null).Select(e => e.ToObject()).Where(e => e));
foreach (var obj in templates)
{
var objType = obj.GetType();
var columns = new List<SearchColumn>();
FillSerializedPropertyColumns(obj, objType, columns);
if (columns.Count <= 0)
continue;
foreach (var c in columns)
c.content.image = Utils.FindTextureForType(objType);
descriptors.AddRange(columns);
}
return descriptors;
}
static void FillSerializedPropertyColumns(UnityEngine.Object obj, Type objType, List<SearchColumn> columns)
{
var iconType = Utils.FindTextureForType(objType);
using (var so = new SerializedObject(obj))
{
SearchUtils.IterateSupportedProperties(so, p =>
{
var column = new SearchColumn(
path: $"{objType.Name}/{p.propertyPath.Replace(".", "/")}",
selector: "#" + p.propertyPath,
provider: p.propertyType.ToString(),
content: new GUIContent(Utils.TrimText(p.displayName, 31), iconType, p.tooltip));
ItemSelectors.Styles.itemLabel.CalcMinMaxWidth(column.content, out column.width, out _);
if (p.hasVisibleChildren)
column.width = Mathf.Min(220, column.width);
columns.Add(column);
});
}
}
[SearchColumnProvider("Color")]
public static void InitializeColorColumn(SearchColumn column)
{
column.cellCreator = col => new ColorField()
{
showAlpha = true,
hdr = false,
showEyeDropper = false,
pickingMode = PickingMode.Ignore
};
column.binder = (SearchColumnEventArgs args, VisualElement ve) =>
{
if (args.value is Color c)
{
var color = (ColorField)ve;
color.value = c;
}
else if (args.value is MaterialProperty mp)
{
var color = (ColorField)ve;
color.value = mp.colorValue;
}
};
}
[SearchColumnProvider("Texture2D")]
public static void InitializeTextureColumn(SearchColumn column)
{
column.cellCreator = (col) => new Image()
{
style =
{
backgroundPositionX = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleToFit),
backgroundPositionY = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleToFit),
backgroundRepeat = BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat(ScaleMode.ScaleToFit),
backgroundSize = BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(ScaleMode.ScaleToFit)
}
};
column.binder = (SearchColumnEventArgs args, VisualElement ve) =>
{
var img = (Image)ve;
img.image = args.value as Texture;
};
}
[SearchColumnProvider("ObjectReference")]
public static void InitializeObjectReferenceColumn(SearchColumn column)
{
column.cellCreator = (col) => new UIElements.ObjectField() { objectType = col.GetMatchingType() };
column.binder = (SearchColumnEventArgs args, VisualElement ve) =>
{
var field = (UIElements.ObjectField)ve;
field.pickingMode = PickingMode.Ignore;
field.objectType = args.value?.GetType() ?? typeof(UnityEngine.Object);
field.value = args.value as UnityEngine.Object;
field.Query<VisualElement>(className: "unity-object-field__selector").ForEach(e => e.style.display = DisplayStyle.None);
};
}
[SearchColumnProvider("ObjectPath")]
public static void InitializeObjectPathColumn(SearchColumn column)
{
column.getter = GetObjectPath;
}
private static object GetObjectPath(SearchColumnEventArgs args)
{
var value = args.column.SelectValue(args.item, args.context);
if (value is UnityEngine.Object obj)
{
var objPath = AssetDatabase.GetAssetPath(obj);
if (!string.IsNullOrEmpty(objPath))
return objPath;
if (obj is GameObject go)
return SearchUtils.GetTransformPath(go.transform);
}
return value;
}
static class SerializedPropertyColumnProvider
{
[SearchColumnProvider("SerializedProperty")]
public static void InitializeSerializedPropertyColumn(SearchColumn column)
{
column.getter = args => Getter(args.item, args.column);
column.setter = args => Setter(args.item, args.column, args.value, args.multiple);
column.comparer = args => Comparer(args.lhs.value, args.rhs.value, args.sortAscending);
column.cellCreator = args => MakePropertyField(args);
column.binder = (args, ve) => BindPropertyField(args, ve);
}
private static VisualElement MakePropertyField(SearchColumn args)
{
return new PropertyField() { label = string.Empty };
}
private static void BindPropertyField(SearchColumnEventArgs args, VisualElement ve)
{
if (ve is not PropertyField f)
throw new SearchColumnBindException(args.column, "Rebuild table");
f.Unbind();
if (args.value is SerializedProperty p)
{
f.visible = true;
if (p.propertyType == SerializedPropertyType.Integer || p.propertyType == SerializedPropertyType.Float)
f.label = "\u2022";
else
f.label = string.Empty;
f.BindProperty(p);
}
else
{
f.visible = false;
f.Unbind();
}
}
static class DefaultDelegates
{
public static int CompareColorHandler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
Color.RGBToHSV(lhsObjCast.colorValue, out float lh, out _, out _);
Color.RGBToHSV(rhsObjCast.colorValue, out float rh, out _, out _);
return lh.CompareTo(rh);
}
public static int CompareFloatHandler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
return lhsObjCast.floatValue.CompareTo(rhsObjCast.floatValue);
}
public static int CompareCheckboxHandler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
return lhsObjCast.boolValue.CompareTo(rhsObjCast.boolValue);
}
public static int CompareIntHandler(SerializedProperty lhs, SerializedProperty rhs)
{
return lhs.intValue.CompareTo(rhs.intValue);
}
public static int CompareEnumHandler(SerializedProperty lhs, SerializedProperty rhs)
{
return lhs.enumValueIndex.CompareTo(rhs.enumValueIndex);
}
public static int CompareVector2Handler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
return lhsObjCast.vector2Value.magnitude.CompareTo(rhsObjCast.vector2Value.magnitude);
}
public static int CompareVector2IntHandler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
return lhsObjCast.vector2IntValue.magnitude.CompareTo(rhsObjCast.vector2IntValue.magnitude);
}
public static int CompareVector3Handler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
return lhsObjCast.vector3Value.magnitude.CompareTo(rhsObjCast.vector3Value.magnitude);
}
public static int CompareVector3IntHandler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
return lhsObjCast.vector3IntValue.magnitude.CompareTo(rhsObjCast.vector3IntValue.magnitude);
}
public static int CompareVector4Handler(SerializedProperty lhsObjCast, SerializedProperty rhsObjCast)
{
return lhsObjCast.vector4Value.magnitude.CompareTo(rhsObjCast.vector4Value.magnitude);
}
internal static int CompareReferencesHandler(SerializedProperty lhs, SerializedProperty rhs)
{
return string.CompareOrdinal(lhs.objectReferenceValue?.name, rhs.objectReferenceValue?.name);
}
internal static int CompareStringHandler(SerializedProperty lhs, SerializedProperty rhs)
{
return string.CompareOrdinal(lhs.stringValue, rhs.stringValue);
}
}
public static object Getter(SearchItem item, SearchColumn column)
{
var p = GetSerializedProperty(item, column, out var _);
if (column.drawer != null || column.binder != null)
{
if (p != null)
p.isExpanded = true;
return p;
}
if (p == null)
return null;
return GetSerializedPropertyValue(p);
}
public static void Setter(SearchItem item, SearchColumn column, object newValue, bool multiple)
{
if (!(newValue is SerializedProperty newValueProperty))
return;
if (!multiple)
{
newValueProperty.serializedObject.ApplyModifiedProperties();
}
else
{
var property = GetSerializedProperty(item, column, out var so);
if (property != null && so != null)
{
so.CopyFromSerializedProperty(newValueProperty);
so.ApplyModifiedProperties();
property.Dispose();
so.Dispose();
}
}
}
public static int Comparer(object lhsObj, object rhsObj, bool sortAscending)
{
if (!(lhsObj is SerializedProperty lhsProp) ||
!(rhsObj is SerializedProperty rhsProp) ||
lhsProp.propertyType != rhsProp.propertyType)
return 0;
var sortOrder = sortAscending ? 1 : -1;
switch (lhsProp.propertyType)
{
case SerializedPropertyType.String: return DefaultDelegates.CompareStringHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Enum: return DefaultDelegates.CompareEnumHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Float: return DefaultDelegates.CompareFloatHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Integer: return DefaultDelegates.CompareIntHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Color: return DefaultDelegates.CompareColorHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Boolean: return DefaultDelegates.CompareCheckboxHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Vector2: return DefaultDelegates.CompareVector2Handler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Vector2Int: return DefaultDelegates.CompareVector2IntHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Vector3: return DefaultDelegates.CompareVector3Handler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Vector3Int: return DefaultDelegates.CompareVector3IntHandler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.Vector4: return DefaultDelegates.CompareVector4Handler(lhsProp, rhsProp) * sortOrder;
case SerializedPropertyType.ObjectReference: return DefaultDelegates.CompareReferencesHandler(lhsProp, rhsProp) * sortOrder;
}
return lhsProp.GetHashCode().CompareTo(rhsProp.GetHashCode()) * sortOrder;
}
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/Selectors/PropertySelectors.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/Selectors/PropertySelectors.cs",
"repo_id": "UnityCsReference",
"token_count": 10342
} | 449 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor.Search
{
static class Icons
{
public static string iconFolder = $"Icons/QuickSearch";
public static Texture2D quicksearch = EditorGUIUtility.FindTexture("Search Icon");
public static Texture2D shortcut = EditorGUIUtility.FindTexture("Shortcut Icon");
public static Texture2D staticAPI = EditorGUIUtility.FindTexture("cs Script Icon");
public static Texture2D settings = EditorGUIUtility.FindTexture("Settings Icon");
public static Texture2D favorite = EditorGUIUtility.FindTexture("Favorite Icon");
public static Texture2D store = EditorGUIUtility.FindTexture("AssetStore Icon");
public static Texture2D help = EditorGUIUtility.LoadIcon($"Icons/_Help.png");
public static Texture2D clear = EditorGUIUtility.LoadIcon("StyleSheets/Northstar/Images/clear.png");
public static Texture2D quickSearchWindow = EditorGUIUtility.LoadIcon($"{iconFolder}/SearchWindow.png");
public static Texture2D more = EditorGUIUtility.LoadIcon($"{iconFolder}/more.png");
public static Texture2D logInfo = EditorGUIUtility.LoadIcon("UIPackageResources/Images/console.infoicon.png");
public static Texture2D logWarning = EditorGUIUtility.LoadIcon("UIPackageResources/Images/cconsole.warnicon.png");
public static Texture2D logError = EditorGUIUtility.LoadIcon("UIPackageResources/Images/console.erroricon.png");
public static Texture2D packageInstalled = EditorGUIUtility.LoadIcon($"{iconFolder}/package_installed.png");
public static Texture2D packageUpdate = EditorGUIUtility.LoadIcon($"{iconFolder}/package_update.png");
public static Texture2D dependencies = EditorGUIUtility.LoadIcon("UnityEditor.FindDependencies");
public static Texture2D toggles = EditorGUIUtility.FindTexture("MoreOptions");
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UI/Icons.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UI/Icons.cs",
"repo_id": "UnityCsReference",
"token_count": 649
} | 450 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Linq;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Search;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
class SearchFieldElement : SearchElement
{
enum FocusType
{
None,
MoveEnd,
SelectAll
}
internal class VisualMessage : VisualElement
{
string m_Text;
Color m_Color;
public int startIndex { get; private set; }
public int endIndex { get; private set; }
public VisualMessage(int startIndex, int endIndex, string text, in Color color, in Rect position)
{
this.startIndex = startIndex;
this.endIndex = endIndex;
m_Text = text;
m_Color = color;
style.position = Position.Absolute;
UpdatePosition(position);
this.generateVisualContent += GenerateVisualContent;
this.tooltip = m_Text;
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
this.generateVisualContent -= GenerateVisualContent;
}
void GenerateVisualContent(MeshGenerationContext mgc)
{
var halfPoint = localBound.height / 2;
mgc.painter2D.BeginPath();
mgc.painter2D.lineWidth = 2f;
mgc.painter2D.strokeColor = m_Color;
mgc.painter2D.MoveTo(new Vector2(0, halfPoint));
mgc.painter2D.LineTo(new Vector2(localBound.width, halfPoint));
mgc.painter2D.Stroke();
}
public void UpdatePosition(in Rect newPosition)
{
style.left = newPosition.xMin;
style.width = newPosition.width;
style.top = newPosition.yMin;
style.height = newPosition.height;
}
}
public static readonly string pressToFilterTooltip = L10n.Tr("Press Tab \u21B9 to filter");
protected INotifyValueChanged<string> m_SearchTextInput;
private readonly UndoManager m_UndoManager;
private readonly Label m_SearchPlaceholder;
private readonly Label m_PressTabPlaceholder;
private readonly bool m_UseSearchGlobalEventHandler;
private Button m_CancelButton;
const float k_PlaceholdersTouchThreshold = 2f;
public ToolbarSearchField searchField { get; private set; }
internal QueryBuilder queryBuilder => (m_SearchTextInput as SearchQueryBuilderView)?.builder;
internal string queryString => viewState.queryBuilderEnabled ? queryBuilder.BuildQuery() : searchField.value;
internal Texture2D addNewBlockIcon { get; set; }
List<VisualMessage> m_VisualMessages = new();
IVisualElementScheduledItem m_UpdateQueryErrorScheduledItem;
internal List<VisualMessage> visualMessages => m_VisualMessages;
internal IVisualElementScheduledItem queryErrorsScheduleItem => m_UpdateQueryErrorScheduledItem;
internal INotifyValueChanged<string> searchTextInput => m_SearchTextInput;
public TextElement textElement
{
get
{
if (textField?.Q<TextElement>() is not TextElement te)
return null;
return te;
}
}
internal TextField textField
{
get
{
if (viewState.queryBuilderEnabled && queryBuilder != null)
return queryBuilder?.textBlock?.GetSearchField()?.GetTextElement() as TextField;
if (searchField?.Q<TextField>() is not TextField tf)
return null;
return tf;
}
}
TextSelectingUtilities selectingUtilities => textElement?.selectingManipulator?.m_SelectingUtilities;
public bool supportsMultiline => !viewState.queryBuilderEnabled;
public static readonly string searchFieldClassName = "search-field";
public static readonly string searchFieldPlaceholderClassName = "search-field-placeholder";
public static readonly string searchFieldMultilineClassName = "search-field-multiline";
public SearchFieldElement(string name, ISearchView viewModel, bool useSearchGlobalEventHandler)
: base(name, viewModel)
{
this.name = name;
m_UseSearchGlobalEventHandler = useSearchGlobalEventHandler;
m_SearchPlaceholder = new Label($"Search {viewState.title}");
m_SearchPlaceholder.AddToClassList(searchFieldPlaceholderClassName);
m_SearchPlaceholder.style.paddingLeft = 4f;
m_SearchPlaceholder.focusable = false;
m_SearchPlaceholder.pickingMode = PickingMode.Ignore;
m_PressTabPlaceholder = new Label(pressToFilterTooltip);
m_PressTabPlaceholder.AddToClassList(searchFieldPlaceholderClassName);
m_PressTabPlaceholder.style.paddingBottom = 3f;
m_PressTabPlaceholder.focusable = false;
m_PressTabPlaceholder.pickingMode = PickingMode.Ignore;
if (!context.empty)
m_PressTabPlaceholder.style.right = 12f;
else
m_PressTabPlaceholder.style.right = 2f;
// Search field
CreateSearchField(this);
m_UndoManager = new UndoManager(context.searchText);
Utils.CallDelayed(SaveUndoManager, 2.0d);
}
private void CreateSearchField(VisualElement searchFieldContainer)
{
m_SearchTextInput = null;
m_VisualMessages.Clear();
searchFieldContainer.Clear();
searchFieldContainer.style.flexDirection = FlexDirection.Row;
searchFieldContainer.style.flexGrow = 1f;
ClearOnCursorChangedHandlers();
searchField = new ToolbarSearchField() { name = "SearchField" };
searchField.AddToClassList(searchFieldClassName);
searchField.style.flexGrow = 1f;
searchField.Children().First().style.display = DisplayStyle.None;
textField.tripleClickSelectsLine = true;
textField.selectAllOnFocus = false;
m_CancelButton = new Button(() => { }) { name = "query-builder-unity-cancel" };
m_CancelButton.AddToClassList(SearchFieldBase<TextField, string>.cancelButtonUssClassName);
m_CancelButton.AddToClassList(SearchFieldBase<TextField, string>.cancelButtonOffVariantUssClassName);
m_CancelButton.clickable.clicked += OnCancelButtonClick;
if (viewState.queryBuilderEnabled)
{
var queryBuilderView = new SearchQueryBuilderView("SearchQueryBuilder", m_ViewModel, searchField, m_UseSearchGlobalEventHandler);
searchField.Insert(1, queryBuilderView);
searchField.RegisterCallback<ChangeEvent<string>>(OnQueryChanged);
m_SearchTextInput = queryBuilderView;
}
else
{
searchField.value = context.searchText;
searchField.Add(m_SearchPlaceholder);
searchField.Add(m_PressTabPlaceholder);
searchField.RegisterCallback<ChangeEvent<string>>(OnQueryChanged);
searchField.RegisterCallback<GeometryChangedEvent>(evt => UpdatePlaceholders());
m_SearchTextInput = textField;
}
searchField.RegisterCallback<AttachToPanelEvent>(OnSearchFieldAttachToPanel);
searchField.RegisterCallback<DetachFromPanelEvent>(OnSearchFieldDetachFromPanel);
searchFieldContainer.Add(searchField);
if (selectingUtilities != null)
{
selectingUtilities.OnCursorIndexChange += OnCursorChanged;
selectingUtilities.OnSelectIndexChange += OnCursorChanged;
}
}
public void FocusSearchField()
{
FocusSearchField(FocusType.SelectAll);
}
void FocusSearchField(FocusType focusType)
{
if (!(textElement?.GetSearchHostWindow()?.HasFocus() ?? false))
return;
if (textElement != null && textElement.selection != null)
{
textElement.Focus();
Utils.CallDelayed(() => // Call delayed is needed because TextSelectingUtilities.OnFocus is overriding the cursor setting
{
Dispatcher.Emit(SearchEvent.SearchFieldFocused, new SearchEventPayload(this));
// the text element might have been detached by the time the delayed callback fires
if (textElement?.selection == null)
return;
if (focusType != FocusType.None && m_ViewModel.IsPicker())
focusType = FocusType.MoveEnd;
switch (focusType)
{
case FocusType.None: break;
case FocusType.MoveEnd:
textElement.selection.MoveTextEnd();
break;
case FocusType.SelectAll:
textElement.selection.SelectAll();
break;
}
});
}
else
Dispatcher.Emit(SearchEvent.SearchFieldFocused, new SearchEventPayload(this));
}
private void UpdatePlaceholders()
{
m_SearchPlaceholder.style.visibility = !context.empty ? Visibility.Hidden : Visibility.Visible;
if (m_SearchPlaceholder.worldBound.xMax + k_PlaceholdersTouchThreshold >= searchField.worldBound.xMax)
m_SearchPlaceholder.style.visibility = Visibility.Hidden;
var oldRight = m_PressTabPlaceholder.style.right.value.value;
if (!context.empty)
m_PressTabPlaceholder.style.right = 12f;
else
m_PressTabPlaceholder.style.right = 2f;
var offset = m_PressTabPlaceholder.style.right.value.value - oldRight;
var te = searchField.Q<TextElement>();
if (te != null)
{
var textSize = te.MeasureTextSize(searchField.value, resolvedStyle.width, MeasureMode.AtMost, resolvedStyle.height, MeasureMode.Exactly);
if ((textSize.x + te.worldBound.x) >= (m_PressTabPlaceholder.worldBound.xMin - 60f))
m_PressTabPlaceholder.style.visibility = Visibility.Hidden;
else
m_PressTabPlaceholder.style.visibility = Visibility.Visible;
if (m_PressTabPlaceholder.style.visibility == Visibility.Visible && (m_PressTabPlaceholder.worldBound.xMin - offset) <= m_SearchPlaceholder.worldBound.xMax + k_PlaceholdersTouchThreshold)
m_PressTabPlaceholder.style.visibility = Visibility.Hidden;
}
else
m_PressTabPlaceholder.style.display = DisplayStyle.None;
}
private void OnQueryChanged(ChangeEvent<string> evt)
{
UpdateCancelButton();
if (m_SearchTextInput != evt.target)
return;
m_ViewModel.SetSearchText(evt.newValue, TextCursorPlacement.None);
m_ViewModel.SetSelection();
UpdatePlaceholders();
UpdateQueryErrors();
UpdateMultiline();
}
private void OnSearchFieldAttachToPanel(AttachToPanelEvent evt)
{
FocusSearchField();
searchField.RegisterCallback<GeometryChangedEvent>(OnSearchFieldReady);
var cancelButton = searchField.Q<Button>(null, SearchFieldBase<TextField, string>.cancelButtonUssClassName);
if (cancelButton != null)
HideElements(cancelButton);
searchField.Add(m_CancelButton);
}
private void OnSearchFieldDetachFromPanel(DetachFromPanelEvent evt)
{
Dispatcher.Off(SearchEvent.SearchTextChanged, OnSearchTextChanged);
Dispatcher.Off(SearchEvent.SearchContextChanged, OnSearchContextChanged);
Dispatcher.Off(SearchEvent.RefreshBuilder, OnQueryBuilderStateChanged);
Dispatcher.Off(SearchEvent.RefreshContent, OnRefreshContent);
UnregisterCallback<KeyDownEvent>(OnSearchToolbarKeyDown);
searchField.UnregisterCallback<KeyDownEvent>(OnSearchFieldKeyDown);
viewState.globalEventManager.UnregisterGlobalEventHandler<KeyDownEvent>(OnGlobalKeyInput);
ClearOnCursorChangedHandlers();
searchField.Remove(m_CancelButton);
}
void OnSearchFieldReady(GeometryChangedEvent evt)
{
searchField.UnregisterCallback<GeometryChangedEvent>(OnSearchFieldReady);
Dispatcher.On(SearchEvent.SearchTextChanged, OnSearchTextChanged);
Dispatcher.On(SearchEvent.SearchContextChanged, OnSearchContextChanged);
Dispatcher.On(SearchEvent.RefreshBuilder, OnQueryBuilderStateChanged);
Dispatcher.On(SearchEvent.RefreshContent, OnRefreshContent);
RegisterCallback<KeyDownEvent>(OnSearchToolbarKeyDown);
searchField.RegisterCallback<KeyDownEvent>(OnSearchFieldKeyDown);
viewState.globalEventManager.RegisterGlobalEventHandler<KeyDownEvent>(OnGlobalKeyInput, int.MaxValue);
UpdateQueryErrors();
UpdateMultiline();
UpdateCancelButton();
}
private static bool IgnoreKey(IKeyboardEvent evt)
{
if (evt.keyCode == KeyCode.Escape || evt.keyCode == KeyCode.Tab || evt.keyCode == KeyCode.Return || evt.shiftKey || evt.ctrlKey)
return true;
if ((evt.modifiers & EventModifiers.FunctionKey) != 0 && (int)evt.keyCode >= 255)
return true;
return false;
}
private static bool IsLineBreak(IKeyboardEvent evt)
{
if ((evt.ctrlKey || evt.shiftKey) && (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter))
return true;
return false;
}
private bool OnGlobalKeyInput(KeyDownEvent evt)
{
if (Contains((VisualElement)evt.target))
return false;
if (IgnoreKey(evt))
return false;
var te = textElement;
if (te == null || te.editingManipulator == null)
return false;
if (te is not Focusable tef)
return false;
te.selection.selectAllOnFocus = false;
te.focusController.DoFocusChange(tef);
te.editingManipulator.HandleEventBubbleUp(evt);
return evt.isPropagationStopped;
}
private void OnSearchToolbarKeyDown(KeyDownEvent evt)
{
if (supportsMultiline && IsLineBreak(evt))
{
var currentCursor = textField.cursorIndex;
searchField.value = searchField.value.Insert(currentCursor, "\n");
UpdateInternalTextData();
selectingUtilities.MoveRight();
evt.StopPropagation();
}
}
private void OnSearchFieldKeyDown(KeyDownEvent evt)
{
if (m_UndoManager.HandleEvent(evt, out var undoText, out var cursorPos, out _))
{
UpdateSearchText(undoText, cursorPos);
evt.StopImmediatePropagation();
}
}
private void UpdateSearchText(string undoText, int cursorPos)
{
m_ViewModel.SetSearchText(undoText, TextCursorPlacement.Default, cursorPos);
}
private void OnSearchTextChanged(ISearchEvent evt)
{
if (evt.sourceViewState != viewState)
return;
var moveCursor = evt.GetArgument<TextCursorPlacement>(2);
var cursorInsertIndex = evt.GetArgument<int>(3);
if (evt.GetArgument<TextCursorPlacement>(2) != TextCursorPlacement.None)
{
m_SearchTextInput?.SetValueWithoutNotify(evt.GetArgument<string>(1));
MoveCursor(moveCursor, cursorInsertIndex);
UpdatePlaceholders();
UpdateQueryErrors();
UpdateMultiline();
}
UpdateCancelButton();
}
private void OnSearchContextChanged(ISearchEvent evt)
{
if (evt.sourceViewState != viewState)
return;
CreateSearchField(this);
UpdatePlaceholders();
FocusSearchField();
UpdateCancelButton();
}
private void OnQueryBuilderStateChanged(ISearchEvent evt)
{
if (evt.sourceViewState != viewState)
return;
ToggleQueryBuilder();
}
public void ToggleQueryBuilder()
{
CreateSearchField(this);
FocusSearchField(FocusType.MoveEnd);
}
void OnRefreshContent(ISearchEvent evt)
{
if (evt.sourceViewState != viewState)
return;
UpdateQueryErrors();
}
private void SaveUndoManager()
{
if (m_ViewModel is not ISearchWindow)
return;
var time = EditorApplication.timeSinceStartup;
m_UndoManager.Save(time, context.searchText, textField);
Utils.CallDelayed(SaveUndoManager, 2.0d);
}
public void MoveCursor(TextCursorPlacement moveCursor, int cursorInsertPosition)
{
if (cursorInsertPosition >= 0)
{
textField.selectIndex = textField.cursorIndex = cursorInsertPosition;
}
else
{
if (textField.textSelection is not TextElement te)
return;
if (selectingUtilities == null)
return;
UpdateInternalTextData();
switch (moveCursor)
{
case TextCursorPlacement.MoveLineEnd: selectingUtilities.MoveLineEnd(); break;
case TextCursorPlacement.MoveLineStart: selectingUtilities.MoveLineStart(); break;
case TextCursorPlacement.MoveToEndOfPreviousWord: selectingUtilities.MoveToEndOfPreviousWord(); break;
case TextCursorPlacement.MoveToStartOfNextWord: selectingUtilities.MoveToStartOfNextWord(); break;
case TextCursorPlacement.MoveWordLeft: selectingUtilities.MoveWordLeft(); break;
case TextCursorPlacement.MoveWordRight: selectingUtilities.MoveWordRight(); break;
case TextCursorPlacement.MoveAutoComplete: MoveAutoComplete(textField, selectingUtilities); break;
}
}
}
static void MoveAutoComplete(TextField te, TextSelectingUtilities selectingUtilities)
{
while (te.cursorIndex < te.text.Length && !char.IsWhiteSpace(te.text[te.cursorIndex]))
selectingUtilities.MoveRight();
// If there is a space at the end of the text, move through it.
if (te.cursorIndex == te.text.Length - 1 && char.IsWhiteSpace(te.text[te.cursorIndex]))
selectingUtilities.MoveRight();
}
void UpdateQueryErrors()
{
m_UpdateQueryErrorScheduledItem?.Pause();
foreach (var visualMessage in m_VisualMessages)
{
visualMessage.RemoveFromHierarchy();
}
m_VisualMessages.Clear();
m_UpdateQueryErrorScheduledItem = this.schedule.Execute(DrawQueryErrors).Every(100).StartingIn(100);
}
// Only draw errors when you are done typing, to prevent cases where
// the cursor moved because of changes but we did not clear the errors yet.
private void DrawQueryErrors()
{
if (context.searchInProgress)
return;
if (m_UpdateQueryErrorScheduledItem != null && m_UpdateQueryErrorScheduledItem.isActive)
m_UpdateQueryErrorScheduledItem.Pause();
if (m_ViewModel.results == null || (!context.options.HasAny(SearchFlags.ShowErrorsWithResults) && m_ViewModel.results.Count > 0))
return;
List<SearchQueryError> errors;
if (m_ViewModel.currentGroup == (m_ViewModel as IGroup)?.id)
errors = m_ViewModel.GetAllVisibleErrors().ToList();
else
errors = context.GetErrorsByProvider(m_ViewModel.currentGroup).ToList();
if (errors.Count == 0 || context.markers?.Length > 0)
return;
errors.Sort(SearchQueryError.Compare);
DrawQueryErrors(errors);
}
private void DrawQueryErrors(IEnumerable<SearchQueryError> errors)
{
var alreadyShownErrors = new List<SearchQueryError>();
UpdateInternalTextData();
foreach (var searchQueryError in errors)
{
var queryErrorStart = searchQueryError.index;
// Do not stack errors on top of each other
if (alreadyShownErrors.Any(e => e.Overlaps(searchQueryError)))
continue;
alreadyShownErrors.Add(searchQueryError);
if (searchQueryError.type == SearchQueryErrorType.Error)
{
DrawError(
queryErrorStart,
searchQueryError.length,
searchQueryError.reason);
}
else
{
DrawWarning(
queryErrorStart,
searchQueryError.length,
searchQueryError.reason);
}
}
}
void DrawError(int startIndex, int length, in string reason)
{
DrawMessage(startIndex, length, reason, Color.red);
}
void DrawWarning(int startIndex, int length, in string reason)
{
DrawMessage(startIndex, length, reason, Color.yellow);
}
void DrawMessage(int startIndex, int length, in string message, in Color color)
{
var position = GetVisualMessagePosition(startIndex, startIndex + length);
var msgElement = new VisualMessage(startIndex, startIndex + length, message, color, position);
m_VisualMessages.Add(msgElement);
textField.Add(msgElement);
msgElement.MarkDirtyRepaint();
if (!CanShowVisualMessage(msgElement, textField))
msgElement.visible = false;
}
bool CanShowVisualMessage(VisualMessage visualMessage, TextField te)
{
// Do not show error if the cursor is inside the error itself, or if the error intersect with
// the current token
if (te.cursorIndex >= visualMessage.startIndex && te.cursorIndex <= visualMessage.endIndex)
return false;
SearchPropositionOptions.GetTokenBoundariesAtCursorPosition(context.searchText, te.cursorIndex, out var tokenStartPos, out var tokenEndPos);
if (visualMessage.startIndex >= tokenStartPos && visualMessage.startIndex <= tokenEndPos)
return false;
if (visualMessage.endIndex >= tokenStartPos && visualMessage.endIndex <= tokenEndPos)
return false;
return true;
}
Rect GetVisualMessagePosition(int startIndex, int endIndex)
{
var diff = textElement.worldBound.position - textField.worldBound.position;
var start = textElement.uitkTextHandle.GetCursorPositionFromStringIndexUsingLineHeight(startIndex);
var end = textElement.uitkTextHandle.GetCursorPositionFromStringIndexUsingLineHeight(endIndex);
start += diff;
end += diff;
return new Rect(start.x, start.y - 5f, end.x - start.x, 10f);
}
Rect GetVisualMessagePosition(VisualMessage visualMessage)
{
return GetVisualMessagePosition(visualMessage.startIndex, visualMessage.endIndex);
}
void OnCursorChanged()
{
foreach (var visualMessage in m_VisualMessages)
{
visualMessage.visible = CanShowVisualMessage(visualMessage, textField);
visualMessage.UpdatePosition(GetVisualMessagePosition(visualMessage));
}
}
void ClearOnCursorChangedHandlers()
{
if (selectingUtilities != null)
{
selectingUtilities.OnCursorIndexChange -= OnCursorChanged;
selectingUtilities.OnSelectIndexChange -= OnCursorChanged;
}
}
void UpdateMultiline()
{
if (textField == null)
return;
var hasLineBreak = supportsMultiline && searchField.value.Contains('\n') || searchField.value.Contains('\r') || searchField.value.Contains("\r\n");
textField.multiline = hasLineBreak;
searchField.EnableInClassList(searchFieldMultilineClassName, hasLineBreak);
}
void OnCancelButtonClick()
{
var cancelValue = viewState.isPicker ? viewState.initialQuery : string.Empty;
m_SearchTextInput.value = cancelValue;
UpdateCancelButton();
}
void UpdateCancelButton()
{
if (viewState.queryBuilderEnabled && queryBuilder == null)
return;
// Override the behavior of the ToolbarSearchField that only removes the X if the field is empty.
var hideCancelBtn = string.IsNullOrEmpty(queryString);
if (m_ViewModel.IsPicker())
{
var simplifiedQueryString = queryString;
var simplifiedInitialQuery = viewState.initialQuery;
if (viewState.queryBuilderEnabled)
{
simplifiedQueryString = Utils.Simplify(queryString).ToLower();
simplifiedInitialQuery = Utils.Simplify(viewState.initialQuery.Trim()).ToLower();
}
hideCancelBtn = string.CompareOrdinal(simplifiedQueryString, simplifiedInitialQuery) == 0;
}
m_CancelButton.EnableInClassList(SearchFieldBase<TextField, string>.cancelButtonOffVariantUssClassName, hideCancelBtn);
}
internal void UpdateInternalTextData()
{
textElement.uitkTextHandle.ComputeSettingsAndUpdate();
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchField.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchField.cs",
"repo_id": "UnityCsReference",
"token_count": 12446
} | 451 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Linq;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.Search
{
abstract class SearchViewItem : SearchElement
{
protected SearchItem m_BindedItem;
protected readonly Label m_Label;
protected readonly Image m_Thumbnail;
protected readonly Button m_FavoriteButton;
private bool m_InitiateDrag = false;
private Vector3 m_InitiateDragPosition;
private Action m_FetchPreviewOff = null;
private SearchPreviewKey m_PreviewKey;
private IVisualElementScheduledItem m_PreviewRefreshCallback;
private const int k_PreviewFetchCounter = 5;
static readonly string searchFavoriteButtonTooltip = L10n.Tr("Mark as Favorite");
static readonly string searchFavoriteOnButtonTooltip = L10n.Tr("Remove as Favorite");
public static readonly string searchFavoriteButtonClassName = "search-view-item".WithUssElement("favorite-button");
public SearchViewItem(string name, ISearchView viewModel, params string[] classNames)
: base(name, viewModel, classNames)
{
m_Label = new Label() { name = "SearchViewItemLabel" };
m_Thumbnail = new Image() { name = "SearchViewItemThumbnail" };
m_FavoriteButton = CreateButton("SearchFavoriteButton", searchFavoriteButtonTooltip, OnFavoriteButtonClicked, baseIconButtonClassName, searchFavoriteButtonClassName);
RegisterCallback<ClickEvent>(OnDoubleClick);
RegisterCallback<ContextClickEvent>(OnItemContextualClicked);
RegisterCallback<PointerDownEvent>(OnItemPointerDown);
RegisterCallback<PointerUpEvent>(OnItemPointerUp);
RegisterCallback<DragExitedEvent>(OnDragExited);
}
protected override void OnAttachToPanel(AttachToPanelEvent evt)
{
base.OnAttachToPanel(evt);
OnAll(SearchEvent.ItemFavoriteStateChanged, OnFavoriteStateChanged);
}
protected override void OnDetachFromPanel(DetachFromPanelEvent evt)
{
Off(SearchEvent.ItemFavoriteStateChanged, OnFavoriteStateChanged);
base.OnDetachFromPanel(evt);
}
private void OnFavoriteStateChanged(ISearchEvent evt)
{
if (m_BindedItem == null)
return;
var id = string.Empty;
if (evt.argumentCount == 1)
id = (string)evt.GetArgument(0);
else
return;
if (id.Equals(m_BindedItem.id, StringComparison.Ordinal))
UpdateFavoriteImage();
}
public virtual void Destroy()
{
CancelFetchPreview();
UnregisterCallback<ClickEvent>(OnDoubleClick);
UnregisterCallback<ContextClickEvent>(OnItemContextualClicked);
UnregisterCallback<PointerDownEvent>(OnItemPointerDown);
UnregisterCallback<PointerMoveEvent>(OnItemPointerMove);
UnregisterCallback<PointerUpEvent>(OnItemPointerUp);
UnregisterCallback<DragExitedEvent>(OnDragExited);
UnregisterCallback<PointerLeaveEvent>(OnItemPointerLeave);
}
private void CancelFetchPreview()
{
m_ViewModel.previewManager.CancelFetch(m_PreviewKey);
m_PreviewKey = default;
if (m_FetchPreviewOff != null)
{
m_FetchPreviewOff?.Invoke();
m_FetchPreviewOff = null;
}
}
public virtual FetchPreviewOptions GetPreviewOptions()
{
return FetchPreviewOptions.Normal | FetchPreviewOptions.Preview2D;
}
public virtual bool ShouldFetchPreview()
{
return SearchSettings.fetchPreview && !m_ViewModel.previewManager.HasPreview(m_PreviewKey);
}
public virtual void Bind(in SearchItem item)
{
name = item.id;
m_BindedItem = item;
m_Label.text = item.GetLabel(context);
UpdatePreview();
// Last tries at getting the preview. (For the AssetStoreProvider).
// TODO FetchItemProperties(DOTSE - 1994): All the fetching of async properties should be consolidated in the ResultView/SearchView.
var counter = 0;
m_PreviewRefreshCallback = m_Thumbnail.schedule.Execute(() =>
{
if (m_FetchPreviewOff == null)
UpdatePreview();
});
m_PreviewRefreshCallback.StartingIn(500).Every(500).Until(() =>
{
counter++;
return m_ViewModel.previewManager.HasPreview(m_PreviewKey) || counter >= k_PreviewFetchCounter;
});
UpdateFavoriteImage();
}
public virtual void Unbind()
{
CancelFetchPreview();
m_Label.text = null;
m_Thumbnail.image = null;
m_FavoriteButton.pseudoStates &= ~PseudoStates.Active;
if (m_BindedItem != null)
{
m_BindedItem.preview = null;
m_BindedItem.thumbnail = null;
m_BindedItem = null;
}
if (m_PreviewRefreshCallback?.isActive == true)
m_PreviewRefreshCallback.Pause();
}
private bool IsSizeValid(out Vector2 size)
{
size = default;
if (m_Thumbnail == null)
return false;
size.x = m_Thumbnail.resolvedStyle.width;
if (float.IsNaN(size.x) || size.x <= 0)
return false;
size.y = m_Thumbnail.resolvedStyle.height;
if (float.IsNaN(size.y) || size.y <= 0)
return false;
return true;
}
private bool GetExistingPreview()
{
if (m_ViewModel.previewManager.HasPreview(m_PreviewKey))
{
var preview = m_ViewModel.previewManager.FetchPreview(m_PreviewKey);
if (preview.valid)
{
m_Thumbnail.image = preview.texture;
m_BindedItem.preview = preview.texture;
return true;
}
}
return false;
}
private void UpdatePreview()
{
if (GetExistingPreview())
return;
if (ShouldFetchPreview())
{
m_FetchPreviewOff?.Invoke();
AsyncFetchPreview();
}
var tex = m_BindedItem.GetThumbnail(context, cacheThumbnail: false);
m_Thumbnail.image = tex;
m_BindedItem.thumbnail = tex;
}
private void AsyncFetchPreview()
{
if (m_BindedItem == null)
return;
if (IsSizeValid(out var previewSize))
{
m_PreviewKey = new SearchPreviewKey(m_BindedItem, GetPreviewOptions(), previewSize);
if (GetExistingPreview())
return;
m_FetchPreviewOff = m_ViewModel.previewManager.FetchPreview(m_BindedItem, context, m_PreviewKey, FetchPreview, OnPreviewReady);
}
else
{
m_FetchPreviewOff = Utils.CallDelayed(AsyncFetchPreview, 0.01d); // To make sure the style is resolved.
}
}
private void FetchPreview(SearchItem item, SearchContext context, FetchPreviewOptions options, Vector2 size, OnPreviewReady onPreviewReady)
{
SearchPreview searchPreview;
if (item == null || m_BindedItem == null)
{
searchPreview = SearchPreview.invalid;
}
else
{
var fetchedPreview = m_BindedItem.GetPreview(context, size, options, cacheThumbnail: false);
searchPreview = new SearchPreview(m_PreviewKey, fetchedPreview);
}
onPreviewReady?.Invoke(item, context, searchPreview);
}
private void OnPreviewReady(SearchItem item, SearchContext context, SearchPreview preview)
{
if (preview.valid && m_BindedItem != null && m_Thumbnail != null)
{
var fetchedPreview = preview.texture;
if (fetchedPreview != null && fetchedPreview.width > 0 && fetchedPreview.height > 0)
{
m_Thumbnail.image = fetchedPreview;
m_BindedItem.preview = fetchedPreview;
}
}
if (m_Thumbnail != null && m_BindedItem != null && m_Thumbnail.image == null)
{
var tex = m_BindedItem.GetThumbnail(context, cacheThumbnail: false);
m_Thumbnail.image = tex;
m_BindedItem.thumbnail = tex;
}
m_FetchPreviewOff = null;
}
private void OnDoubleClick(ClickEvent evt)
{
if (evt.clickCount != 2)
return;
m_ViewModel.ExecuteAction(null, new[] { m_BindedItem }, !SearchSettings.keepOpen);
}
private void OnItemContextualClicked(ContextClickEvent evt)
{
m_ViewModel.ShowItemContextualMenu(m_BindedItem, default);
}
private void OnItemPointerDown(PointerDownEvent evt)
{
// dragging is initiated only by left mouse clicks
if (evt.button != (int)MouseButton.LeftMouse)
return;
m_InitiateDrag = !m_ViewModel.IsPicker() && m_BindedItem.provider.startDrag != null;
m_InitiateDragPosition = evt.localPosition;
UnregisterCallback<PointerMoveEvent>(OnItemPointerMove);
RegisterCallback<PointerMoveEvent>(OnItemPointerMove);
UnregisterCallback<PointerLeaveEvent>(OnItemPointerLeave);
RegisterCallback<PointerLeaveEvent>(OnItemPointerLeave);
}
void OnItemPointerLeave(PointerLeaveEvent evt)
{
// If we enter here, it means the mouse left the element before any mouse
// move, so the item jumped around to be repositioned in the window.
// This will cause an issue with drag and drop
m_InitiateDrag = false;
UnregisterCallback<PointerLeaveEvent>(OnItemPointerLeave);
}
private void OnItemPointerMove(PointerMoveEvent evt)
{
if (!m_InitiateDrag)
return;
if ((evt.localPosition - m_InitiateDragPosition).sqrMagnitude < 5f)
return;
UnregisterCallback<PointerMoveEvent>(OnItemPointerMove);
UnregisterCallback<PointerLeaveEvent>(OnItemPointerLeave);
DragAndDrop.PrepareStartDrag();
m_BindedItem.provider.startDrag(m_BindedItem, context);
m_InitiateDrag = false;
}
private void OnDragExited(DragExitedEvent evt) => ResetDrag();
private void OnItemPointerUp(PointerUpEvent evt) => ResetDrag();
private void OnFavoriteButtonClicked()
{
if (SearchSettings.searchItemFavorites.Contains(m_BindedItem.id))
SearchSettings.RemoveItemFavorite(m_BindedItem);
else
SearchSettings.AddItemFavorite(m_BindedItem);
UpdateFavoriteImage();
}
protected void UpdateFavoriteImage()
{
if (SearchSettings.searchItemFavorites.Contains(m_BindedItem.id))
{
m_FavoriteButton.tooltip = searchFavoriteOnButtonTooltip;
m_FavoriteButton.pseudoStates |= PseudoStates.Active;
}
else
{
m_FavoriteButton.tooltip = searchFavoriteButtonTooltip;
m_FavoriteButton.pseudoStates &= ~PseudoStates.Active;
}
}
protected void OnActionDropdownClicked()
{
m_ViewModel.ShowItemContextualMenu(m_BindedItem, default);
}
private void ResetDrag()
{
m_InitiateDrag = false;
UnregisterCallback<PointerMoveEvent>(OnItemPointerMove);
UnregisterCallback<PointerLeaveEvent>(OnItemPointerLeave);
}
}
}
| UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchViewItem.cs/0 | {
"file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchViewItem.cs",
"repo_id": "UnityCsReference",
"token_count": 5789
} | 452 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
//#define ENABLE_SCENE_PREVIEW_OVERLAY
using System;
using System.Collections.Generic;
using UnityEditor.Experimental;
using UnityEditor.Overlays;
using UnityEditor.SceneTemplate;
using UnityEditor.Toolbars;
using UnityEngine;
using UnityEngine.Search;
namespace UnityEditor.Search
{
static class ScenePicker
{
[MenuItem("Window/Search/Scene", priority = 1269, secondaryPriority = 1)]
internal static void OpenScenePicker()
{
var searchContext = SearchService.CreateContext(CreateOpenSceneProviders(), string.Empty);
var state = SearchViewState.CreatePickerState(L10n.Tr("Scenes"), searchContext, OnSceneSelected);
state.excludeClearItem = true;
SearchService.ShowPicker(state);
}
static IEnumerable<SearchProvider> CreateOpenSceneProviders()
{
yield return new SearchProvider("stemplates", L10n.Tr("Templates"), FetchTemplates)
{
priority = 2998,
fetchPreview = FetchTemplatePreview,
fetchThumbnail = FetchTemplateThumbnail
};
yield return new SearchProvider("sassets", L10n.Tr("Scenes"), FetchScenes)
{
priority = 2999,
fetchLabel = FetchSceneLabel,
fetchDescription = FetchSceneDescription,
fetchPreview = FetchScenePreview,
fetchThumbnail = FetchSceneThumbnail
};
}
static Texture2D FetchTemplateThumbnail(SearchItem item, SearchContext context)
{
if (item.thumbnail)
return item.thumbnail;
var sceneTemplateInfo = item.data as SceneTemplateInfo;
if (sceneTemplateInfo == null)
return null;
if (sceneTemplateInfo.thumbnail)
return (item.thumbnail = sceneTemplateInfo.thumbnail);
if (!string.IsNullOrEmpty(sceneTemplateInfo.thumbnailPath))
item.thumbnail = sceneTemplateInfo.thumbnail = EditorResources.Load<Texture2D>(sceneTemplateInfo.thumbnailPath);
return item.thumbnail;
}
static Texture2D FetchTemplatePreview(SearchItem item, SearchContext context, Vector2 size, FetchPreviewOptions options)
{
var sceneTemplateInfo = item.data as SceneTemplateInfo;
if (sceneTemplateInfo == null)
return null;
return sceneTemplateInfo.sceneTemplate?.preview;
}
static IEnumerable<SearchItem> FetchTemplates(SearchContext context, SearchProvider provider)
{
long score = 0;
var templates = SceneTemplateUtils.GetSceneTemplateInfos();
List<int> matches = new List<int>();
foreach (var t in templates)
{
var id = t.sceneTemplate?.GetInstanceID().ToString() ?? t.name;
if (string.IsNullOrEmpty(context.searchQuery) || FuzzySearch.FuzzyMatch(context.searchQuery, $"{t.name} {t.description}", ref score, matches))
yield return provider.CreateItem(context, id, ~(int)score, t.name, t.description, t.thumbnail, t);
score++;
}
}
static string FetchSceneDescription(SearchItem item, SearchContext context)
{
if (TryGetScenePath(item, out var scenePath))
return scenePath;
return item.id;
}
static string FetchSceneLabel(SearchItem item, SearchContext context)
{
if (TryGetScenePath(item, out var scenePath))
return System.IO.Path.GetFileNameWithoutExtension(scenePath);
return item.id;
}
static Texture2D FetchSceneThumbnail(SearchItem item, SearchContext context)
{
if (!TryGetScenePath(item, out var scenePath))
return null;
return AssetDatabase.GetCachedIcon(scenePath) as Texture2D;
}
static Texture2D FetchScenePreview(SearchItem item, SearchContext context, Vector2 size, FetchPreviewOptions options)
{
if (!TryGetScenePath(item, out var scenePath))
return null;
var dirPath = System.IO.Path.GetDirectoryName(scenePath);
var filename = System.IO.Path.GetFileNameWithoutExtension(scenePath);
var previewScenePath = $"{dirPath}/{filename}.preview.png";
if (!System.IO.File.Exists(previewScenePath))
return null;
return AssetDatabase.LoadAssetAtPath<Texture2D>(previewScenePath);
}
static IEnumerable<SearchItem> FetchScenes(SearchContext context, SearchProvider provider)
{
using (var findContext = SearchService.CreateContext("find", $"(*.unity) {context.searchQuery}"))
using (var request = SearchService.Request(findContext))
{
foreach (var r in request)
{
if (r == null)
yield return null;
else
{
r.provider = provider;
r.data = null;
yield return r;
}
}
}
}
static bool TryGetScenePath(SearchItem item, out string path)
{
path = item.data as string;
if (!string.IsNullOrEmpty(path))
return true;
if (!GlobalObjectId.TryParse(item.id, out var gid))
return false;
var scenePath = AssetDatabase.GUIDToAssetPath(gid.assetGUID);
if (string.IsNullOrEmpty(scenePath))
return false;
item.data = path = scenePath;
return true;
}
static void OnSceneSelected(SearchItem item, bool canceled)
{
if (canceled)
return;
if (item.data is SceneTemplateInfo sti)
{
const bool additive = false;
sti.onCreateCallback?.Invoke(additive);
}
else
{
if (!TryGetScenePath(item, out var scenePath))
throw new Exception($"Failed to parse scene id of {item}");
EditorApplication.OpenFileGeneric(scenePath);
}
}
}
sealed class ScenePickerScreenshotToolbarOverlay : ToolbarOverlay
{
const string k_Id = "unity-scene-screenshot-toolbar";
const string k_ElementName = "Tools/Screenshot";
public ScenePickerScreenshotToolbarOverlay() : base(k_ElementName) { }
sealed class SceneScreenshotToolsStrip : EditorToolbarButton
{
const int resWidth = 256;
const int resHeight = 256;
public SceneScreenshotToolsStrip() : base(TakeScenePreview)
{
name = "ScenePreviewScreenshot";
icon = EditorGUIUtility.LoadIcon("CameraPreview");
tooltip = L10n.Tr("Take scene preview screenshot");
}
static string GetScenePreviewImagePath()
{
var scene = UnityEngine.SceneManagement.SceneManager.GetActiveScene();
if (scene == null)
return null;
string scenePath = scene.path;
if (string.IsNullOrEmpty(scenePath))
return null;
var dirPath = System.IO.Path.GetDirectoryName(scenePath);
var sceneFilename = System.IO.Path.GetFileNameWithoutExtension(scenePath);
return $"{dirPath}/{sceneFilename}.preview.png";
}
static void TakeScenePreview()
{
var previewScenePath = GetScenePreviewImagePath();
if (string.IsNullOrEmpty(previewScenePath))
return;
var rt = new RenderTexture(resWidth, resHeight, 32);
var camera = SceneView.lastActiveSceneView.camera;
var screenShot = new Texture2D(resWidth, resHeight, TextureFormat.RGBA32, true);
camera.targetTexture = rt;
camera.Render();
RenderTexture.active = rt;
screenShot.ReadPixels(new Rect(0, 0, resWidth, resHeight), 0, 0);
camera.targetTexture = null;
RenderTexture.active = null;
var bytes = screenShot.EncodeToPNG();
System.IO.File.WriteAllBytes(previewScenePath, bytes);
AssetDatabase.ImportAsset(previewScenePath);
UnityEngine.Object.DestroyImmediate(rt);
}
}
}
}
| UnityCsReference/Modules/SceneTemplateEditor/ScenePicker.cs/0 | {
"file_path": "UnityCsReference/Modules/SceneTemplateEditor/ScenePicker.cs",
"repo_id": "UnityCsReference",
"token_count": 4121
} | 453 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEditor.Overlays;
using UnityEditor.Rendering;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.UIElements;
namespace UnityEditor
{
[Overlay(typeof(SceneView), k_OverlayID, "Lighting Visualization", priority = (int)OverlayPriority.LightingVisualization, defaultDockZone = DockZone.RightColumn)]
[Icon("Icons/LightingVisualization.png")]
class SceneViewLighting : Overlay, ITransientOverlay
{
internal static class Styles
{
internal const string k_UnityHiddenClass = "unity-pbr-validation-hidden";
internal const string k_UnityBaseFieldClass = "unity-base-field";
internal const string k_SliderRowClass = "unity-pbr-slider-row";
internal const string k_SliderClass = "unity-pbr-slider";
internal const string k_SliderFloatFieldClass = "unity-pbr-slider-float-field";
internal const string k_SwatchColorContent = "color-content";
internal const string k_ToggleClass = "unity-lighting-visualization-toggle";
internal const string k_ToggleLabelClass = "unity-lighting-visualization-toggle-label";
}
const string k_OverlayID = "Scene View/Light Settings";
bool m_ShouldDisplay;
public bool visible => m_ShouldDisplay;
SceneView m_SceneView;
SceneView sceneView => m_SceneView;
VisualElement m_ContentRoot;
// Interactive preview toggle
VisualElement m_InteractiveBakingContent;
// Draw lightmap resolution
VisualElement m_LightmapResolutionContent;
// Draw backface highlights
VisualElement m_BackfaceHighlightsContent;
// Light exposure
VisualElement m_LightExposureContent;
Slider m_ExposureSlider;
FloatField m_ExposureField;
const float k_ExposureSliderAbsoluteMax = 23.0f;
float m_ExposureMax = 16f;
static Texture2D s_ExposureTexture, s_EmptyExposureTexture;
public SceneViewLighting()
{
collapsedChanged += OnCollapsedChanged;
}
public override void OnCreated()
{
if (!(containerWindow is SceneView view))
throw new Exception("Lighting Visualization Overlay is only valid in the Scene View");
m_ShouldDisplay = false;
m_SceneView = view;
m_SceneView.onCameraModeChanged += OnCameraModeChanged;
m_SceneView.debugDrawModesUseInteractiveLightBakingDataChanged += OnUseInteractiveLightBakingDataChanged;
Lightmapping.bakeStarted += OnBakeStarted;
Lightmapping.bakeCompleted += OnBakeCompleted;
Lightmapping.bakeCancelled += OnBakeCompleted;
}
public override void OnWillBeDestroyed()
{
m_SceneView.onCameraModeChanged -= OnCameraModeChanged;
m_SceneView.debugDrawModesUseInteractiveLightBakingDataChanged -= OnUseInteractiveLightBakingDataChanged;
Lightmapping.bakeStarted -= OnBakeStarted;
Lightmapping.bakeCompleted -= OnBakeCompleted;
Lightmapping.bakeCancelled -= OnBakeCompleted;
}
void OnCollapsedChanged(bool collapsed)
{
if (collapsed)
SceneView.duringSceneGui -= UpdateGizmoExposure;
else
SceneView.duringSceneGui += UpdateGizmoExposure;
}
public override VisualElement CreatePanelContent()
{
if (!(containerWindow is SceneView view))
return new Label("Lighting Visualization Overlay is only valid in the Scene View");
m_SceneView = view;
m_ContentRoot = new VisualElement();
m_ContentRoot.Add(m_InteractiveBakingContent = CreateInteractiveBakingContent());
m_ContentRoot.Add(m_LightmapResolutionContent = CreateLightmapResolutionContent());
m_ContentRoot.Add(m_BackfaceHighlightsContent = CreateBackfaceHighlightsContent());
m_ContentRoot.Add(m_LightExposureContent = CreateLightExposureContent());
OnCameraModeChanged(sceneView.cameraMode);
return m_ContentRoot;
}
void OnCameraModeChanged(SceneView.CameraMode mode)
{
// If the rootVisualElement hasn't yet been created, early out
if (m_ContentRoot == null)
CreatePanelContent();
m_InteractiveBakingContent.EnableInClassList(Styles.k_UnityHiddenClass, !sceneView.currentDrawModeMayUseInteractiveLightBakingData);
m_LightmapResolutionContent.EnableInClassList(Styles.k_UnityHiddenClass, !sceneView.showLightmapResolutionToggle);
m_BackfaceHighlightsContent.EnableInClassList(Styles.k_UnityHiddenClass, !sceneView.showBackfaceHighlightsToggle);
m_LightExposureContent.EnableInClassList(Styles.k_UnityHiddenClass, !sceneView.showExposureSettings);
if (sceneView.showLightingVisualizationPanel)
{
m_SceneView.SetOverlayVisible(k_OverlayID, true);
m_ShouldDisplay = true;
}
else
{
m_ShouldDisplay = false;
}
}
void OnUseInteractiveLightBakingDataChanged(bool useInteractiveLightBakingDataChanged)
{
m_InteractiveBakingContent?.Q<EnumField>()?.SetValueWithoutNotify(useInteractiveLightBakingDataChanged ? LightingDataSource.Preview : LightingDataSource.Baked);
m_InteractiveBakingContent?.Q<FloatField>()?.EnableInClassList(Styles.k_UnityHiddenClass, !useInteractiveLightBakingDataChanged);
}
void OnBakeStarted()
{
m_InteractiveBakingContent?.Q<EnumField>()?.SetEnabled(false);
m_InteractiveBakingContent?.Q<FloatField>()?.SetEnabled(false);
}
void OnBakeCompleted()
{
m_InteractiveBakingContent?.Q<EnumField>()?.SetEnabled(true);
m_InteractiveBakingContent?.Q<FloatField>()?.SetEnabled(true);
}
enum LightingDataSource
{
Baked,
Preview
}
VisualElement CreateInteractiveBakingContent()
{
var useInteractiveLightBakingDataChanged = SceneView.lastActiveSceneView?.debugDrawModesUseInteractiveLightBakingData ?? false;
var root = new VisualElement();
var dropdown = new EnumField("Lighting Data", LightingDataSource.Baked);
dropdown.tooltip = "Select which lighting data is shown in Debug Draw Modes.\n\nBaked displays the most recent lighting data generated from the Lighting Window.\n\nPreview displays an interactive preview which updates in relation to Scene changes.";
dropdown.RegisterValueChangedCallback((evt) =>
{
bool isInteractive = (LightingDataSource)evt.newValue == LightingDataSource.Preview;
SceneView.lastActiveSceneView.debugDrawModesUseInteractiveLightBakingData = isInteractive;
});
dropdown.labelElement.AddToClassList(Styles.k_ToggleLabelClass);
dropdown.visualInput.AddToClassList(Styles.k_SliderFloatFieldClass);
dropdown.SetEnabled(!Lightmapping.isRunning);
dropdown.SetValueWithoutNotify(useInteractiveLightBakingDataChanged ? LightingDataSource.Preview : LightingDataSource.Baked);
const float minLightmapResolutionScale = 0.001f;
var lightmapScaleField = new FloatField(" Lightmap Scale");
lightmapScaleField.labelElement.AddToClassList(Styles.k_ToggleLabelClass);
lightmapScaleField.visualInput.AddToClassList(Styles.k_SliderFloatFieldClass);
lightmapScaleField.tooltip = "Controls lightmap resolution by multiplying the value with the resolution chosen in the lighting window";
lightmapScaleField.isDelayed = true;
lightmapScaleField.RegisterValueChangedCallback((evt) =>
{
float scale = evt.newValue;
if (scale < minLightmapResolutionScale)
{
scale = minLightmapResolutionScale;
lightmapScaleField.SetValueWithoutNotify(scale);
}
InteractiveLightBaking.lightmapResolutionScale = scale;
});
// Set default to the lightmap resolution from the lighting window
lightmapScaleField.SetValueWithoutNotify(InteractiveLightBaking.lightmapResolutionScale);
lightmapScaleField.EnableInClassList(Styles.k_UnityHiddenClass, !useInteractiveLightBakingDataChanged);
root.Add(dropdown);
root.Add(lightmapScaleField);
return root;
}
VisualElement CreateLightmapResolutionContent()
{
var showResolution = LightmapVisualization.showResolution;
var root = new VisualElement();
root.tooltip = "Draw lightmap texel density as an overlay in this Scene View Mode.";
var toggle = new Toggle { label = "Show Lightmap Resolution", name = "lightmap-resolution-toggle" };
toggle.labelElement.AddToClassList(Styles.k_ToggleLabelClass);
toggle.visualInput.AddToClassList(Styles.k_ToggleClass);
toggle.RegisterValueChangedCallback((ChangeEvent<bool> evt) => LightmapVisualization.showResolution = evt.newValue);
toggle.SetValueWithoutNotify(LightmapVisualization.showResolution);
root.Add(toggle);
return root;
}
VisualElement CreateBackfaceHighlightsContent()
{
var backfaceHighlights = SceneView.GetDrawBackfaceHighlights();
var root = new VisualElement();
root.tooltip = "Highlight back-facing geometry using debug colors.";
var toggle = new Toggle { label = "Highlight Back-Facing Geometry", name = "backface-highlights-toggle" };
toggle.labelElement.AddToClassList(Styles.k_ToggleLabelClass);
toggle.visualInput.AddToClassList(Styles.k_ToggleClass);
toggle.RegisterValueChangedCallback((ChangeEvent<bool> evt) => SceneView.SetDrawBackfaceHighlights(evt.newValue));
toggle.SetValueWithoutNotify(backfaceHighlights);
root.Add(toggle);
return root;
}
VisualElement CreateLightExposureContent()
{
var exposure = SceneView.s_DrawModeExposure;
var root = new VisualElement();
root.tooltip = "Adjust Lightmap Exposure";
root.AddToClassList(Styles.k_SliderRowClass);
var icon = new Image() { name = "exposure-label" };
m_ExposureSlider = new Slider(-m_ExposureMax, m_ExposureMax) { name = "exposure-slider" };
m_ExposureSlider.AddToClassList(Styles.k_SliderClass);
m_ExposureSlider.RegisterValueChangedCallback(SetBakedExposure);
m_ExposureSlider.SetValueWithoutNotify(exposure);
m_ExposureField = new FloatField() { name = "exposure-float-field" };
m_ExposureField.AddToClassList(Styles.k_SliderFloatFieldClass);
m_ExposureField.RegisterValueChangedCallback(SetBakedExposure);
m_ExposureField.SetValueWithoutNotify(exposure);
root.Add(icon);
root.Add(m_ExposureSlider);
root.Add(m_ExposureField);
return root;
}
void SetBakedExposure(ChangeEvent<float> evt)
{
var value = Mathf.Clamp(evt.newValue, -k_ExposureSliderAbsoluteMax, k_ExposureSliderAbsoluteMax);
// This will allow the user to set a new max value for the current session
if (Mathf.Abs(value) > m_ExposureMax)
{
m_ExposureMax = Mathf.Min(k_ExposureSliderAbsoluteMax, Mathf.Abs(value));
m_ExposureSlider.lowValue = -m_ExposureMax;
m_ExposureSlider.highValue = m_ExposureMax;
}
m_ExposureSlider.SetValueWithoutNotify(value);
if (evt.target != m_ExposureField || evt.newValue != 0)
m_ExposureField.SetValueWithoutNotify(value);
SceneView.s_DrawModeExposure.value = value;
}
void UpdateGizmoExposure(SceneView view)
{
if (m_SceneView != view)
return;
if (m_SceneView.showExposureSettings || m_SceneView.cameraMode.drawMode == DrawCameraMode.LitClustering)
{
if (s_ExposureTexture == null)
{
s_ExposureTexture = new Texture2D(1, 1, GraphicsFormat.R32G32_SFloat, TextureCreationFlags.None);
s_ExposureTexture.hideFlags = HideFlags.HideAndDontSave;
}
s_ExposureTexture.SetPixel(0, 0, new Color(Mathf.Pow(2.0f, SceneView.s_DrawModeExposure), 0.0f, 0.0f));
s_ExposureTexture.Apply();
Gizmos.exposure = s_ExposureTexture;
}
else
{
if (s_EmptyExposureTexture == null)
{
s_EmptyExposureTexture = new Texture2D(1, 1, GraphicsFormat.R32G32_SFloat, TextureCreationFlags.None);
s_EmptyExposureTexture.hideFlags = HideFlags.HideAndDontSave;
s_EmptyExposureTexture.SetPixel(0, 0, new Color(1.0f, 0.0f, 0.0f));
s_EmptyExposureTexture.Apply();
}
Gizmos.exposure = s_EmptyExposureTexture;
}
}
}
[Overlay(typeof(SceneView), k_OverlayID, "PBR Validation Settings", priority = (int)OverlayPriority.PBRValidation, defaultDockZone = DockZone.RightColumn)]
[Icon("Icons/Exposure.png")]
class SceneViewLightingPBRValidation : Overlay, ITransientOverlay
{
const string k_OverlayID = "Scene View/PBR Validation Settings";
bool m_ShouldDisplay;
public bool visible => m_ShouldDisplay;
SceneView m_SceneView;
SceneView sceneView => m_SceneView;
List<AlbedoSwatchInfo> m_AlbedoSwatchInfos;
AlbedoSwatchInfo m_SelectedAlbedoSwatch;
VisualElement m_ContentRoot;
// Validate albedo / metals
const float k_AlbedoHueToleranceMin = 0f;
const float k_AlbedoHueToleranceMax = .5f;
VisualElement m_AlbedoContent;
VisualElement m_AlbedoHueTolerance;
VisualElement m_AlbedoSaturationTolerance;
PopupField<AlbedoSwatchInfo> m_SelectedAlbedoPopup;
float m_AlbedoSwatchHueTolerance = .1f;
float m_AlbedoSwatchSaturationTolerance = .2f;
public SceneViewLightingPBRValidation()
{
CreateAlbedoSwatchData();
}
public override void OnCreated()
{
if (!(containerWindow is SceneView view))
throw new Exception("PBR Validation Overlay is only valid in the Scene View");
m_ShouldDisplay = false;
m_SceneView = view;
m_SceneView.onCameraModeChanged += OnCameraModeChanged;
}
public override void OnWillBeDestroyed()
{
m_SceneView.onCameraModeChanged -= OnCameraModeChanged;
}
public override VisualElement CreatePanelContent()
{
if (!(containerWindow is SceneView view))
return new Label("PBR Validation Overlay is only valid in the Scene View");
m_SceneView = view;
m_ContentRoot = new VisualElement();
m_ContentRoot.Add(m_AlbedoContent = CreateAlbedoContent());
OnCameraModeChanged(sceneView.cameraMode);
return m_ContentRoot;
}
void OnCameraModeChanged(SceneView.CameraMode mode)
{
// If the rootVisualElement hasn't yet been created, early out
if (m_ContentRoot == null)
CreatePanelContent();
bool showValidateAlbedo = mode.drawMode == DrawCameraMode.ValidateAlbedo;
bool showPanel = showValidateAlbedo || mode.drawMode == DrawCameraMode.ValidateMetalSpecular;
m_AlbedoContent.EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, !showPanel);
m_AlbedoContent.Q("Albedo").EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, !showValidateAlbedo);
m_ShouldDisplay = showPanel;
if (m_ShouldDisplay)
{
m_AlbedoContent.Q<HelpBox>()?.EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, PlayerSettings.colorSpace != ColorSpace.Gamma);
m_SceneView.SetOverlayVisible(k_OverlayID, true);
}
UpdateAlbedoMetalValidation();
}
VisualElement CreateAlbedoContent()
{
var root = new VisualElement() { name = "Albedo and Metals" };
var validateTrueMetals = new Toggle("Check Pure Metals");
validateTrueMetals.SetValueWithoutNotify(sceneView.validateTrueMetals);
validateTrueMetals.RegisterValueChangedCallback(ValidateTrueMetalsChanged);
validateTrueMetals.tooltip = "Check if albedo is black for materials with an average specular color above 0.45";
root.Add(validateTrueMetals);
var albedoSpecificContent = new VisualElement() { name = "Albedo" };
if (PlayerSettings.colorSpace == ColorSpace.Gamma)
albedoSpecificContent.Add(new HelpBox("Albedo Validation doesn't work when Color Space is set to gamma space",
HelpBoxMessageType.Warning));
m_SelectedAlbedoSwatch = m_AlbedoSwatchInfos[0];
m_SelectedAlbedoPopup = new PopupField<AlbedoSwatchInfo>("Luminance Validation", m_AlbedoSwatchInfos, m_SelectedAlbedoSwatch);
m_SelectedAlbedoPopup.tooltip = "Select default luminance validation or validate against a configured albedo swatch";
m_SelectedAlbedoPopup.formatListItemCallback = swatch => swatch.name;
m_SelectedAlbedoPopup.formatSelectedValueCallback = swatch => swatch.name;
m_SelectedAlbedoPopup.RegisterValueChangedCallback(SetSelectedAlbedoSwatch);
albedoSpecificContent.Add(m_SelectedAlbedoPopup);
albedoSpecificContent.Add(m_AlbedoContent = SceneViewLightingColors.CreateColorSwatch("magenta", null));
var hue = EditorGUIUtility.TrTextContent("Hue Tolerance:", "Check that the hue of the albedo value of a " +
"material is within the tolerance of the hue of the albedo swatch being validated against");
var sat = EditorGUIUtility.TrTextContent("Saturation Tolerance:", "Check that the saturation of the albedo " +
"value of a material is within the tolerance of the saturation of the albedo swatch being validated against");
m_AlbedoHueTolerance = CreateSliderWithField(hue, m_AlbedoSwatchHueTolerance, k_AlbedoHueToleranceMin, k_AlbedoHueToleranceMax, SetAlbedoHueTolerance);
albedoSpecificContent.Add(m_AlbedoHueTolerance);
m_AlbedoSaturationTolerance = CreateSliderWithField(sat, m_AlbedoSwatchSaturationTolerance, k_AlbedoHueToleranceMin, k_AlbedoHueToleranceMax, SetSaturationTolerance);
albedoSpecificContent.Add(m_AlbedoSaturationTolerance);
root.Add(albedoSpecificContent);
return root;
}
void SetAlbedoHueTolerance(ChangeEvent<float> evt)
{
m_AlbedoSwatchHueTolerance = Mathf.Clamp(evt.newValue, k_AlbedoHueToleranceMin, k_AlbedoHueToleranceMax);
var slider = m_AlbedoHueTolerance.Q<Slider>();
var field = m_AlbedoHueTolerance.Q<FloatField>();
slider.SetValueWithoutNotify(m_AlbedoSwatchHueTolerance);
if (evt.target != field || evt.newValue != 0)
field.SetValueWithoutNotify(m_AlbedoSwatchHueTolerance);
UpdateAlbedoSwatch();
}
void SetSaturationTolerance(ChangeEvent<float> evt)
{
m_AlbedoSwatchSaturationTolerance = Mathf.Clamp(evt.newValue, k_AlbedoHueToleranceMin, k_AlbedoHueToleranceMax);
var slider = m_AlbedoSaturationTolerance.Q<Slider>();
var field = m_AlbedoSaturationTolerance.Q<FloatField>();
slider.SetValueWithoutNotify(m_AlbedoSwatchSaturationTolerance);
if (evt.target != field || evt.newValue != 0)
field.SetValueWithoutNotify(m_AlbedoSwatchSaturationTolerance);
UpdateAlbedoSwatch();
}
VisualElement CreateSliderWithField(GUIContent label, float value, float min, float max, EventCallback<ChangeEvent<float>> callback)
{
var root = new VisualElement() { name = "Slider Float Field" };
root.AddToClassList(SceneViewLighting.Styles.k_SliderRowClass);
var slider = new Slider(min, max);
slider.AddToClassList(SceneViewLighting.Styles.k_SliderClass);
slider.RegisterValueChangedCallback(callback);
slider.SetValueWithoutNotify(value);
if (label != null && !string.IsNullOrEmpty(label.text))
{
slider.label = label.text;
slider.tooltip = label.tooltip;
}
var field = new FloatField();
field.AddToClassList(SceneViewLighting.Styles.k_SliderFloatFieldClass);
field.RegisterValueChangedCallback(callback);
field.SetValueWithoutNotify(value);
root.Add(slider);
root.Add(field);
return root;
}
void CreateAlbedoSwatchData()
{
AlbedoSwatchInfo[] graphicsSettingsSwatches = EditorGraphicsSettings.albedoSwatches;
if (graphicsSettingsSwatches.Length != 0)
{
m_AlbedoSwatchInfos = new List<AlbedoSwatchInfo>(graphicsSettingsSwatches);
}
else
{
m_AlbedoSwatchInfos = new List<AlbedoSwatchInfo>()
{
// colors taken from http://www.babelcolor.com/index_htm_files/ColorChecker_RGB_and_spectra.xls
new AlbedoSwatchInfo()
{
name = "Black Acrylic Paint",
color = new Color(56f / 255f, 56f / 255f, 56f / 255f),
minLuminance = 0.03f,
maxLuminance = 0.07f
},
new AlbedoSwatchInfo()
{
name = "Dark Soil",
color = new Color(85f / 255f, 61f / 255f, 49f / 255f),
minLuminance = 0.05f,
maxLuminance = 0.14f
},
new AlbedoSwatchInfo()
{
name = "Worn Asphalt",
color = new Color(91f / 255f, 91f / 255f, 91f / 255f),
minLuminance = 0.10f,
maxLuminance = 0.15f
},
new AlbedoSwatchInfo()
{
name = "Dry Clay Soil",
color = new Color(137f / 255f, 120f / 255f, 102f / 255f),
minLuminance = 0.15f,
maxLuminance = 0.35f
},
new AlbedoSwatchInfo()
{
name = "Green Grass",
color = new Color(123f / 255f, 131f / 255f, 74f / 255f),
minLuminance = 0.16f,
maxLuminance = 0.26f
},
new AlbedoSwatchInfo()
{
name = "Old Concrete",
color = new Color(135f / 255f, 136f / 255f, 131f / 255f),
minLuminance = 0.17f,
maxLuminance = 0.30f
},
new AlbedoSwatchInfo()
{
name = "Red Clay Tile",
color = new Color(197f / 255f, 125f / 255f, 100f / 255f),
minLuminance = 0.23f,
maxLuminance = 0.33f
},
new AlbedoSwatchInfo()
{
name = "Dry Sand",
color = new Color(177f / 255f, 167f / 255f, 132f / 255f),
minLuminance = 0.20f,
maxLuminance = 0.45f
},
new AlbedoSwatchInfo()
{
name = "New Concrete",
color = new Color(185f / 255f, 182f / 255f, 175f / 255f),
minLuminance = 0.32f,
maxLuminance = 0.55f
},
new AlbedoSwatchInfo()
{
name = "White Acrylic Paint",
color = new Color(227f / 255f, 227f / 255f, 227f / 255f),
minLuminance = 0.75f,
maxLuminance = 0.85f
},
new AlbedoSwatchInfo()
{
name = "Fresh Snow",
color = new Color(243f / 255f, 243f / 255f, 243f / 255f),
minLuminance = 0.85f,
maxLuminance = 0.95f
},
new AlbedoSwatchInfo()
{
name = "Blue Sky",
color = new Color(93f / 255f, 123f / 255f, 157f / 255f),
minLuminance = new Color(93f / 255f, 123f / 255f, 157f / 255f).linear.maxColorComponent - 0.05f,
maxLuminance = new Color(93f / 255f, 123f / 255f, 157f / 255f).linear.maxColorComponent + 0.05f
},
new AlbedoSwatchInfo()
{
name = "Foliage",
color = new Color(91f / 255f, 108f / 255f, 65f / 255f),
minLuminance = new Color(91f / 255f, 108f / 255f, 65f / 255f).linear.maxColorComponent - 0.05f,
maxLuminance = new Color(91f / 255f, 108f / 255f, 65f / 255f).linear.maxColorComponent + 0.05f
},
};
}
m_AlbedoSwatchInfos.Insert(0, new AlbedoSwatchInfo()
{
name = "Default Luminance",
color = Color.gray,
minLuminance = 0.012f,
maxLuminance = 0.9f
});
}
void UpdateAlbedoMetalValidation()
{
SelectedAlbedoSwatchChanged();
}
void UpdateAlbedoSwatch()
{
var color = m_SelectedAlbedoSwatch.color;
Shader.SetGlobalFloat("_AlbedoMinLuminance", m_SelectedAlbedoSwatch.minLuminance);
Shader.SetGlobalFloat("_AlbedoMaxLuminance", m_SelectedAlbedoSwatch.maxLuminance);
Shader.SetGlobalFloat("_AlbedoHueTolerance", m_AlbedoSwatchHueTolerance);
Shader.SetGlobalFloat("_AlbedoSaturationTolerance", m_AlbedoSwatchSaturationTolerance);
Shader.SetGlobalColor("_AlbedoCompareColor", color.linear);
Shader.SetGlobalFloat("_CheckAlbedo", (m_SelectedAlbedoPopup.index != 0) ? 1.0f : 0.0f);
Shader.SetGlobalFloat("_CheckPureMetal", m_SceneView.validateTrueMetals ? 1.0f : 0.0f);
}
void SelectedAlbedoSwatchChanged()
{
var color = m_AlbedoContent.Q(SceneViewLighting.Styles.k_SwatchColorContent);
var label = m_AlbedoContent.Q<Label>("color-label");
bool colorCorrect = PlayerSettings.colorSpace == ColorSpace.Linear;
color.style.backgroundColor = colorCorrect
? m_SelectedAlbedoSwatch.color.gamma
: m_SelectedAlbedoSwatch.color;
float minLum = m_SelectedAlbedoSwatch.minLuminance;
float maxLum = m_SelectedAlbedoSwatch.maxLuminance;
label.text = $"Luminance ({minLum:F2} - {maxLum:F2})";
UpdateAlbedoSwatch();
}
void SetSelectedAlbedoSwatch(ChangeEvent<AlbedoSwatchInfo> evt)
{
m_SelectedAlbedoSwatch = evt.newValue;
SelectedAlbedoSwatchChanged();
}
void ValidateTrueMetalsChanged(ChangeEvent<bool> evt)
{
m_SceneView.validateTrueMetals = evt.newValue;
}
}
[Overlay(typeof(SceneView), k_OverlayID, "Lighting Visualization Colors", priority = (int)OverlayPriority.LightingVisualizationColor, defaultDockZone = DockZone.LeftColumn)]
[Icon("Icons/LightingVisualizationColors.png")]
class SceneViewLightingColors : Overlay, ITransientOverlay
{
const string k_OverlayID = "Scene View/Lighting Visualization Colors";
static readonly PrefColor kSceneViewMaterialValidateLow = new PrefColor("Scene/Material Validator Value Too Low", 255.0f / 255.0f, 0.0f, 0.0f, 1.0f);
static readonly PrefColor kSceneViewMaterialValidateHigh = new PrefColor("Scene/Material Validator Value Too High", 0.0f, 0.0f, 255.0f / 255.0f, 1.0f);
static readonly PrefColor kSceneViewMaterialValidatePureMetal = new PrefColor("Scene/Material Validator Pure Metal", 255.0f / 255.0f, 255.0f / 255.0f, 0.0f, 1.0f);
static readonly PrefColor kSceneViewMaterialNoContributeGI = new PrefColor("Scene/Receive GI Only (Light Probes)", 230.0f / 255.0f, 99.0f / 255.0f, 25.0f / 255.0f, 1.0f);
static readonly PrefColor kSceneViewMaterialReceiveGILightmaps = new PrefColor("Scene/Receive + Contribute GI (Lightmaps)", 47.0f / 255.0f, 153.0f / 255.0f, 41.0f / 255.0f, 1.0f);
static readonly PrefColor kSceneViewMaterialReceiveGILightProbes = new PrefColor("Scene/Receive + Contribute GI (Light Probes)", 35.0f / 255.0f, 15.0f / 255.0f, 153.0f / 255.0f, 1.0f);
static readonly PrefColor kSceneViewHighlightBackfaces = new PrefColor("Scene/Back-Facing Geometry", 126.0f / 255.0f, 46.0f / 255.0f, 217.0f / 255.0f, 1.0f);
// Should match colors in BakePipelineBuildVisualization.cpp!
static readonly Color kSceneViewInvalidTexel = new Color(247.0f / 255.0f, 79.0f / 255.0f, 65.0f / 255.0f, 255.0f / 255.0f);
static readonly Color kSceneViewValidTexel = new Color(12.0f / 255.0f, 99.0f / 255.0f, 8.0f / 255.0f, 255.0f / 255.0f);
static readonly Color kSceneViewOverlappingTexel = new Color(247.0f / 255.0f, 79.0f / 255.0f, 65.0f / 255.0f, 255.0f / 255.0f);
static readonly Color kSceneViewNonOverlappingTexel = new Color(255.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f, 255.0f / 255.0f);
// material validation, contribute GI, and albedo swatches are represented in this array. it is used to update
// the colors when preferences are changed.
Dictionary<PrefColor, VisualElement> m_PrefColorSwatches = new Dictionary<PrefColor, VisualElement>();
bool m_ShouldDisplay;
public bool visible => m_ShouldDisplay;
SceneView m_SceneView;
SceneView sceneView => m_SceneView;
VisualElement m_ContentRoot;
// Backface highlights
VisualElement m_BackfaceHighlightsContent;
// Validate albedo / metals
VisualElement m_AlbedoContent;
ColorSpace m_LastKnownColorSpace = ColorSpace.Uninitialized;
// Light exposure
VisualElement m_GlobalIlluminationContent;
// Debug view modes
VisualElement m_TexelValidityContent;
VisualElement m_UVOverlapContent;
public SceneViewLightingColors()
{
PrefSettings.settingChanged += UpdatePrefColors;
}
public override void OnCreated()
{
if (!(containerWindow is SceneView view))
throw new Exception("Lighting Visualization Colors Overlay is only valid in the Scene View");
m_ShouldDisplay = false;
m_SceneView = view;
m_SceneView.onCameraModeChanged += OnCameraModeChanged;
SceneView.onDrawBackfaceHighlightsChanged += OnDrawBackfaceHighlightsChanged;
}
public override void OnWillBeDestroyed()
{
m_SceneView.onCameraModeChanged -= OnCameraModeChanged;
SceneView.onDrawBackfaceHighlightsChanged -= OnDrawBackfaceHighlightsChanged;
}
public override VisualElement CreatePanelContent()
{
if (!(containerWindow is SceneView view))
return new Label("Lighting Visualization Colors Overlay is only valid in the Scene View");
m_SceneView = view;
m_ContentRoot = new VisualElement();
m_ContentRoot.Add(m_BackfaceHighlightsContent = CreateBackfaceHighlightsContent());
m_ContentRoot.Add(m_AlbedoContent = CreateAlbedoContent());
m_ContentRoot.Add(m_GlobalIlluminationContent = CreateGIContent());
m_ContentRoot.Add(m_TexelValidityContent = CreateTexelValidityContent());
m_ContentRoot.Add(m_UVOverlapContent = CreateUVOverlapContent());
OnCameraModeChanged(sceneView.cameraMode);
return m_ContentRoot;
}
void OnDrawBackfaceHighlightsChanged(bool value)
{
OnCameraModeChanged(sceneView.cameraMode);
}
void OnCameraModeChanged(SceneView.CameraMode mode)
{
// If the rootVisualElement hasn't yet been created, early out
if (m_ContentRoot == null)
CreatePanelContent();
bool showValidationLegend = mode.drawMode == DrawCameraMode.ValidateAlbedo || mode.drawMode == DrawCameraMode.ValidateMetalSpecular;
bool showGIContributorsReceiversLegend = mode.drawMode == DrawCameraMode.GIContributorsReceivers;
bool showTexelValidityLegend = mode.drawMode == DrawCameraMode.BakedTexelValidity;
bool showUVOverlapLegend = mode.drawMode == DrawCameraMode.BakedUVOverlap;
bool showBackfaceHighlightsLegend = sceneView.showBackfaceHighlightsToggle && SceneView.GetDrawBackfaceHighlights();
bool showPanel = showValidationLegend || showGIContributorsReceiversLegend || showBackfaceHighlightsLegend || showTexelValidityLegend || showUVOverlapLegend;
m_BackfaceHighlightsContent.EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, !showBackfaceHighlightsLegend);
m_AlbedoContent.EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, !showValidationLegend);
m_GlobalIlluminationContent.EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, !showGIContributorsReceiversLegend);
m_TexelValidityContent.EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, !showTexelValidityLegend);
m_UVOverlapContent.EnableInClassList(SceneViewLighting.Styles.k_UnityHiddenClass, !showUVOverlapLegend);
if (showPanel)
{
m_SceneView.SetOverlayVisible(k_OverlayID, true);
m_ShouldDisplay = true;
}
else
{
m_ShouldDisplay = false;
}
if (PlayerSettings.colorSpace != m_LastKnownColorSpace)
UpdateColorLegend();
}
VisualElement CreateBackfaceHighlightsContent()
{
var root = new VisualElement() { name = "Back-Facing Geometry Content" };
root.Add(m_PrefColorSwatches[kSceneViewHighlightBackfaces] = CreateColorSwatch("Back-Facing Geometry", kSceneViewHighlightBackfaces));
return root;
}
VisualElement CreateGIContent()
{
var root = new VisualElement() { name = "GI Content" };
string contributeGIOff = "Receive GI Only (Light Probes)";
string receiveGILightmaps = "Receive + Contribute GI (Lightmaps)";
string receiveGILightProbes = "Receive + Contribute GI (Light Probes)";
root.Add(m_PrefColorSwatches[kSceneViewMaterialNoContributeGI] = CreateColorSwatch(contributeGIOff, kSceneViewMaterialNoContributeGI));
root.Add(m_PrefColorSwatches[kSceneViewMaterialReceiveGILightmaps] = CreateColorSwatch(receiveGILightmaps, kSceneViewMaterialReceiveGILightmaps));
root.Add(m_PrefColorSwatches[kSceneViewMaterialReceiveGILightProbes] = CreateColorSwatch(receiveGILightProbes, kSceneViewMaterialReceiveGILightProbes));
return root;
}
VisualElement CreateAlbedoContent()
{
var root = new VisualElement() { name = "Albedo Content" };
string modeString = m_SceneView.cameraMode.drawMode == DrawCameraMode.ValidateAlbedo
? "Luminance"
: "Specular";
root.Add(m_PrefColorSwatches[kSceneViewMaterialValidateLow] = CreateColorSwatch($"Below Minimum {modeString} Value", kSceneViewMaterialValidateLow));
root.Add(m_PrefColorSwatches[kSceneViewMaterialValidateHigh] = CreateColorSwatch($"Above Maximum {modeString} Value", kSceneViewMaterialValidateHigh));
root.Add(m_PrefColorSwatches[kSceneViewMaterialValidatePureMetal] = CreateColorSwatch($"Not A Pure Metal", kSceneViewMaterialValidatePureMetal));
return root;
}
VisualElement CreateTexelValidityContent()
{
var root = new VisualElement() { name = "Texel Validity Content" };
root.Add(CreateColorSwatch("Invalid Texels", null, kSceneViewInvalidTexel));
root.Add(CreateColorSwatch("Valid Texels", null, kSceneViewValidTexel));
return root;
}
VisualElement CreateUVOverlapContent()
{
var root = new VisualElement() { name = "UV Overlap Content" };
root.Add(CreateColorSwatch("Overlapping Texels", null, kSceneViewOverlappingTexel));
root.Add(CreateColorSwatch("Non-Overlapping Texels", null, kSceneViewNonOverlappingTexel));
return root;
}
internal static VisualElement CreateColorSwatch(string label, PrefColor prefColor) => CreateColorSwatch(label, prefColor, Color.magenta);
internal static VisualElement CreateColorSwatch(string label, PrefColor prefColor, Color fallbackColor)
{
var row = new VisualElement() { style = { flexDirection = FlexDirection.Row, marginLeft = 2 } };
row.AddToClassList(SceneViewLighting.Styles.k_UnityBaseFieldClass);
var swatchContainer = new VisualElement();
swatchContainer.AddToClassList("unity-base-field__label");
swatchContainer.AddToClassList("unity-pbr-validation-color-swatch");
var colorContent = new VisualElement() { name = SceneViewLighting.Styles.k_SwatchColorContent };
if (prefColor == null)
{
colorContent.style.backgroundColor = new StyleColor(fallbackColor);
}
else
{
colorContent.style.backgroundColor = new StyleColor(prefColor);
colorContent.AddManipulator(new Clickable(() =>
{
ColorPicker.Show((c) =>
{
prefColor.Color = c;
PrefSettings.Set(prefColor.Name, prefColor);
},
prefColor.Color, false, false);
}));
}
swatchContainer.Add(colorContent);
row.Add(swatchContainer);
var colorLabel = new Label(label) { name = "color-label" };
colorLabel.AddToClassList("unity-base-field__label");
row.Add(colorLabel);
return row;
}
void UpdateColorLegend()
{
if (PlayerSettings.colorSpace == ColorSpace.Linear)
{
Shader.SetGlobalColor("unity_MaterialValidateLowColor", kSceneViewMaterialValidateLow.Color.linear);
Shader.SetGlobalColor("unity_MaterialValidateHighColor", kSceneViewMaterialValidateHigh.Color.linear);
Shader.SetGlobalColor("unity_MaterialValidatePureMetalColor", kSceneViewMaterialValidatePureMetal.Color.linear);
Shader.SetGlobalColor("unity_BackfaceHighlightsColor", kSceneViewHighlightBackfaces.Color.linear);
}
else
{
Shader.SetGlobalColor("unity_MaterialValidateLowColor", kSceneViewMaterialValidateLow.Color);
Shader.SetGlobalColor("unity_MaterialValidateHighColor", kSceneViewMaterialValidateHigh.Color);
Shader.SetGlobalColor("unity_MaterialValidatePureMetalColor", kSceneViewMaterialValidatePureMetal.Color);
Shader.SetGlobalColor("unity_BackfaceHighlightsColor", kSceneViewHighlightBackfaces.Color);
}
Handles.SetSceneViewModeGIContributorsReceiversColors(
kSceneViewMaterialNoContributeGI.Color,
kSceneViewMaterialReceiveGILightmaps.Color,
kSceneViewMaterialReceiveGILightProbes.Color);
m_LastKnownColorSpace = PlayerSettings.colorSpace;
}
void UpdatePrefColors(string key, Type prefType)
{
if (m_ContentRoot == null || prefType != typeof(PrefColor))
return;
foreach (var color in m_PrefColorSwatches)
{
if (color.Key.Name == key)
{
var swatch = color.Value.Q(SceneViewLighting.Styles.k_SwatchColorContent);
if (swatch != null)
swatch.style.backgroundColor = new StyleColor(color.Key.Color);
break;
}
}
UpdateColorLegend();
}
}
}
| UnityCsReference/Modules/SceneView/SceneViewLightingOverlays.cs/0 | {
"file_path": "UnityCsReference/Modules/SceneView/SceneViewLightingOverlays.cs",
"repo_id": "UnityCsReference",
"token_count": 19217
} | 454 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
namespace UnityEditor.ShaderFoundry
{
// This class stores static data relating IInternalType and IPublicType objects.
// This is used to handle generics in order to interface with the native container.
class DataTypeStatic
{
internal readonly struct DataTypeInfo
{
public readonly DataType dataType;
public readonly Type publicType;
public readonly Type internalType;
public readonly int internalTypeSizeInBytes;
public DataTypeInfo(DataType dataType, Type internalType, Type publicType)
: this(dataType, internalType, publicType, System.Runtime.InteropServices.Marshal.SizeOf(internalType))
{
}
private DataTypeInfo(DataType dataType, Type internalType, Type publicType, int internalTypeSizeInBytes)
{
this.dataType = dataType;
this.publicType = publicType;
this.internalType = internalType;
this.internalTypeSizeInBytes = internalTypeSizeInBytes;
}
public static DataTypeInfo Invalid => new DataTypeInfo(DataType.Unknown, null, null, 0);
}
DataTypeInfo Invalid = DataTypeInfo.Invalid;
Dictionary<Type, DataTypeInfo> internalTypeMap = new Dictionary<Type, DataTypeInfo>();
Dictionary<Type, DataTypeInfo> publicTypeMap = new Dictionary<Type, DataTypeInfo>();
Dictionary<DataType, DataTypeInfo> dataTypeToInfo = new Dictionary<DataType, DataTypeInfo>();
static DataTypeStatic m_Instance = null;
static DataTypeStatic Instance
{
get
{
if (m_Instance == null)
Initialize();
return m_Instance;
}
}
static void Initialize()
{
// The type relations must be explicitly recorded.
m_Instance = new DataTypeStatic();
m_Instance.Register<ShaderAttributeParameterInternal, ShaderAttributeParameter>(DataType.ShaderAttributeParameter);
m_Instance.Register<ShaderAttributeInternal, ShaderAttribute>(DataType.ShaderAttribute);
m_Instance.Register<RenderStateDescriptorInternal, RenderStateDescriptor>(DataType.RenderStateDescriptor);
m_Instance.Register<DefineDescriptorInternal, DefineDescriptor>(DataType.DefineDescriptor);
m_Instance.Register<IncludeDescriptorInternal, IncludeDescriptor>(DataType.IncludeDescriptor);
m_Instance.Register<KeywordDescriptorInternal, KeywordDescriptor>(DataType.KeywordDescriptor);
m_Instance.Register<PragmaDescriptorInternal, PragmaDescriptor>(DataType.PragmaDescriptor);
m_Instance.Register<TagDescriptorInternal, TagDescriptor>(DataType.TagDescriptor);
m_Instance.Register<FunctionParameterInternal, FunctionParameter>(DataType.FunctionParameter);
m_Instance.Register<ShaderFunctionInternal, ShaderFunction>(DataType.ShaderFunction);
m_Instance.Register<StructFieldInternal, StructField>(DataType.StructField);
m_Instance.Register<ShaderTypeInternal, ShaderType>(DataType.ShaderType);
m_Instance.Register<BlockVariableInternal, BlockVariable>(DataType.BlockVariable);
m_Instance.Register<BlockInternal, Block>(DataType.Block);
m_Instance.Register<CustomizationPointInternal, CustomizationPoint>(DataType.CustomizationPoint);
m_Instance.Register<TemplatePassInternal, TemplatePass>(DataType.TemplatePass);
m_Instance.Register<TemplateInternal, Template>(DataType.Template);
m_Instance.Register<TemplateInstanceInternal, TemplateInstance>(DataType.TemplateInstance);
m_Instance.Register<ShaderDependencyInternal, ShaderDependency>(DataType.ShaderDependency);
m_Instance.Register<ShaderCustomEditorInternal, ShaderCustomEditor>(DataType.ShaderCustomEditor);
m_Instance.Register<PackageRequirementInternal, PackageRequirement>(DataType.PackageRequirement);
m_Instance.Register<CopyRuleInternal, CopyRule>(DataType.CopyRule);
m_Instance.Register<BlockLinkOverrideInternal, BlockLinkOverride>(DataType.LinkOverride);
m_Instance.Register<BlockLinkOverrideInternal.LinkAccessorInternal, BlockLinkOverride.LinkAccessor>(DataType.LinkAccessor);
m_Instance.Register<BlockLinkOverrideInternal.LinkElementInternal, BlockLinkOverride.LinkElement>(DataType.LinkElement);
m_Instance.Register<BlockSequenceElementInternal, BlockSequenceElement>(DataType.BlockSequenceElement);
m_Instance.Register<CustomizationPointImplementationInternal, CustomizationPointImplementation>(DataType.CustomizationPointImplementation);
m_Instance.Register<StageDescriptionInternal, StageDescription>(DataType.StageDescription);
m_Instance.Register<BlockShaderInterfaceInternal, BlockShaderInterface>(DataType.BlockShaderInterface);
m_Instance.Register<BlockShaderInternal, BlockShader>(DataType.BlockShader);
m_Instance.Register<RegisterTemplatesWithInterfaceInternal, RegisterTemplatesWithInterface>(DataType.RegisterTemplatesWithInterface);
m_Instance.Register<InterfaceRegistrationStatementInternal, InterfaceRegistrationStatement>(DataType.InterfaceRegistrationStatement);
m_Instance.Register<NamespaceInternal, Namespace>(DataType.Namespace);
}
void Register<InternalType, PublicType>(DataType dataType)
where InternalType : struct, IInternalType<InternalType>
where PublicType : struct, IPublicType<PublicType>
{
var iType = typeof(InternalType);
var pType = typeof(PublicType);
var info = new DataTypeInfo(dataType, iType, pType);
m_Instance.internalTypeMap[iType] = info;
m_Instance.publicTypeMap[pType] = info;
m_Instance.dataTypeToInfo[dataType] = info;
}
static internal DataTypeInfo GetInfoFromDataType(DataType type)
{
if (!Instance.dataTypeToInfo.TryGetValue(type, out var info))
return Instance.Invalid;
return info;
}
static internal DataTypeInfo GetInfoFromInternalType<T>() where T : struct, IInternalType<T>
{
if (!Instance.internalTypeMap.TryGetValue(typeof(T), out var info))
return Instance.Invalid;
return info;
}
static internal DataType GetDataTypeFromInternalType<T>() where T : struct, IInternalType<T>
{
if (!Instance.internalTypeMap.TryGetValue(typeof(T), out var info))
return DataType.Unknown;
return info.dataType;
}
static internal DataTypeInfo GetInfoFromPublicType<T>() where T : struct, IPublicType<T>
{
if (!Instance.publicTypeMap.TryGetValue(typeof(T), out var info))
return Instance.Invalid;
return info;
}
static internal DataType GetDataTypeFromPublicType<T>() where T : struct, IPublicType<T>
{
if (!Instance.publicTypeMap.TryGetValue(typeof(T), out var info))
return DataType.Unknown;
return info.dataType;
}
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/DataTypeStatic.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/DataTypeStatic.cs",
"repo_id": "UnityCsReference",
"token_count": 2894
} | 455 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEditor.ShaderFoundry
{
// THIS ENUM MUST BE KEPT IN SYNC WITH THE ENUM IN PassStageType.h
enum PassStageType : short
{
Invalid = -1,
Vertex = 0,
HullConstant,
Hull,
Domain,
Geometry,
Fragment,
Count,
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/PassStageType.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/PassStageType.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 195
} | 456 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Bindings;
namespace UnityEditor.ShaderFoundry
{
[NativeHeader("Modules/ShaderFoundry/Public/Template.h")]
internal struct TemplateInternal : IInternalType<TemplateInternal>
{
internal FoundryHandle m_NameHandle; // string
internal FoundryHandle m_AttributeListHandle; // List<ShaderAttribute>
internal FoundryHandle m_ContainingNamespaceHandle; // Namespace
internal FoundryHandle m_PassListHandle; // List<TemplatePass>
internal FoundryHandle m_TagDescriptorListHandle; // List<FoundryHandle>
internal FoundryHandle m_LODHandle; // string
internal FoundryHandle m_PackageRequirementListHandle; // List<PackageRequirements>
internal FoundryHandle m_CustomizationPointListHandle; // List<CustomizationPoint>
internal FoundryHandle m_ExtendedTemplateListHandle; // List<Template>
internal FoundryHandle m_PassCopyRuleListHandle; // List<CopyRule>
internal FoundryHandle m_CustomizationPointCopyRuleListHandle; // List<CopyRule>
internal FoundryHandle m_CustomizationPointImplementationListHandle; // List<CustomizationPointImplementation>
internal FoundryHandle m_AdditionalShaderIDStringHandle; // string
internal FoundryHandle m_LinkerHandle; // ILinker (in C# container only)
// these are per-shader settings, that get passed up to the shader level
// and merged with the same settings from other subshaders
internal FoundryHandle m_ShaderDependencyListHandle; // List<ShaderDependency>
internal FoundryHandle m_ShaderCustomEditorHandle; // ShaderCustomEditor
internal FoundryHandle m_ShaderFallbackHandle; // string
internal extern static TemplateInternal Invalid();
internal extern bool IsValid();
// IInternalType
TemplateInternal IInternalType<TemplateInternal>.ConstructInvalid() => Invalid();
}
[FoundryAPI]
internal readonly struct Template : IEquatable<Template>, IPublicType<Template>
{
// data members
readonly ShaderContainer container;
internal readonly FoundryHandle handle;
readonly TemplateInternal template;
// IPublicType
ShaderContainer IPublicType.Container => Container;
bool IPublicType.IsValid => IsValid;
FoundryHandle IPublicType.Handle => handle;
Template IPublicType<Template>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new Template(container, handle);
// public API
public ShaderContainer Container => container;
public bool IsValid => (container != null && handle.IsValid);
public string Name => container?.GetString(template.m_NameHandle) ?? string.Empty;
public IEnumerable<ShaderAttribute> Attributes => HandleListInternal.Enumerate<ShaderAttribute>(container, template.m_AttributeListHandle);
public Namespace ContainingNamespace => new Namespace(container, template.m_ContainingNamespaceHandle);
public string AdditionalShaderID => container?.GetString(template.m_AdditionalShaderIDStringHandle) ?? string.Empty;
public IEnumerable<TemplatePass> Passes
{
get
{
var localContainer = Container;
var passList = new HandleListInternal(template.m_PassListHandle);
return passList.Select<TemplatePass>(localContainer, (handle) => (new TemplatePass(localContainer, handle)));
}
}
public IEnumerable<TagDescriptor> TagDescriptors => template.m_TagDescriptorListHandle.AsListEnumerable<TagDescriptor>(container, (container, handle) => (new TagDescriptor(container, handle)));
public string LOD => container?.GetString(template.m_LODHandle) ?? string.Empty;
public IEnumerable<PackageRequirement> PackageRequirements => template.m_PackageRequirementListHandle.AsListEnumerable<PackageRequirement>(container, (container, handle) => (new PackageRequirement(container, handle)));
public IEnumerable<CustomizationPoint> CustomizationPoints => template.m_CustomizationPointListHandle.AsListEnumerable<CustomizationPoint>(Container, (container, handle) => (new CustomizationPoint(container, handle)));
public IEnumerable<Template> ExtendedTemplates => template.m_ExtendedTemplateListHandle.AsListEnumerable<Template>(container, (container, handle) => (new Template(container, handle)));
public IEnumerable<CopyRule> PassCopyRules => template.m_PassCopyRuleListHandle.AsListEnumerable<CopyRule>(container, (container, handle) => (new CopyRule(container, handle)));
public IEnumerable<CopyRule> CustomizationPointCopyRules => template.m_CustomizationPointCopyRuleListHandle.AsListEnumerable<CopyRule>(container, (container, handle) => (new CopyRule(container, handle)));
public IEnumerable<CustomizationPointImplementation> CustomizationPointImplementations => template.m_CustomizationPointImplementationListHandle.AsListEnumerable<CustomizationPointImplementation>(container, (container, handle) => (new CustomizationPointImplementation(container, handle)));
public IEnumerable<ShaderDependency> ShaderDependencies => template.m_ShaderDependencyListHandle.AsListEnumerable(container, (container, handle) => new ShaderDependency(container, handle));
public ShaderCustomEditor CustomEditor => new ShaderCustomEditor(container, template.m_ShaderCustomEditorHandle);
public string ShaderFallback => container?.GetString(template.m_ShaderFallbackHandle) ?? string.Empty;
public ITemplateLinker Linker => container?.GetTemplateLinker(template.m_LinkerHandle) ?? null;
// private
internal Template(ShaderContainer container, FoundryHandle handle)
{
this.container = container;
this.handle = handle;
ShaderContainer.Get(container, handle, out template);
}
public static Template Invalid => new Template(null, FoundryHandle.Invalid());
// Equals and operator == implement Reference Equality. ValueEquals does a deep compare if you need that instead.
public override bool Equals(object obj) => obj is Template other && this.Equals(other);
public bool Equals(Template other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container);
public override int GetHashCode() => (container, handle).GetHashCode();
public static bool operator==(Template lhs, Template rhs) => lhs.Equals(rhs);
public static bool operator!=(Template lhs, Template rhs) => !lhs.Equals(rhs);
public class Builder
{
public string Name { get; set; }
public List<ShaderAttribute> attributes;
public Namespace containingNamespace = Namespace.Invalid;
List<TemplatePass> passes { get; set; }
public string AdditionalShaderID { get; set; }
ITemplateLinker linker;
List<TagDescriptor> tagDescriptors;
public string LOD;
List<PackageRequirement> packageRequirements;
List<CustomizationPoint> customizationPoints;
List<Template> extendedTemplates;
List<CopyRule> passCopyRules;
List<CopyRule> customizationPointCopyRules;
List<CustomizationPointImplementation> customizationPointImplementations;
List<ShaderDependency> shaderDependencies;
public ShaderCustomEditor CustomEditor { get; set; } = ShaderCustomEditor.Invalid;
public string ShaderFallback { get; set; }
readonly ShaderContainer container;
public ShaderContainer Container => container;
public Builder(ShaderContainer container, string name)
{
if (container == null)
throw new Exception("A valid ShaderContainer must be provided to create a Template Builder.");
this.container = container;
this.Name = name;
this.containingNamespace = Utilities.BuildDefaultObjectNamespace(container, name);
this.linker = null;
}
public Builder(ShaderContainer container, string name, ITemplateLinker linker)
{
if (container == null || linker == null)
throw new Exception("A valid ShaderContainer and ITemplateLinker must be provided to create a Template Builder.");
this.container = container;
this.Name = name;
this.containingNamespace = Utilities.BuildDefaultObjectNamespace(container, name);
this.linker = linker;
}
public void AddAttribute(ShaderAttribute attribute) => Utilities.AddToList(ref attributes, attribute);
public void AddPass(TemplatePass pass)
{
if (pass.IsValid)
{
if (passes == null)
passes = new List<TemplatePass>();
passes.Add(pass);
}
}
public void AddTagDescriptor(TagDescriptor tagDescriptor)
{
if (tagDescriptor.IsValid)
{
if (tagDescriptors == null)
tagDescriptors = new List<TagDescriptor>();
tagDescriptors.Add(tagDescriptor);
}
}
public void AddPackageRequirement(PackageRequirement packageRequirement)
{
if (packageRequirement.IsValid)
{
if (packageRequirements == null)
packageRequirements = new List<PackageRequirement>();
packageRequirements.Add(packageRequirement);
}
}
public void AddCustomizationPoint(CustomizationPoint customizationPoint)
{
if (customizationPoint.IsValid)
{
if (customizationPoints == null)
customizationPoints = new List<CustomizationPoint>();
customizationPoints.Add(customizationPoint);
}
}
public void AddTemplateExtension(Template template) => Utilities.AddToList(ref extendedTemplates, template);
public void AddPassCopyRule(CopyRule rule) => Utilities.AddToList(ref passCopyRules, rule);
public void AddCustomizationPointCopyRule(CopyRule rule) => Utilities.AddToList(ref customizationPointCopyRules, rule);
public void AddCustomizationPointImplementation(CustomizationPointImplementation customizationPointImplementation) => Utilities.AddToList(ref customizationPointImplementations, customizationPointImplementation);
public void AddUsePass(string usePassName)
{
if (!string.IsNullOrEmpty(usePassName))
{
var builder = new TemplatePass.UsePassBuilder(container, usePassName);
AddPass(builder.Build());
}
}
public void AddShaderDependency(ShaderDependency shaderDependency)
{
if (shaderDependency.IsValid)
{
if (shaderDependencies == null)
shaderDependencies = new List<ShaderDependency>();
shaderDependencies.Add(shaderDependency);
}
}
public void AddShaderDependency(string dependencyName, string shaderName)
{
AddShaderDependency(new ShaderDependency(container, dependencyName, shaderName));
}
public void SetCustomEditor(string customEditorClassName, string renderPipelineAssetClassName)
{
CustomEditor = new ShaderCustomEditor(container, customEditorClassName, renderPipelineAssetClassName);
}
public Template Build()
{
var templateInternal = new TemplateInternal()
{
m_NameHandle = container.AddString(Name),
m_AdditionalShaderIDStringHandle = container.AddString(AdditionalShaderID),
m_LinkerHandle = container.AddTemplateLinker(linker),
m_ShaderFallbackHandle = container.AddString(ShaderFallback),
};
templateInternal.m_AttributeListHandle = HandleListInternal.Build(container, attributes);
templateInternal.m_ContainingNamespaceHandle = containingNamespace.handle;
templateInternal.m_PassListHandle = HandleListInternal.Build(container, passes, (p) => (p.handle));
templateInternal.m_LODHandle = container.AddString(LOD);
templateInternal.m_PackageRequirementListHandle = HandleListInternal.Build(container, packageRequirements, (p) => (p.handle));
templateInternal.m_CustomizationPointListHandle = HandleListInternal.Build(container, customizationPoints, (c) => c.handle);
templateInternal.m_ExtendedTemplateListHandle = HandleListInternal.Build(container, extendedTemplates, (t) => (t.handle));
templateInternal.m_PassCopyRuleListHandle = HandleListInternal.Build(container, passCopyRules, (r) => (r.handle));
templateInternal.m_CustomizationPointCopyRuleListHandle = HandleListInternal.Build(container, customizationPointCopyRules, (r) => (r.handle));
templateInternal.m_CustomizationPointImplementationListHandle = HandleListInternal.Build(container, customizationPointImplementations, (c) => (c.handle));
templateInternal.m_TagDescriptorListHandle = HandleListInternal.Build(container, tagDescriptors, (t) => (t.handle));
templateInternal.m_ShaderDependencyListHandle = HandleListInternal.Build(container, shaderDependencies, (sd) => sd.handle);
templateInternal.m_ShaderCustomEditorHandle = CustomEditor.IsValid ? CustomEditor.handle : FoundryHandle.Invalid();
var returnTypeHandle = container.Add(templateInternal);
return new Template(container, returnTypeHandle);
}
}
}
}
| UnityCsReference/Modules/ShaderFoundry/ScriptBindings/Template.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/Template.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 5731
} | 457 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEditor.ShortcutManagement
{
[AttributeUsage(AttributeTargets.Method)]
internal class FormerlyPrefKeyAsAttribute : Attribute
{
public readonly string name;
public readonly string defaultValue;
public FormerlyPrefKeyAsAttribute(string name, string defaultValue)
{
this.name = name;
this.defaultValue = defaultValue;
}
}
}
| UnityCsReference/Modules/ShortcutManagerEditor/FormerlyPrefKeyAsAttribute.cs/0 | {
"file_path": "UnityCsReference/Modules/ShortcutManagerEditor/FormerlyPrefKeyAsAttribute.cs",
"repo_id": "UnityCsReference",
"token_count": 211
} | 458 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.Scripting;
namespace UnityEditor.ShortcutManagement
{
enum RebindResolution
{
DoNotRebind,
CreateConflict,
UnassignExistingAndBind
}
interface IShortcutManagerWindowView
{
VisualElement GetVisualElementHierarchyRoot();
void RefreshAll();
void RefreshKeyboard();
void RefreshMouse();
void RefreshCategoryList();
void RefreshShortcutList();
void RefreshProfiles();
void UpdateSearchFilterOptions();
RebindResolution HandleRebindWillCreateConflict(ShortcutEntry entry, IList<KeyCombination> newBinding, IList<ShortcutEntry> conflicts);
}
enum BindingState
{
NotBound = 0,
BoundGlobally = 1,
BoundToContext = 2,
BoundMixed = 3
}
enum SearchOption
{
Name,
Binding
}
interface IShortcutManagerWindowViewController
{
List<string> GetAvailableProfiles();
string activeProfile
{
get; set;
}
string CanCreateProfile(string newProfileId);
void CreateProfile(string newProfileId);
bool CanRenameActiveProfile();
string CanRenameActiveProfile(string newProfileId);
void RenameActiveProfile(string newProfileId);
bool CanDeleteActiveProfile();
void DeleteActiveProfile();
void ResetToDefault(ShortcutEntry entry);
void RemoveBinding(ShortcutEntry entry);
IList<string> GetCategories();
int categorySeparatorIndex { get; }
bool CanImportProfile(string path, bool letUserDecide = true);
void ImportProfile(string path);
bool CanExportProfile();
void ExportProfile(string path);
void SetCategorySelected(string category);
int selectedCategoryIndex
{
get;
}
SearchOption searchMode
{
get; set;
}
void SetSearch(string newSearch);
string GetSearch();
List<KeyCombination> GetBindingSearch();
void SetBindingSearch(List<KeyCombination> newBindingSearch);
bool ShouldShowSearchFilters();
void GetSearchFilters(List<string> filters);
string GetSelectedSearchFilter();
void SetSelectedSearchFilter(string filter);
IList<ShortcutEntry> GetShortcutList();
IList<string> GetShortcutPathList();
ShortcutEntry selectedEntry
{
get;
}
int selectedEntryIndex
{
get;
}
void ShortcutEntrySelected(ShortcutEntry shortcutEntry);
void DragEntryAndDropIntoKey(KeyCode keyCode, EventModifiers eventModifier, ShortcutEntry entry);
bool CanEntryBeAssignedToKey(KeyCode keyCode, EventModifiers eventModifier, ShortcutEntry entry);
void SetKeySelected(KeyCode keyCode, EventModifiers eventModifier);
KeyCode GetSelectedKey();
EventModifiers GetSelectedEventModifiers();
IList<ShortcutEntry> GetSelectedKeyShortcuts();
int selectedKeyDetail
{
get;
}
void NavigateTo(ShortcutEntry shortcutEntry);
void RequestRebindOfSelectedEntry(List<KeyCombination> newbinding);
void BindSelectedEntryTo(List<KeyCombination> newbinding);
IList<ShortcutEntry> GetSelectedEntryConflictsForGivenKeyCombination(List<KeyCombination> temporaryCombination);
IList<ShortcutEntry> GetShortcutsBoundTo(KeyCode keyCode, EventModifiers modifiers);
bool IsEntryPartOfConflict(ShortcutEntry shortcutEntry);
}
interface IKeyBindingStateProvider
{
BindingState GetBindingStateForKeyWithModifiers(KeyCode keyCode, EventModifiers modifiers);
bool CanBeSelected(KeyCode code);
bool IsReservedKey(KeyCode code);
bool IsModifier(KeyCode code);
EventModifiers ModifierFromKeyCode(KeyCode k);
}
[Serializable]
class SerializedShortcutManagerWindowState
{
[SerializeField]
internal string selectedCategory;
[SerializeField]
internal SearchOption searchMode;
[SerializeField]
internal string search;
[SerializeField]
internal List<KeyCombination> bindingsSearch = new List<KeyCombination>();
[SerializeField]
internal SearchCategoryFilter searchCategoryFilter = SearchCategoryFilter.SearchWithinSelectedCategory;
[SerializeField]
internal KeyCode selectedKey;
[SerializeField]
internal EventModifiers selectedModifiers;
[SerializeField]
internal Identifier selectedEntryIdentifier;
}
enum SearchCategoryFilter
{
IgnoreCategory,
SearchWithinSelectedCategory
}
class ShortcutManagerWindow : EditorWindow
{
SerializedShortcutManagerWindowState m_State = new SerializedShortcutManagerWindowState();
ShortcutManagerWindowView m_View;
ShortcutManagerWindowViewController m_ViewController;
static readonly Vector2 k_MinSizeToShowKeyboard = new Vector2(850, 400);
[RequiredByNativeCode]
static void Open() => GetWindow<ShortcutManagerWindow>();
void OnEnable()
{
var rootElement = rootVisualElement;
//Workaround for the rootVisualContainer not having a height set on AuxWindows:
rootElement.StretchToParentSize();
titleContent = new GUIContent("Shortcuts");
minSize = k_MinSizeToShowKeyboard;
maxSize = new Vector2(10000, 10000);
var directory = ShortcutIntegration.instance.directory;
var contextManager = ShortcutIntegration.instance.contextManager;
var profileManager = ShortcutIntegration.instance.profileManager;
var bindingValidator = ShortcutIntegration.instance.bindingValidator;
m_ViewController = new ShortcutManagerWindowViewController(m_State, directory, bindingValidator, profileManager, contextManager, ShortcutIntegration.instance);
m_View = new ShortcutManagerWindowView(m_ViewController, m_ViewController);
m_ViewController.SetView(m_View);
var root = m_View.GetVisualElementHierarchyRoot();
rootElement.Add(root);
m_ViewController.OnEnable();
EditorApplication.modifierKeysChanged += OnModifiersMightHaveChanged;
}
//On Windows, shift key down does not send its own KeyDown event, so we need to listen to this event to workaround that.
void OnModifiersMightHaveChanged()
{
if (focusedWindow == this)
SendEvent(EditorGUIUtility.CommandEvent(EventCommandNames.ModifierKeysChanged));
}
void OnDisable()
{
EditorApplication.modifierKeysChanged -= OnModifiersMightHaveChanged;
m_ViewController.OnDisable();
}
internal override void OnResized()
{
if (m_View.deviceContainer is null)
return;
var displayKeyboard = position.width > k_MinSizeToShowKeyboard.x &&
position.height > k_MinSizeToShowKeyboard.y
? DisplayStyle.Flex
: DisplayStyle.None;
m_View.SetKeyboardDisplay(displayKeyboard);
}
public static void ShowConflicts()
{
var win = GetWindowDontShow<ShortcutManagerWindow>();
win.m_ViewController.SelectConflictCategory();
win.ShowUtility();
}
}
}
| UnityCsReference/Modules/ShortcutManagerEditor/ShortcutManagerWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/ShortcutManagerEditor/ShortcutManagerWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 3115
} | 459 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEditor.Experimental;
using UnityEditor.UIElements.StyleSheets;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.UIElements;
using UnityEngine.UIElements.StyleSheets;
using Object = UnityEngine.Object;
namespace UnityEditor.StyleSheets
{
internal enum SkinTarget
{
Shared,
Light,
Dark
}
internal class DebugLogTimer : IDisposable
{
private System.Diagnostics.Stopwatch m_Timer;
public string msg { get; set; }
public DebugLogTimer(string m)
{
msg = m;
m_Timer = System.Diagnostics.Stopwatch.StartNew();
}
public static DebugLogTimer Start(string m)
{
return new DebugLogTimer(m);
}
public void Dispose()
{
m_Timer.Stop();
Debug.LogFormat(LogType.Log, LogOption.NoStacktrace, null, msg + " - " + m_Timer.ElapsedMilliseconds + "ms");
}
}
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static class ConverterUtils
{
public const string k_TextAlignment = "-unity-text-align";
public const string k_Border = "-unity-slice";
public const string k_Clipping = "-unity-clipping";
public const string k_ContentOffset = "-unity-content-offset";
public const string k_Overflow = "-unity-overflow";
public const string k_Height = "height";
public const string k_Width = "width";
public const string k_Font = "-unity-font";
public const string k_FontSize = "font-size";
public const string k_FontStyle = "font-style";
public const string k_FontWeight = "font-weight";
public const string k_ImagePosition = "-unity-image-position";
public const string k_Margin = "margin";
public const string k_Padding = "padding";
public const string k_RichText = "-unity-rich-text";
public const string k_StretchHeight = "-unity-stretch-height";
public const string k_StretchWidth = "-unity-stretch-width";
public const string k_WordWrap = "-unity-word-wrap";
public const string k_TextColor = "color";
public const string k_BackgroundImage = "background-image";
public const string k_ScaledBackground = "-unity-scaled-backgrounds";
public const string k_Name = "-unity-name";
public const string k_CustomAbstractGUIStyleSelectorPrefix = ".imgui-abstract-";
public const string k_CustomGUIStyleSelectorPrefix = ".imgui-style-";
public const string k_GUISettingsSelector = ".imgui-skin-settings";
public const string k_SelectionColor = "selection-color";
public const string k_CursorColor = "cursor-color";
public const string k_CursorFlashSpeed = "-unity-cursor-flash-speed";
public const string k_DoubleClickSelectsWord = "-unity-double-click-selects-word";
public const string k_TripleClickSelectsLine = "-unity-triple-click-selects-line";
public const string k_Extend = "-unity-extend";
public const string k_GeneratedSkinPath = "Assets/Editor Default Resources/Builtin Skins/Generated/Skins";
public const string k_BundleSkinPath = "Builtin Skins/Generated/Skins";
public static Dictionary<string, string> k_GuiStyleTypeNames;
public static HashSet<string> k_StyleProperties;
public static List<string> k_SkinStylePrefixes;
static ConverterUtils()
{
k_GuiStyleTypeNames = GetGUIStyleProperties().ToDictionary(p => p.Name.ToLower(), p => p.Name.Capitalize());
k_StyleProperties = new HashSet<string>();
k_StyleProperties.Add(k_TextAlignment);
foreach (var propPrefix in new[] { k_Border, k_Margin, k_Padding, k_Overflow })
{
k_StyleProperties.Add(propPrefix + "-left");
k_StyleProperties.Add(propPrefix + "-right");
k_StyleProperties.Add(propPrefix + "-top");
k_StyleProperties.Add(propPrefix + "-bottom");
}
k_StyleProperties.Add(k_Clipping);
k_StyleProperties.Add(k_ContentOffset);
k_StyleProperties.Add(k_Height);
k_StyleProperties.Add(k_Width);
k_StyleProperties.Add(k_Font);
k_StyleProperties.Add(k_FontSize);
k_StyleProperties.Add(k_FontStyle);
k_StyleProperties.Add(k_FontWeight);
k_StyleProperties.Add(k_ImagePosition);
k_StyleProperties.Add(k_RichText);
k_StyleProperties.Add(k_StretchHeight);
k_StyleProperties.Add(k_StretchWidth);
k_StyleProperties.Add(k_WordWrap);
k_StyleProperties.Add(k_TextColor);
k_StyleProperties.Add(k_BackgroundImage);
k_StyleProperties.Add(k_ScaledBackground);
k_StyleProperties.Add(k_Name);
k_StyleProperties.Add(k_SelectionColor);
k_StyleProperties.Add(k_RichText);
k_StyleProperties.Add(k_CursorColor);
k_StyleProperties.Add(k_CursorFlashSpeed);
k_StyleProperties.Add(k_DoubleClickSelectsWord);
k_StyleProperties.Add(k_TripleClickSelectsLine);
k_StyleProperties.Add(k_Extend);
k_SkinStylePrefixes = new List<string>();
k_SkinStylePrefixes.Add(k_CustomAbstractGUIStyleSelectorPrefix);
k_SkinStylePrefixes.Add(k_CustomGUIStyleSelectorPrefix);
k_SkinStylePrefixes.Add(k_GUISettingsSelector);
}
public static string ToUssString(TextAnchor anchor)
{
switch (anchor)
{
case TextAnchor.LowerCenter: return "lower-center";
case TextAnchor.LowerLeft: return "lower-left";
case TextAnchor.LowerRight: return "lower-right";
case TextAnchor.UpperCenter: return "upper-center";
case TextAnchor.UpperLeft: return "upper-left";
case TextAnchor.UpperRight: return "upper-right";
case TextAnchor.MiddleCenter: return "middle-center";
case TextAnchor.MiddleLeft: return "middle-left";
case TextAnchor.MiddleRight: return "middle-right";
}
return "";
}
public static TextAnchor ToTextAnchor(string anchor)
{
switch (anchor)
{
case "lower-center": return TextAnchor.LowerCenter;
case "lower-left": return TextAnchor.LowerLeft;
case "lower-right": return TextAnchor.LowerRight;
case "upper-center": return TextAnchor.UpperCenter;
case "upper-left": return TextAnchor.UpperLeft;
case "upper-right": return TextAnchor.UpperRight;
case "middle-center": return TextAnchor.MiddleCenter;
case "middle-left": return TextAnchor.MiddleLeft;
case "middle-right": return TextAnchor.MiddleRight;
}
return TextAnchor.LowerCenter;
}
public static string ToUssString(TextClipping clipping)
{
switch (clipping)
{
case TextClipping.Clip: return "clip";
case TextClipping.Overflow: return "overflow";
}
return "";
}
internal static TextClipping ToTextClipping(string clipping)
{
switch (clipping)
{
case "clip": return TextClipping.Clip;
case "overflow": return TextClipping.Overflow;
}
return TextClipping.Clip;
}
public static string ToUssString(ImagePosition imgPosition)
{
switch (imgPosition)
{
case ImagePosition.ImageAbove: return "image-above";
case ImagePosition.ImageLeft: return "image-left";
case ImagePosition.ImageOnly: return "image-only";
case ImagePosition.TextOnly: return "text-only";
}
return "";
}
public static ImagePosition ToImagePosition(string imgPosition)
{
switch (imgPosition)
{
case "image-above": return ImagePosition.ImageAbove;
case "image-left": return ImagePosition.ImageLeft;
case "image-only": return ImagePosition.ImageOnly;
case "text-only": return ImagePosition.TextOnly;
}
return ImagePosition.ImageAbove;
}
public static StyleSelectorPart CreateSelectorPart(string selectorStr)
{
return selectorStr[0] == '.' ? StyleSelectorPart.CreateClass(selectorStr.Substring(1)) : StyleSelectorPart.CreateType(selectorStr);
}
public static StyleSelectorPart[] GetStateRuleSelectorParts(string baseSelectorStr, string id)
{
var baseSelector = CreateSelectorPart(baseSelectorStr);
switch (id)
{
case "active":
return new[]
{
baseSelector,
StyleSelectorPart.CreatePseudoClass("hover"),
StyleSelectorPart.CreatePseudoClass("active")
};
case "focused":
return new[]
{
baseSelector,
StyleSelectorPart.CreatePseudoClass("focus")
};
case "hover":
return new[]
{
baseSelector,
StyleSelectorPart.CreatePseudoClass("hover")
};
case "onActive":
return new[]
{
baseSelector,
StyleSelectorPart.CreatePseudoClass("hover"),
StyleSelectorPart.CreatePseudoClass("active"),
StyleSelectorPart.CreatePseudoClass("checked")
};
case "onFocused":
return new[]
{
baseSelector,
StyleSelectorPart.CreatePseudoClass("hover"),
StyleSelectorPart.CreatePseudoClass("focus"),
StyleSelectorPart.CreatePseudoClass("checked")
};
case "onHover":
return new[]
{
baseSelector,
StyleSelectorPart.CreatePseudoClass("hover"),
StyleSelectorPart.CreatePseudoClass("checked")
};
case "onNormal":
return new[]
{
baseSelector,
StyleSelectorPart.CreatePseudoClass("checked")
};
default:
throw new Exception("Unsupported GUIStyleStateId: " + id);
}
}
public static string GetNoPseudoSelector(string selectorName)
{
var colonIndex = selectorName.IndexOf(":");
if (colonIndex != -1)
{
selectorName = selectorName.Substring(0, colonIndex);
}
return selectorName;
}
public static StyleComplexSelector CreateSelectorFromSource(StyleComplexSelector srcSelector, string newSelectorBase)
{
var newSelector = new StyleComplexSelector();
var newSelectorParts = srcSelector.selectors[0].parts.ToArray();
if (newSelectorBase[0] == '.')
{
newSelectorParts[0].type = StyleSelectorType.Class;
newSelectorParts[0].value = newSelectorBase.Substring(1);
}
else
{
newSelectorParts[0].type = StyleSelectorType.Type;
newSelectorParts[0].value = newSelectorBase;
}
newSelector.selectors = new[] { new StyleSelector() { previousRelationship = StyleSelectorRelationship.None, parts = newSelectorParts } };
return newSelector;
}
public static StyleComplexSelector CreateSimpleSelector(string styleName)
{
var cs = new StyleComplexSelector();
StyleSelectorPart[] parts;
CSSSpec.ParseSelector(styleName, out parts);
var selector = new StyleSelector();
selector.parts = parts;
cs.selectors = new[] { selector };
return cs;
}
public static string Capitalize(this string s)
{
if (String.IsNullOrEmpty(s))
{
return String.Empty;
}
char[] a = s.ToCharArray();
a[0] = Char.ToUpper(a[0]);
return new string(a);
}
public static string Lowerize(this string s)
{
if (String.IsNullOrEmpty(s))
{
return String.Empty;
}
char[] a = s.ToCharArray();
a[0] = Char.ToLower(a[0]);
return new string(a);
}
public static void TryAdd<K, V>(this Dictionary<K, V> dict, K key, V value)
{
if (!dict.ContainsKey(key))
{
dict.Add(key, value);
}
}
public static void Set<K, V>(this Dictionary<K, V> dict, K key, V value)
{
if (dict.ContainsKey(key))
{
dict[key] = value;
}
else
{
dict.Add(key, value);
}
}
public static void Assign(this GUISettings settings, GUISettings src)
{
settings.cursorFlashSpeed = src.cursorFlashSpeed;
settings.cursorColor = src.cursorColor;
settings.doubleClickSelectsWord = src.doubleClickSelectsWord;
settings.selectionColor = src.selectionColor;
settings.tripleClickSelectsLine = src.tripleClickSelectsLine;
}
public static void Assign(this GUIStyleState state, GUIStyleState src)
{
state.background = src.background;
state.textColor = src.textColor;
state.scaledBackgrounds = src.scaledBackgrounds.ToArray();
}
public static void Assign(this GUIStyle style, GUIStyle src)
{
style.name = src.name;
style.alignment = src.alignment;
style.border = src.border;
style.clipping = src.clipping;
style.contentOffset = src.contentOffset;
style.fixedHeight = src.fixedHeight;
style.fixedWidth = src.fixedWidth;
style.focused = src.focused;
style.fontStyle = src.fontStyle;
style.font = src.font;
style.fontSize = src.fontSize;
style.imagePosition = src.imagePosition;
style.margin = src.margin;
style.name = src.name;
style.overflow = src.overflow;
style.padding = src.padding;
style.richText = src.richText;
style.stretchHeight = src.stretchHeight;
style.stretchWidth = src.stretchWidth;
style.wordWrap = src.wordWrap;
style.active.Assign(src.active);
style.hover.Assign(src.hover);
style.normal.Assign(src.normal);
style.onActive.Assign(src.onActive);
style.onFocused.Assign(src.onFocused);
style.onHover.Assign(src.onHover);
style.onNormal.Assign(src.onNormal);
}
public static void SetToDefault(GUIStyle style)
{
var name = style.name;
style.Assign(GUIStyle.none);
style.name = name;
}
public static void Assign(this GUISkin skin, GUISkin src)
{
skin.customStyles = src.customStyles.Select(style =>
{
var newStyle = new GUIStyle();
newStyle.Assign(style);
return newStyle;
}).ToArray();
skin.font = src.font;
skin.settings.Assign(src.settings);
skin.button.Assign(src.button);
skin.box.Assign(src.box);
skin.horizontalScrollbarThumb.Assign(src.horizontalScrollbarThumb);
skin.horizontalScrollbar.Assign(src.horizontalScrollbar);
skin.horizontalScrollbarLeftButton.Assign(src.horizontalScrollbarLeftButton);
skin.horizontalScrollbarRightButton.Assign(src.horizontalScrollbarRightButton);
skin.horizontalSlider.Assign(src.horizontalSlider);
skin.horizontalSliderThumb.Assign(src.horizontalSliderThumb);
skin.label.Assign(src.label);
skin.scrollView.Assign(src.scrollView);
skin.textArea.Assign(src.textArea);
skin.textField.Assign(src.textField);
skin.toggle.Assign(src.toggle);
skin.verticalScrollbar.Assign(src.verticalScrollbar);
skin.verticalScrollbarDownButton.Assign(src.verticalScrollbarDownButton);
skin.verticalScrollbarThumb.Assign(src.verticalScrollbarThumb);
skin.verticalScrollbarUpButton.Assign(src.verticalScrollbarUpButton);
skin.verticalSlider.Assign(src.verticalSlider);
skin.verticalSliderThumb.Assign(src.verticalSliderThumb);
skin.window.Assign(src.window);
skin.name = src.name;
}
public static void SetToDefault(GUISkin skin)
{
ForEachGUIStyleProperty(skin, (name, style) => SetToDefault(style));
foreach (var style in skin.customStyles)
{
SetToDefault(style);
}
}
public static IEnumerable<PropertyInfo> GetGUIStyleProperties()
{
return typeof(GUISkin).GetProperties().Where(p => p.PropertyType == typeof(GUIStyle)).OrderBy(style => style.Name);
}
public static IEnumerable<PropertyInfo> GetGUIStateProperties()
{
return typeof(GUIStyle).GetProperties().Where(p => p.PropertyType == typeof(GUIStyleState));
}
public static StyleProperty FindProperty(this StyleComplexSelector selector, string propertyName)
{
return Array.Find(selector.rule.properties, p => p.name == propertyName);
}
public static string FindStyleName(this StyleComplexSelector selector, string selectorStr, StyleSheet sheet)
{
var property = FindProperty(selector, k_Name);
if (property == null)
{
return ToStyleName(selectorStr);
}
return sheet.ReadString(property.values[0]);
}
public static string FindExtend(this StyleComplexSelector selector, StyleSheet sheet)
{
var property = FindProperty(selector, k_Extend);
if (property == null)
{
return null;
}
return sheet.ReadString(property.values[0]);
}
public static void ForEachGUIStyleProperty(this GUISkin skin, Action<string, GUIStyle> action)
{
var styleProperties = GetGUIStyleProperties();
foreach (var property in styleProperties)
{
var style = property.GetValue(skin, null) as GUIStyle;
action(property.Name, style);
}
}
public static void ForEachGUIStateProperty(this GUIStyle skin, Action<string, GUIStyleState> action)
{
var properties = GetGUIStateProperties();
foreach (var property in properties)
{
var state = property.GetValue(skin, null) as GUIStyleState;
action(property.Name, state);
}
}
public static GUIStyle GetStyleFromSkin(this GUISkin skin, string styleName)
{
var propertyInfo = typeof(GUISkin).GetProperties().FirstOrDefault(pi => pi.Name.ToLower() == styleName.ToLower());
if (propertyInfo != null)
{
return propertyInfo.GetValue(skin, null) as GUIStyle;
}
return skin.customStyles.FirstOrDefault(s => s.name == styleName);
}
public static string EscapeSelectorName(string name)
{
return name.Replace(" ", "-").Replace(".", "-");
}
public static string ToStyleName(string selectorName)
{
// Type selector:
var lowerSelector = selectorName.ToLower();
if (k_GuiStyleTypeNames.ContainsKey(lowerSelector))
{
return lowerSelector;
}
return selectorName.Replace(k_CustomGUIStyleSelectorPrefix, "").Replace("-", " ").Replace(".", "");
}
public static string ToGUIStyleSelectorName(string guiStyleName)
{
if (k_GuiStyleTypeNames.ContainsKey(guiStyleName))
{
return EscapeSelectorName(k_GuiStyleTypeNames[guiStyleName]);
}
return k_CustomGUIStyleSelectorPrefix + EscapeSelectorName(guiStyleName);
}
public static string GetStateRuleSelectorStr(string baseSelectorStr, string id)
{
var parts = GetStateRuleSelectorParts(baseSelectorStr, id);
var sb = new StringBuilder();
StyleSheetToUss.ToUssString(StyleSelectorRelationship.None, parts, sb);
return sb.ToString();
}
public static string ToUssPropertyName(params string[] values)
{
return String.Join("-", values.Where(v => !String.IsNullOrEmpty(v)).ToArray());
}
public static T LoadResource<T>(string path) where T : Object
{
var resource = Panel.LoadResource(path, typeof(T), GUIUtility.pixelsPerPoint) as T;
if (resource == null)
{
// It might be a builtin resource:
resource = Resources.GetBuiltinResource<T>(path);
}
return resource;
}
public static T LoadResourceRequired<T>(string path) where T : Object
{
var resource = Panel.LoadResource(path, typeof(T), GUIUtility.pixelsPerPoint) as T;
if (resource == null)
{
// It might be a builtin resource:
resource = Resources.GetBuiltinResource<T>(path);
}
if (resource == null)
{
throw new Exception("Cannot load resource: " + path);
}
return resource;
}
public static bool IsPseudoSelector(string selectorStr)
{
return selectorStr.Contains(":");
}
public static bool IsCustomStyleSelector(string selectorStr)
{
return selectorStr.StartsWith(k_CustomGUIStyleSelectorPrefix) && !selectorStr.Contains(":");
}
public static bool IsAbstractStyleSelector(string selectorStr)
{
return selectorStr.StartsWith(k_CustomAbstractGUIStyleSelectorPrefix) && !selectorStr.Contains(":");
}
public static bool IsTypeStyleSelector(string guiStyleName)
{
return k_GuiStyleTypeNames.ContainsKey(guiStyleName.ToLower());
}
public static bool IsSkinStyleSelector(string guiStyleName)
{
return IsTypeStyleSelector(guiStyleName) || k_SkinStylePrefixes.Any(guiStyleName.StartsWith);
}
public static void GetFontStylePropertyValues(FontStyle style, out string fontStyle, out string fontWeight)
{
fontStyle = style == FontStyle.Italic || style == FontStyle.BoldAndItalic ? "italic" : "normal";
fontWeight = style == FontStyle.Bold || style == FontStyle.BoldAndItalic ? "bold" : "normal";
}
public static bool TryGetFontStyle(string fontStyle, string weight, out FontStyle style)
{
if (fontStyle == "italic" && weight == "bold")
{
style = FontStyle.BoldAndItalic;
return true;
}
if (fontStyle == "italic")
{
style = FontStyle.Italic;
return true;
}
if (weight == "bold")
{
style = FontStyle.Bold;
return true;
}
if (fontStyle == "normal")
{
style = FontStyle.Normal;
return true;
}
style = FontStyle.Normal;
return false;
}
public static void SelectAsset<T>(string path) where T : Object
{
var asset = ConverterUtils.LoadResource<T>(path);
if (asset)
{
EditorGUIUtility.PingObject(asset);
}
}
public static GUISkin CreateDefaultGUISkin()
{
var skin = ScriptableObject.CreateInstance<GUISkin>();
// For some strange reason, the default GUISkin is created with a customStyles array of a single null element.
// Remove this null element for testing purpose.
skin.customStyles = new GUIStyle[0];
return skin;
}
public static GUISkin LoadSkin(SkinTarget target)
{
return LoadResource<GUISkin>(GetSkinPath(target));
}
public static GUISkin LoadBundleSkin(SkinTarget target)
{
var editorAssetBundle = EditorGUIUtility.GetEditorAssetBundle();
return editorAssetBundle.LoadAsset<GUISkin>(GetSkinPath(target, true).ToLower());
}
public static void ResetSkinToPristine(GUISkin skin, SkinTarget target)
{
var pristinePath = GetSkinPath(target, true, true);
var pristineSkin = LoadResource<GUISkin>(pristinePath);
if (pristineSkin != null)
{
var originalName = skin.name;
skin.Assign(pristineSkin);
skin.name = originalName;
}
}
public static string GetSkinPath(SkinTarget target, bool bundle = false, bool pristine = false)
{
var skinName = target == SkinTarget.Dark ? "DarkSkin" : "LightSkin";
if (pristine)
{
skinName += "_Pristine";
}
return $"{(bundle ? k_BundleSkinPath : k_GeneratedSkinPath)}/{skinName}.guiskin";
}
public static string[] GetSheetPathsFromRootFolders(IEnumerable<string> rootFolders, SkinTarget target, string sheetPostFix = "")
{
var skinSheetName = $"{(target == SkinTarget.Light ? "light" : "dark")}{sheetPostFix}.uss";
var sheetPaths = rootFolders.Select(folderPath => Directory.GetFiles(EditorResources.ExpandPath(folderPath), "*.uss", SearchOption.AllDirectories))
.SelectMany(p => p)
.Where(p => p.EndsWith("common.uss") || p.EndsWith(skinSheetName))
.Select(p => p.Replace("\\", "/"))
.ToArray();
return sheetPaths;
}
public static GUISkin CreatePackageSkinFromBundleSkin(SkinTarget target)
{
var packageSkin = CreateDefaultGUISkin();
var bundleSkin = LoadBundleSkin(target);
packageSkin.Assign(bundleSkin);
ConvertToPackageAsset(packageSkin, bundleSkin);
return packageSkin;
}
public static void ConvertToPackageAsset(GUISkin packageSkin, GUISkin bundleSkin)
{
// Switch all images and font to package resources:
if (bundleSkin.font != null)
packageSkin.font = ConvertToPackageAsset(bundleSkin.font);
ConvertToPackageAsset(packageSkin.box, bundleSkin.box);
ConvertToPackageAsset(packageSkin.label, bundleSkin.label);
ConvertToPackageAsset(packageSkin.textField, bundleSkin.textField);
ConvertToPackageAsset(packageSkin.textArea, bundleSkin.textArea);
ConvertToPackageAsset(packageSkin.button, bundleSkin.button);
ConvertToPackageAsset(packageSkin.toggle, bundleSkin.toggle);
ConvertToPackageAsset(packageSkin.window, bundleSkin.window);
ConvertToPackageAsset(packageSkin.horizontalSlider, bundleSkin.horizontalSlider);
ConvertToPackageAsset(packageSkin.horizontalSliderThumb, bundleSkin.horizontalSliderThumb);
ConvertToPackageAsset(packageSkin.verticalSlider, bundleSkin.verticalSlider);
ConvertToPackageAsset(packageSkin.verticalSliderThumb, bundleSkin.verticalSliderThumb);
ConvertToPackageAsset(packageSkin.horizontalScrollbar, bundleSkin.horizontalScrollbar);
ConvertToPackageAsset(packageSkin.horizontalScrollbarThumb, bundleSkin.horizontalScrollbarThumb);
ConvertToPackageAsset(packageSkin.horizontalScrollbarLeftButton, bundleSkin.horizontalScrollbarLeftButton);
ConvertToPackageAsset(packageSkin.horizontalScrollbarRightButton, bundleSkin.horizontalScrollbarRightButton);
ConvertToPackageAsset(packageSkin.verticalScrollbar, bundleSkin.verticalScrollbar);
ConvertToPackageAsset(packageSkin.verticalScrollbarThumb, bundleSkin.verticalScrollbarThumb);
ConvertToPackageAsset(packageSkin.verticalScrollbarUpButton, bundleSkin.verticalScrollbarUpButton);
ConvertToPackageAsset(packageSkin.verticalScrollbarDownButton, bundleSkin.verticalScrollbarDownButton);
ConvertToPackageAsset(packageSkin.scrollView, bundleSkin.scrollView);
for (var i = 0; i < packageSkin.customStyles.Length; ++i)
{
var packageStyle = packageSkin.customStyles[i];
var bundleStyle = bundleSkin.customStyles[i];
ConvertToPackageAsset(packageStyle, bundleStyle);
}
}
private static T ConvertToPackageAsset<T>(T bundleAsset) where T : Object
{
var partialPath = EditorResources.GetAssetPath(bundleAsset);
return LoadResource<T>(partialPath);
}
private static void ConvertToPackageAsset(GUIStyle dst, GUIStyle src)
{
ConvertToPackageAsset(dst.normal, src.normal);
ConvertToPackageAsset(dst.active, src.active);
ConvertToPackageAsset(dst.focused, src.focused);
ConvertToPackageAsset(dst.hover, src.hover);
ConvertToPackageAsset(dst.onActive, src.onActive);
ConvertToPackageAsset(dst.onFocused, src.onFocused);
ConvertToPackageAsset(dst.onHover, src.onHover);
ConvertToPackageAsset(dst.onNormal, src.onNormal);
if (src.font != null)
dst.font = ConvertToPackageAsset(src.font);
}
private static void ConvertToPackageAsset(GUIStyleState dst, GUIStyleState src)
{
if (src.background != null)
dst.background = ConvertToPackageAsset(src.background);
if (src.scaledBackgrounds != null && src.scaledBackgrounds.Length > 0 && src.scaledBackgrounds[0] != null)
dst.scaledBackgrounds = new[] { ConvertToPackageAsset(src.scaledBackgrounds[0]) };
}
internal static StyleSheet ResolveSheets(params string[] sheetPaths)
{
var resolver = new StyleSheetResolver();
resolver.AddStyleSheets(sheetPaths);
return resolver.ResolvedSheet;
}
internal static StyleSheet ResolveSheets(params StyleSheet[] sheets)
{
var resolver = new StyleSheetResolver();
resolver.AddStyleSheets(sheets);
return resolver.ResolvedSheet;
}
internal static StyleSheetResolver ResolveFromSheetsFolder(string folder, SkinTarget target, StyleSheetResolver.ResolvingOptions options = null, string sheetPostFix = "")
{
return ResolveFromSheetsFolder(new[] { folder }, target, options, sheetPostFix);
}
internal static StyleSheetResolver ResolveFromSheetsFolder(IEnumerable<string> folders, SkinTarget target, StyleSheetResolver.ResolvingOptions options = null, string sheetPostFix = "")
{
var sheetPaths = ConverterUtils.GetSheetPathsFromRootFolders(folders, target, sheetPostFix);
if (sheetPaths.Length == 0)
{
throw new Exception("Cannot find sheets to generate skin");
}
var resolver = new StyleSheetResolver(options ?? new StyleSheetResolver.ResolvingOptions() { ThrowIfCannotResolve = true });
foreach (var sheet in sheetPaths)
{
resolver.AddStyleSheets(sheet);
}
return resolver;
}
internal static StyleSheet CompileStyleSheetContent(string styleSheetContent, bool disableValidation = true, bool reportErrors = false)
{
var importer = new StyleSheetImporterImpl();
var styleSheet = ScriptableObject.CreateInstance<StyleSheet>();
importer.disableValidation = disableValidation;
importer.Import(styleSheet, styleSheetContent);
if (reportErrors)
{
foreach (var err in importer.importErrors)
Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, styleSheet, err.ToString());
}
return styleSheet;
}
}
}
| UnityCsReference/Modules/StyleSheetsEditor/Converters/ConverterUtils.cs/0 | {
"file_path": "UnityCsReference/Modules/StyleSheetsEditor/Converters/ConverterUtils.cs",
"repo_id": "UnityCsReference",
"token_count": 15885
} | 460 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
using UsedByNativeCodeAttribute = UnityEngine.Scripting.UsedByNativeCodeAttribute;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnityEngine.Subsystems
{
[NativeType(Header = "Modules/Subsystems/Example/ExampleSubsystemDescriptor.h")]
[UsedByNativeCode]
public class ExampleSubsystemDescriptor : IntegratedSubsystemDescriptor<ExampleSubsystem>
{
public extern bool supportsEditorMode { get; }
public extern bool disableBackbufferMSAA { get; }
public extern bool stereoscopicBackbuffer { get; }
public extern bool usePBufferEGL { get; }
internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(ExampleSubsystemDescriptor exampleSubsystemDescriptor) => exampleSubsystemDescriptor.m_Ptr;
}
}
}
| UnityCsReference/Modules/Subsystems/Example/ExampleSubsystemDescriptor.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Subsystems/Example/ExampleSubsystemDescriptor.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 345
} | 461 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.SubsystemsImplementation
{
public class SubsystemProxy<TSubsystem, TProvider>
where TSubsystem : SubsystemWithProvider, new()
where TProvider : SubsystemProvider<TSubsystem>
{
public TProvider provider { get; private set; }
public bool running
{
get => provider.running;
set => provider.m_Running = value;
}
internal SubsystemProxy(TProvider provider) => this.provider = provider;
}
}
| UnityCsReference/Modules/Subsystems/SubsystemProxy.cs/0 | {
"file_path": "UnityCsReference/Modules/Subsystems/SubsystemProxy.cs",
"repo_id": "UnityCsReference",
"token_count": 240
} | 462 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.IO;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEditorInternal;
using UnityEditor.Experimental;
namespace UnityEditor
{
internal class BrushList
{
int m_SelectedBrush = 0;
Brush[] m_BrushList = null;
Hash128[] m_BrushHashes = null;
UnityEngine.Object[] m_FoldoutContent = new UnityEngine.Object[1];
GUIContent[] m_Thumnails;
Editor m_BrushEditor = null;
bool m_ShowBrushSettings = false;
// UI
Vector2 m_ScrollPos;
public int selectedIndex { get { return m_SelectedBrush; } }
internal static class Styles
{
public static GUIStyle gridList = "GridList";
public static GUIContent brushes = EditorGUIUtility.TrTextContent("Brushes");
}
public BrushList()
{
if (m_BrushList == null)
{
LoadBrushes();
UpdateSelection(0);
}
}
public void LoadBrushes()
{
// Load the textures;
var arr = new List<Brush>();
var hashes = new List<Hash128>();
int idx = 1;
Texture2D t = null;
Brush brush = null;
// Load builtin brushes from editor resources
do
{
brush = (Brush)EditorGUIUtility.Load(EditorResources.brushesPath + "builtin_brush_" + idx + ".brush");
if (brush != null && brush.m_Mask != null)
{
brush.readOnly = true;
arr.Add(brush);
hashes.Add(brush.thumbnail.imageContentsHash);
}
idx++;
}
while (brush);
// Load user created brushes from the Assets/Gizmos folder
idx = 0;
do
{
t = EditorGUIUtility.FindTexture("brush_" + idx + ".png");
if (t)
{
Brush b = Brush.CreateInstance(t, AnimationCurve.Constant(0, 1, 1), Brush.kMaxRadiusScale, true);
arr.Add(b);
hashes.Add(b.thumbnail.imageContentsHash);
}
idx++;
}
while (t);
// Load .brush files
foreach (string assetPath in AssetDatabase.FindAssets($"t:{typeof(Brush).Name}"))
{
var b = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(assetPath), typeof(Brush)) as Brush;
// We do not need to test whether b.texture is non-null because for Brush objects it is always true;
// if no mask is assigned then the default one is used.
if (b != null)
{
arr.Add(b);
hashes.Add(b.thumbnail.imageContentsHash);
}
}
m_BrushList = arr.ToArray();
m_BrushHashes = hashes.ToArray();
}
public void SelectPrevBrush()
{
if (--m_SelectedBrush < 0)
m_SelectedBrush = m_BrushList.Length - 1;
UpdateSelection(m_SelectedBrush);
}
public void SelectNextBrush()
{
if (++m_SelectedBrush >= m_BrushList.Length)
m_SelectedBrush = 0;
UpdateSelection(m_SelectedBrush);
}
public void UpdateSelection(int newSelectedBrush)
{
m_SelectedBrush = newSelectedBrush;
m_BrushEditor = Editor.CreateEditor(GetActiveBrush());
}
public Brush GetCircleBrush()
{
return m_BrushList[0];
}
public Brush GetActiveBrush()
{
if (m_SelectedBrush >= m_BrushList.Length)
m_SelectedBrush = 0;
return m_BrushList[m_SelectedBrush];
}
public bool ShowGUI()
{
bool repaint = false;
// check if we need to update our thumbnail list
if (m_Thumnails != null)
{
for (int x = 0; x < m_BrushList.Length; x++)
{
Hash128 thumbnailHash = m_BrushList[x].thumbnail.imageContentsHash;
if (m_BrushHashes[x] != thumbnailHash)
{
m_BrushHashes[x] = thumbnailHash;
m_Thumnails = null;
}
}
}
EditorGUILayout.BeginHorizontal();
GUILayout.Label(Styles.brushes, EditorStyles.boldLabel);
GUILayout.FlexibleSpace();
var b = m_BrushList != null ? GetActiveBrush() : null;
if (b != null && !b.readOnly)
{
if (GUILayout.Button("Delete Brush...")
&& EditorUtility.DisplayDialog(L10n.Tr("Delete Brush"), L10n.Tr("Deleting this brush will delete the brush asset from disk. You cannot undo this operation. Do you wish to continue?"), L10n.Tr("Yes"), L10n.Tr("No")))
{
AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(b));
LoadBrushes();
UpdateSelection(m_BrushList != null && m_SelectedBrush < m_BrushList.Length ? m_SelectedBrush : 0);
}
}
if (GUILayout.Button("New Brush..."))
CreateBrush();
EditorGUILayout.EndHorizontal();
EditorGUILayout.BeginHorizontal();
{
Rect brushPreviewRect = EditorGUILayout.GetControlRect(true, GUILayout.Width(60), GUILayout.Height(60));
if (m_BrushList != null)
{
EditorGUI.DrawTextureAlpha(brushPreviewRect, GetActiveBrush().thumbnail);
bool dummy;
m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos, GUILayout.Height(128));
var missingBrush = EditorGUIUtility.TrTextContent("No brushes defined.");
int newBrush = BrushSelectionGrid(m_SelectedBrush, m_BrushList, 32, Styles.gridList, missingBrush, out dummy);
if (newBrush != m_SelectedBrush)
{
UpdateSelection(newBrush);
repaint = true;
}
EditorGUILayout.EndScrollView();
}
}
EditorGUILayout.EndHorizontal();
return repaint;
}
public void ShowEditGUI()
{
if (selectedIndex == -1)
return;
Brush b = m_BrushList == null ? null : GetActiveBrush();
// if the brush has been deleted outside unity rebuild the brush list
if (b == null)
{
m_BrushList = null;
LoadBrushes();
UpdateSelection(0);
return;
}
if (b.readOnly)
{
EditorGUILayout.HelpBox("The brush is read-only.", MessageType.Info);
}
else if (m_BrushEditor)
{
Rect titleRect = Editor.DrawHeaderGUI(m_BrushEditor, b.name, 10f);
int id = GUIUtility.GetControlID(78901, FocusType.Passive);
Rect renderRect = EditorGUI.GetInspectorTitleBarObjectFoldoutRenderRect(titleRect);
renderRect.y = titleRect.yMax - 17f; // align with bottom
m_FoldoutContent[0] = b;
bool newVisible = EditorGUI.DoObjectFoldout(m_ShowBrushSettings, titleRect, renderRect, m_FoldoutContent, id);
// Toggle visibility
if (newVisible != m_ShowBrushSettings)
{
m_ShowBrushSettings = newVisible;
InternalEditorUtility.SetIsInspectorExpanded(b, newVisible);
}
if (m_ShowBrushSettings)
m_BrushEditor.OnInspectorGUI();
}
}
int BrushSelectionGrid(int selected, Brush[] brushes, int approxSize, GUIStyle style, GUIContent emptyString, out bool doubleClick)
{
GUILayout.BeginVertical("box", GUILayout.MinHeight(approxSize));
int retval = 0;
doubleClick = false;
if (brushes.Length != 0)
{
int columns = (int)(EditorGUIUtility.currentViewWidth - 150) / approxSize;
if (columns <= 0)
columns = 1;
int rows = (int)Mathf.Ceil((brushes.Length + columns - 1) / columns);
Rect r = GUILayoutUtility.GetAspectRect((float)columns / (float)rows);
Event evt = Event.current;
if (evt.type == EventType.MouseDown && evt.clickCount == 2 && r.Contains(evt.mousePosition))
{
doubleClick = true;
evt.Use();
}
if (m_Thumnails == null || m_Thumnails.Length != brushes.Length)
{
m_Thumnails = GUIContentFromBrush(brushes);
}
retval = GUI.SelectionGrid(r, System.Math.Min(selected, brushes.Length - 1), m_Thumnails, (int)columns, style);
}
else
GUILayout.Label(emptyString);
GUILayout.EndVertical();
return retval;
}
internal void CreateBrush()
{
ObjectSelector.get.Show(null, typeof(Texture2D), null, false, null,
selection =>
{
if (selection == null)
return;
var brushName = AssetDatabase.GenerateUniqueAssetPath(Path.Combine(ProjectWindowUtil.GetActiveFolderPath(), "NewBrush.brush"));
var newBrush = Brush.CreateInstance((Texture2D)selection, AnimationCurve.Linear(0, 0, 1, 1), Brush.kMaxRadiusScale, false);
AssetDatabase.CreateAsset(newBrush, brushName);
LoadBrushes();
int newIndex = m_BrushList != null ? System.Array.IndexOf(m_BrushList, newBrush) : -1;
if (newIndex >= 0)
UpdateSelection(newIndex);
}, null);
}
internal static GUIContent[] GUIContentFromBrush(Brush[] brushes)
{
GUIContent[] retval = new GUIContent[brushes.Length];
for (int i = 0; i < brushes.Length; i++)
retval[i] = new GUIContent(brushes[i].thumbnail, brushes[i].name);
return retval;
}
}
} //namespace
| UnityCsReference/Modules/TerrainEditor/Brush/BrushList.cs/0 | {
"file_path": "UnityCsReference/Modules/TerrainEditor/Brush/BrushList.cs",
"repo_id": "UnityCsReference",
"token_count": 5718
} | 463 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEditor;
using UnityEngine.TerrainTools;
using UnityEditor.ShortcutManagement;
namespace UnityEditor.TerrainTools
{
[FilePathAttribute("Library/TerrainTools/Stamp", FilePathAttribute.Location.ProjectFolder)]
internal class StampTool : TerrainPaintToolWithOverlays<StampTool>
{
internal const string k_ToolName = "Stamp Terrain";
public override string OnIcon => "TerrainOverlays/Stamp_On.png";
public override string OffIcon => "TerrainOverlays/Stamp.png";
[SerializeField]
float m_StampHeightTerrainSpace = 0.0f;
[SerializeField]
float m_MaxBlendAdd = 0.0f;
[Shortcut("Terrain/Stamp Terrain", typeof(TerrainToolShortcutContext), KeyCode.F7)]
static void SelectShortcut(ShortcutArguments args)
{
TerrainToolShortcutContext context = (TerrainToolShortcutContext)args.context;
context.SelectPaintToolWithOverlays<StampTool>();
}
class Styles
{
public readonly GUIContent description = EditorGUIUtility.TrTextContent("Left click to stamp the brush onto the terrain.\n\nHold control and mousewheel to adjust height.\nHold shift to invert the stamp.");
public readonly GUIContent height = EditorGUIUtility.TrTextContent("Stamp Height", "You can set the Stamp Height manually or you can hold shift and mouse wheel on the terrain to adjust it.");
public readonly GUIContent down = EditorGUIUtility.TrTextContent("Subtract", "Subtract the stamp from the terrain.");
public readonly GUIContent maxadd = EditorGUIUtility.TrTextContent("Max <--> Add", "Blend between adding the heights and taking the maximum.");
}
private static Styles m_styles;
private Styles GetStyles()
{
if (m_styles == null)
{
m_styles = new Styles();
}
return m_styles;
}
public override int IconIndex
{
get { return (int) SculptIndex.Stamp; }
}
public override TerrainCategory Category
{
get { return TerrainCategory.Sculpt; }
}
public override string GetName()
{
return k_ToolName;
}
public override string GetDescription()
{
return GetStyles().description.text;
}
public override bool HasToolSettings => true;
public override bool HasBrushMask => true;
public override bool HasBrushAttributes => true;
private void ApplyBrushInternal(PaintContext paintContext, float brushStrength, Texture brushTexture, BrushTransform brushXform, Terrain terrain, bool negate)
{
Material mat = TerrainPaintUtility.GetBuiltinPaintMaterial();
float height = m_StampHeightTerrainSpace / terrain.terrainData.size.y;
if (negate)
{
height = -height;
}
Vector4 brushParams = new Vector4(brushStrength, 0.0f, height, m_MaxBlendAdd);
mat.SetTexture("_BrushTex", brushTexture);
mat.SetVector("_BrushParams", brushParams);
TerrainPaintUtility.SetupTerrainToolMaterialProperties(paintContext, brushXform, mat);
Graphics.Blit(paintContext.sourceRenderTexture, paintContext.destinationRenderTexture, mat, (int)TerrainBuiltinPaintMaterialPasses.StampHeight);
}
public override bool OnPaint(Terrain terrain, IOnPaint editContext)
{
// ignore mouse drags
if (Event.current.type == EventType.MouseDrag)
return true;
BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.uv, editContext.brushSize, 0.0f);
PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds());
ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform, terrain, Event.current.shift);
TerrainPaintUtility.EndPaintHeightmap(paintContext, "Terrain Paint - Stamp");
return true;
}
public override void OnSceneGUI(Terrain terrain, IOnSceneGUI editContext)
{
Event evt = Event.current;
if (evt.control && (evt.type == EventType.ScrollWheel))
{
const float k_mouseWheelToHeightRatio = -0.0004f;
// we use distance to modify the scroll speed, so that when a user is up close to the brush, they get fine adjustment, and when the user is far from the brush, it adjusts quickly
m_StampHeightTerrainSpace += Event.current.delta.y * k_mouseWheelToHeightRatio * editContext.raycastHit.distance;
evt.Use();
editContext.Repaint();
}
}
public override void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext)
{
Event evt = Event.current;
// We're only doing painting operations, early out if it's not a repaint
if (evt.type != EventType.Repaint)
return;
if (editContext.hitValidTerrain)
{
BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, editContext.brushSize, 0.0f);
PaintContext paintContext = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1);
Material material = TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial();
TerrainPaintUtilityEditor.DrawBrushPreview(paintContext, TerrainBrushPreviewMode.SourceRenderTexture, editContext.brushTexture, brushXform, material, 0);
// draw result preview
{
ApplyBrushInternal(paintContext, editContext.brushStrength, editContext.brushTexture, brushXform, terrain, evt.shift);
// restore old render target
RenderTexture.active = paintContext.oldRenderTexture;
material.SetTexture("_HeightmapOrig", paintContext.sourceRenderTexture);
TerrainPaintUtilityEditor.DrawBrushPreview(paintContext, TerrainBrushPreviewMode.DestinationRenderTexture, editContext.brushTexture, brushXform, material, 1);
}
TerrainPaintUtility.ReleaseContextResources(paintContext);
}
}
public override void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext)
{
Styles styles = GetStyles();
EditorGUI.BeginChangeCheck();
{
float height = Mathf.Abs(m_StampHeightTerrainSpace);
bool stampDown = (m_StampHeightTerrainSpace < 0.0f);
height = EditorGUILayout.PowerSlider(styles.height, height, 0, terrain.terrainData.size.y, 2.0f);
stampDown = EditorGUILayout.Toggle(styles.down, stampDown);
if (EditorGUI.EndChangeCheck())
{
m_StampHeightTerrainSpace = (stampDown ? -height : height);
}
}
m_MaxBlendAdd = EditorGUILayout.Slider(styles.maxadd, m_MaxBlendAdd, 0.0f, 1.0f);
}
public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext)
{
OnToolSettingsGUI(terrain, editContext);
// show built-in brushes
int textureRez = terrain.terrainData.heightmapResolution;
editContext.ShowBrushesGUI(5, BrushGUIEditFlags.All, textureRez);
}
}
}
| UnityCsReference/Modules/TerrainEditor/PaintTools/StampTool.cs/0 | {
"file_path": "UnityCsReference/Modules/TerrainEditor/PaintTools/StampTool.cs",
"repo_id": "UnityCsReference",
"token_count": 3286
} | 464 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using UnityEngine.Internal;
using UnityEngine.Scripting;
namespace UnityEngine.TextCore.LowLevel
{
/// <summary>
/// The OpenType Layout Tables.
/// </summary>
internal enum OTL_TableType
{
/// <summary>
/// Baseline Table.
/// Provides information used to align glyphs of different scripts and sizes in a line of text,
/// whether the glyphs are in the same font or in different fonts.
/// </summary>
BASE = 0x01000,
/// <summary>
/// The Glyph Definition (GDEF) table provides various glyph properties used in OpenType Layout processing.
/// </summary>
GDEF = 0x02000,
/// <summary>
/// The Glyph Positioning table (GPOS) provides precise control over glyph placement for sophisticated text
/// layout and rendering in each script and language system that a font supports.
/// </summary>
GPOS = 0x04000,
/// <summary>
/// The Glyph Substitution (GSUB) table provides data for substition of glyphs for appropriate rendering of scripts,
/// such as cursively-connecting forms in Arabic script, or for advanced typographic effects, such as ligatures.
/// </summary>
GSUB = 0x08000,
/// <summary>
/// The Justification table (JSTF) provides font developers with additional control over glyph substitution
/// and positioning in justified text.
/// </summary>
JSTF = 0x10000,
/// <summary>
/// The Mathematical Typesetting Table.
/// Provides font-specific information necessary for math formula layout.
/// </summary>
MATH = 0x20000,
}
/// <summary>
/// The Lookup tables referenced in OpenType Layout Tables.
/// </summary>
internal enum OTL_LookupType
{
// =============================================
// GSUB - https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#gsub-header
// =============================================
/// <summary>
/// Single substitution subtable tells a client to replace a single glyph with another glyph.
/// </summary>
Single_Substitution = OTL_TableType.GSUB | 1,
/// <summary>
/// A Multiple Substitution subtable replaces a single glyph with more than one glyph,
/// as when multiple glyphs replace a single ligature.
/// </summary>
Multiple_Substitution = OTL_TableType.GSUB | 2,
/// <summary>
/// An Alternate Substitution subtable identifies any number of aesthetic alternatives
/// from which a user can choose a glyph variant to replace the input glyph. For example, if a font contains
/// four variants of the ampersand symbol, the 'cmap' table will specify the index of one of the four glyphs
/// as the default glyph index, and an AlternateSubst subtable will list the indices of the other three
/// glyphs as alternatives.
/// </summary>
Alternate_Substitution = OTL_TableType.GSUB | 3,
/// <summary>
/// A Ligature Substitution subtable identifies ligature substitutions where a single glyph
/// replaces multiple glyphs.
/// </summary>
Ligature_Substitution = OTL_TableType.GSUB | 4,
/// <summary>
/// A Contextual Substitution subtable describes glyph substitutions in context that replace one or more
/// glyphs within a certain pattern of glyphs.
/// </summary>
Contextual_Substitution = OTL_TableType.GSUB | 5,
/// <summary>
/// A Chained Contexts Substitution subtable describes glyph substitutions in context with an ability to
/// look back and/or look ahead in the sequence of glyphs.
/// </summary>
Chaining_Contextual_Substitution = OTL_TableType.GSUB | 6,
/// <summary>
/// This lookup type provides a way to access lookup subtables within the GSUB table using 32-bit offsets.
/// This is needed if the total size of the subtables exceeds the 16-bit limits of the various other offsets in the GSUB table.
/// </summary>
Extension_Substitution = OTL_TableType.GSUB | 7,
/// <summary>
/// Reverse Chaining Contextual subtable Single Substitution describes single-glyph substitutions
/// in context with an ability to look back and/or look ahead in the sequence of glyphs.
/// The major difference between this and other lookup types is that processing of input glyph sequence goes from end to start.
/// </summary>
Reverse_Chaining_Contextual_Single_Substitution = OTL_TableType.GSUB | 8,
// =============================================
// GPOS - https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#gpos-header
// =============================================
/// <summary>
/// A single adjustment positioning subtable is used to adjust the placement or advance of a single glyph, such as a subscript
/// or superscript. In addition, a SinglePos subtable is commonly used to implement lookup data for contextual positioning.
/// </summary>
Single_Adjustment = OTL_TableType.GPOS | 1,
/// <summary>
/// A pair adjustment positioning subtable is used to adjust the placement or advances of two glyphs in relation to one another.
/// </summary>
Pair_Adjustment = OTL_TableType.GPOS | 2,
/// <summary>
/// A cursive attachment positioning subtable can describe how to connect cursive fonts so that adjacent glyphs join.
/// /// </summary>
Cursive_Attachment = OTL_TableType.GPOS | 3,
/// <summary>
/// The Mark To Base attachment subtable is used to position combining mark glyphs with respect to base glyphs.
/// For example, the Arabic, Hebrew, and Thai scripts combine vowels, diacritical marks, and tone marks with base glyphs.
/// </summary>
Mark_to_Base_Attachment = OTL_TableType.GPOS | 4,
/// <summary>
/// The Mark To Ligature attachment subtable is used to position combining mark glyphs with respect to ligature base glyphs.
/// </summary>
Mark_to_Ligature_Attachment = OTL_TableType.GPOS | 5,
/// <summary>
/// Mark To Mark attachment defines the position of one mark relative to another mark as when, for example, positioning
/// tone marks with respect to vowel diacritical marks in Vietnamese.
/// </summary>
Mark_to_Mark_Attachment = OTL_TableType.GPOS | 6,
/// <summary>
/// A Contextual Positioning subtable describes glyph positioning in context so a text-processing client can adjust the
/// position of one or more glyphs within a certain pattern of glyphs.
/// </summary>
Contextual_Positioning = OTL_TableType.GPOS | 7,
/// <summary>
/// A Chained Contexts Positioning subtable describes glyph positioning in context with an ability to look back and/or
/// look ahead in the sequence of glyphs.
/// </summary>
Chaining_Contextual_Positioning = OTL_TableType.GPOS | 8,
/// <summary>
/// This lookup type provides a way to access lookup subtables within the GPOS table using 32-bit offsets.
/// This is needed if the total size of the subtables exceeds the 16-bit limits of the various other offsets in the GPOS table.
/// </summary>
Extension_Positioning = OTL_TableType.GPOS | 9,
}
[Flags]
public enum FontFeatureLookupFlags
{
None = 0x000,
//RightToLeft = 0x001,
//IgnoreBaseGlyphs = 0x002,
IgnoreLigatures = 0x004,
//IgnoreMarks = 0x008,
//UseMarkFilteringSet = 0x010,
IgnoreSpacingAdjustments = 0x100,
}
[Serializable]
internal struct OpenTypeLayoutTable
{
public List<OpenTypeLayoutScript> scripts;
public List<OpenTypeLayoutFeature> features;
[SerializeReference] public List<OpenTypeLayoutLookup> lookups;
}
[Serializable]
[DebuggerDisplay("Script = {tag}, Language Count = {languages.Count}")]
internal struct OpenTypeLayoutScript
{
public string tag;
public List<OpenTypeLayoutLanguage> languages;
}
[Serializable]
[DebuggerDisplay("Language = {tag}, Feature Count = {featureIndexes.Length}")]
internal struct OpenTypeLayoutLanguage
{
public string tag;
public uint[] featureIndexes;
//public List<OpenTypeLayoutFeature> features;
}
[Serializable]
[DebuggerDisplay("Feature = {tag}, Lookup Count = {lookupIndexes.Length}")]
internal struct OpenTypeLayoutFeature
{
public string tag;
public uint[] lookupIndexes;
//public List<OpenTypeLayoutLookup> lookups;
}
internal struct OpenTypeFeature { } // Required to prevent compilation errors on TMP 3.20.0 Preview 3.
[Serializable]
//[DebuggerDisplay("{(OTL_LookupType)lookupType}")]
internal abstract class OpenTypeLayoutLookup
{
public uint lookupType;
public uint lookupFlag;
public uint markFilteringSet;
public abstract void InitializeLookupDictionary();
public virtual void UpdateRecords(int lookupIndex, uint glyphIndex) { }
public virtual void UpdateRecords(int lookupIndex, uint glyphIndex, float emScale) { }
public virtual void UpdateRecords(int lookupIndex, List<uint> glyphIndexes) { }
public virtual void UpdateRecords(int lookupIndex, List<uint> glyphIndexes, float emScale) { }
public abstract void ClearRecords();
}
//[Serializable]
//internal class OpenTypeLayoutLookupSubTable
//{
//}
/// <summary>
/// The values used to adjust the position of a glyph or set of glyphs.
/// </summary>
[Serializable]
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public struct GlyphValueRecord : IEquatable<GlyphValueRecord>
{
/// <summary>
/// The positional adjustment that affects the horizontal bearing X of the glyph.
/// </summary>
public float xPlacement { get { return m_XPlacement; } set { m_XPlacement = value; } }
/// <summary>
/// The positional adjustment that affects the horizontal bearing Y of the glyph.
/// </summary>
public float yPlacement { get { return m_YPlacement; } set { m_YPlacement = value; } }
/// <summary>
/// The positional adjustment that affects the horizontal advance of the glyph.
/// </summary>
public float xAdvance { get { return m_XAdvance; } set { m_XAdvance = value; } }
/// <summary>
/// The positional adjustment that affects the vertical advance of the glyph.
/// </summary>
public float yAdvance { get { return m_YAdvance; } set { m_YAdvance = value; } }
// =============================================
// Private backing fields for public properties.
// =============================================
[SerializeField]
[NativeName("xPlacement")]
private float m_XPlacement;
[SerializeField]
[NativeName("yPlacement")]
private float m_YPlacement;
[SerializeField]
[NativeName("xAdvance")]
private float m_XAdvance;
[SerializeField]
[NativeName("yAdvance")]
private float m_YAdvance;
/// <summary>
/// Constructor
/// </summary>
/// <param name="xPlacement">The positional adjustment that affects the horizontal bearing X of the glyph.</param>
/// <param name="yPlacement">The positional adjustment that affects the horizontal bearing Y of the glyph.</param>
/// <param name="xAdvance">The positional adjustment that affects the horizontal advance of the glyph.</param>
/// <param name="yAdvance">The positional adjustment that affects the vertical advance of the glyph.</param>
public GlyphValueRecord(float xPlacement, float yPlacement, float xAdvance, float yAdvance)
{
m_XPlacement = xPlacement;
m_YPlacement = yPlacement;
m_XAdvance = xAdvance;
m_YAdvance = yAdvance;
}
public static GlyphValueRecord operator+(GlyphValueRecord a, GlyphValueRecord b)
{
GlyphValueRecord c;
c.m_XPlacement = a.xPlacement + b.xPlacement;
c.m_YPlacement = a.yPlacement + b.yPlacement;
c.m_XAdvance = a.xAdvance + b.xAdvance;
c.m_YAdvance = a.yAdvance + b.yAdvance;
return c;
}
[ExcludeFromDocs]
public static GlyphValueRecord operator *(GlyphValueRecord a, float emScale)
{
a.m_XPlacement = a.xPlacement * emScale;
a.m_YPlacement = a.yPlacement * emScale;
a.m_XAdvance = a.xAdvance * emScale;
a.m_YAdvance = a.yAdvance * emScale;
return a;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public bool Equals(GlyphValueRecord other)
{
return base.Equals(other);
}
public static bool operator==(GlyphValueRecord lhs, GlyphValueRecord rhs)
{
return lhs.m_XPlacement == rhs.m_XPlacement &&
lhs.m_YPlacement == rhs.m_YPlacement &&
lhs.m_XAdvance == rhs.m_XAdvance &&
lhs.m_YAdvance == rhs.m_YAdvance;
}
public static bool operator!=(GlyphValueRecord lhs, GlyphValueRecord rhs)
{
return !(lhs == rhs);
}
}
/// <summary>
/// The positional adjustment values of a glyph.
/// </summary>
[Serializable]
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
public struct GlyphAdjustmentRecord : IEquatable<GlyphAdjustmentRecord>
{
/// <summary>
/// The index of the glyph in the source font file.
/// </summary>
public uint glyphIndex { get { return m_GlyphIndex; } set { m_GlyphIndex = value; } }
/// <summary>
/// The GlyphValueRecord contains the positional adjustments of the glyph.
/// </summary>
public GlyphValueRecord glyphValueRecord { get { return m_GlyphValueRecord; } set { m_GlyphValueRecord = value; } }
// =============================================
// Private backing fields for public properties.
// =============================================
[SerializeField]
[NativeName("glyphIndex")]
private uint m_GlyphIndex;
[SerializeField]
[NativeName("glyphValueRecord")]
private GlyphValueRecord m_GlyphValueRecord;
/// <summary>
/// Constructor
/// </summary>
/// <param name="glyphIndex">The index of the glyph in the source font file.</param>
/// <param name="glyphValueRecord">The GlyphValueRecord contains the positional adjustments of the glyph.</param>
public GlyphAdjustmentRecord(uint glyphIndex, GlyphValueRecord glyphValueRecord)
{
m_GlyphIndex = glyphIndex;
m_GlyphValueRecord = glyphValueRecord;
}
[ExcludeFromDocs]
public override int GetHashCode()
{
return base.GetHashCode();
}
[ExcludeFromDocs]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
[ExcludeFromDocs]
public bool Equals(GlyphAdjustmentRecord other)
{
return base.Equals(other);
}
[ExcludeFromDocs]
public static bool operator ==(GlyphAdjustmentRecord lhs, GlyphAdjustmentRecord rhs)
{
return lhs.m_GlyphIndex == rhs.m_GlyphIndex &&
lhs.m_GlyphValueRecord == rhs.m_GlyphValueRecord;
}
[ExcludeFromDocs]
public static bool operator !=(GlyphAdjustmentRecord lhs, GlyphAdjustmentRecord rhs)
{
return !(lhs == rhs);
}
}
/// <summary>
/// The positional adjustment values for a pair of glyphs.
/// </summary>
[Serializable]
[UsedByNativeCode]
[StructLayout(LayoutKind.Sequential)]
[DebuggerDisplay("First glyphIndex = {m_FirstAdjustmentRecord.m_GlyphIndex}, Second glyphIndex = {m_SecondAdjustmentRecord.m_GlyphIndex}")]
public struct GlyphPairAdjustmentRecord : IEquatable<GlyphPairAdjustmentRecord>
{
/// <summary>
/// Contains the positional adjustment values for the first glyph.
/// </summary>
public GlyphAdjustmentRecord firstAdjustmentRecord { get { return m_FirstAdjustmentRecord; } set { m_FirstAdjustmentRecord = value; } }
/// <summary>
/// Contains the positional adjustment values for the second glyph.
/// </summary>
public GlyphAdjustmentRecord secondAdjustmentRecord { get { return m_SecondAdjustmentRecord; } set { m_SecondAdjustmentRecord = value; } }
/// <summary>
///
/// </summary>
public FontFeatureLookupFlags featureLookupFlags { get { return m_FeatureLookupFlags; } set { m_FeatureLookupFlags = value; } }
// =============================================
// Private backing fields for public properties.
// =============================================
[SerializeField]
[NativeName("firstAdjustmentRecord")]
private GlyphAdjustmentRecord m_FirstAdjustmentRecord;
[SerializeField]
[NativeName("secondAdjustmentRecord")]
private GlyphAdjustmentRecord m_SecondAdjustmentRecord;
[SerializeField]
private FontFeatureLookupFlags m_FeatureLookupFlags;
/// <summary>
/// Constructor
/// </summary>
/// <param name="firstAdjustmentRecord">First glyph adjustment record.</param>
/// <param name="secondAdjustmentRecord">Second glyph adjustment record.</param>
public GlyphPairAdjustmentRecord(GlyphAdjustmentRecord firstAdjustmentRecord, GlyphAdjustmentRecord secondAdjustmentRecord)
{
m_FirstAdjustmentRecord = firstAdjustmentRecord;
m_SecondAdjustmentRecord = secondAdjustmentRecord;
m_FeatureLookupFlags = FontFeatureLookupFlags.None;
}
[ExcludeFromDocs]
public override int GetHashCode()
{
return base.GetHashCode();
}
[ExcludeFromDocs]
public override bool Equals(object obj)
{
return base.Equals(obj);
}
[ExcludeFromDocs]
public bool Equals(GlyphPairAdjustmentRecord other)
{
return base.Equals(other);
}
[ExcludeFromDocs]
public static bool operator ==(GlyphPairAdjustmentRecord lhs, GlyphPairAdjustmentRecord rhs)
{
return lhs.m_FirstAdjustmentRecord == rhs.m_FirstAdjustmentRecord &&
lhs.m_SecondAdjustmentRecord == rhs.m_SecondAdjustmentRecord;
}
[ExcludeFromDocs]
public static bool operator !=(GlyphPairAdjustmentRecord lhs, GlyphPairAdjustmentRecord rhs)
{
return !(lhs == rhs);
}
}
}
| UnityCsReference/Modules/TextCoreFontEngine/Managed/FontFeatureCommon.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreFontEngine/Managed/FontFeatureCommon.cs",
"repo_id": "UnityCsReference",
"token_count": 7615
} | 465 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
namespace UnityEngine.TextCore.Text
{
class MaterialReferenceManager
{
static MaterialReferenceManager s_Instance;
// Dictionaries used to track Asset references.
Dictionary<int, Material> m_FontMaterialReferenceLookup = new Dictionary<int, Material>();
Dictionary<int, FontAsset> m_FontAssetReferenceLookup = new Dictionary<int, FontAsset>();
Dictionary<int, SpriteAsset> m_SpriteAssetReferenceLookup = new Dictionary<int, SpriteAsset>();
Dictionary<int, TextColorGradient> m_ColorGradientReferenceLookup = new Dictionary<int, TextColorGradient>();
/// <summary>
/// Get a singleton instance of the registry
/// </summary>
public static MaterialReferenceManager instance
{
get
{
if (s_Instance == null)
s_Instance = new MaterialReferenceManager();
return s_Instance;
}
}
/// <summary>
/// Add new font asset reference to dictionary.
/// </summary>
/// <param name="fontAsset"></param>
public static void AddFontAsset(FontAsset fontAsset)
{
instance.AddFontAssetInternal(fontAsset);
}
/// <summary>
/// Add new Font Asset reference to dictionary.
/// </summary>
/// <param name="fontAsset"></param>
void AddFontAssetInternal(FontAsset fontAsset)
{
if (m_FontAssetReferenceLookup.ContainsKey(fontAsset.hashCode)) return;
// Add reference to the font asset.
m_FontAssetReferenceLookup.Add(fontAsset.hashCode, fontAsset);
// Add reference to the font material.
m_FontMaterialReferenceLookup.Add(fontAsset.materialHashCode, fontAsset.material);
}
/// <summary>
/// Add new Sprite Asset to dictionary.
/// </summary>
/// <param name="spriteAsset"></param>
public static void AddSpriteAsset(SpriteAsset spriteAsset)
{
instance.AddSpriteAssetInternal(spriteAsset);
}
/// <summary>
/// Internal method to add a new sprite asset to the dictionary.
/// </summary>
/// <param name="spriteAsset"></param>
void AddSpriteAssetInternal(SpriteAsset spriteAsset)
{
if (m_SpriteAssetReferenceLookup.ContainsKey(spriteAsset.hashCode)) return;
// Add reference to sprite asset.
m_SpriteAssetReferenceLookup.Add(spriteAsset.hashCode, spriteAsset);
// Adding reference to the sprite asset material as well
m_FontMaterialReferenceLookup.Add(spriteAsset.hashCode, spriteAsset.material);
}
/// <summary>
/// Add new Sprite Asset to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
public static void AddSpriteAsset(int hashCode, SpriteAsset spriteAsset)
{
instance.AddSpriteAssetInternal(hashCode, spriteAsset);
}
/// <summary>
/// Internal method to add a new sprite asset to the dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
void AddSpriteAssetInternal(int hashCode, SpriteAsset spriteAsset)
{
if (m_SpriteAssetReferenceLookup.ContainsKey(hashCode)) return;
// Add reference to Sprite Asset.
m_SpriteAssetReferenceLookup.Add(hashCode, spriteAsset);
// Add reference to Sprite Asset using the asset hashcode.
m_FontMaterialReferenceLookup.Add(hashCode, spriteAsset.material);
// Compatibility check
if (spriteAsset.hashCode == 0)
spriteAsset.hashCode = hashCode;
}
/// <summary>
/// Add new Material reference to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
public static void AddFontMaterial(int hashCode, Material material)
{
instance.AddFontMaterialInternal(hashCode, material);
}
/// <summary>
/// Add new material reference to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
void AddFontMaterialInternal(int hashCode, Material material)
{
// Since this function is called after checking if the material is
// contained in the dictionary, there is no need to check again.
m_FontMaterialReferenceLookup.Add(hashCode, material);
}
/// <summary>
/// Add new Color Gradient Preset to dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
public static void AddColorGradientPreset(int hashCode, TextColorGradient spriteAsset)
{
instance.AddColorGradientPreset_Internal(hashCode, spriteAsset);
}
/// <summary>
/// Internal method to add a new Color Gradient Preset to the dictionary.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
void AddColorGradientPreset_Internal(int hashCode, TextColorGradient spriteAsset)
{
if (m_ColorGradientReferenceLookup.ContainsKey(hashCode)) return;
// Add reference to Color Gradient Preset Asset.
m_ColorGradientReferenceLookup.Add(hashCode, spriteAsset);
}
/// <summary>
/// Function to check if the font asset is already referenced.
/// </summary>
/// <param name="font"></param>
/// <returns></returns>
public bool Contains(FontAsset font)
{
return m_FontAssetReferenceLookup.ContainsKey(font.hashCode);
}
/// <summary>
/// Function to check if the sprite asset is already referenced.
/// </summary>
/// <param name="sprite"></param>
/// <returns></returns>
public bool Contains(SpriteAsset sprite)
{
return m_FontAssetReferenceLookup.ContainsKey(sprite.hashCode);
}
/// <summary>
/// Function returning the Font Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
public static bool TryGetFontAsset(int hashCode, out FontAsset fontAsset)
{
return instance.TryGetFontAssetInternal(hashCode, out fontAsset);
}
/// <summary>
/// Internal Function returning the Font Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="fontAsset"></param>
/// <returns></returns>
bool TryGetFontAssetInternal(int hashCode, out FontAsset fontAsset)
{
fontAsset = null;
return m_FontAssetReferenceLookup.TryGetValue(hashCode, out fontAsset);
}
/// <summary>
/// Function returning the Sprite Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
/// <returns></returns>
public static bool TryGetSpriteAsset(int hashCode, out SpriteAsset spriteAsset)
{
return instance.TryGetSpriteAssetInternal(hashCode, out spriteAsset);
}
/// <summary>
/// Internal function returning the Sprite Asset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="spriteAsset"></param>
/// <returns></returns>
bool TryGetSpriteAssetInternal(int hashCode, out SpriteAsset spriteAsset)
{
spriteAsset = null;
return m_SpriteAssetReferenceLookup.TryGetValue(hashCode, out spriteAsset);
}
/// <summary>
/// Function returning the Color Gradient Preset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="gradientPreset"></param>
/// <returns></returns>
public static bool TryGetColorGradientPreset(int hashCode, out TextColorGradient gradientPreset)
{
return instance.TryGetColorGradientPresetInternal(hashCode, out gradientPreset);
}
/// <summary>
/// Internal function returning the Color Gradient Preset corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="gradientPreset"></param>
/// <returns></returns>
bool TryGetColorGradientPresetInternal(int hashCode, out TextColorGradient gradientPreset)
{
gradientPreset = null;
return m_ColorGradientReferenceLookup.TryGetValue(hashCode, out gradientPreset);
}
/// <summary>
/// Function returning the Font Material corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
/// <returns></returns>
public static bool TryGetMaterial(int hashCode, out Material material)
{
return instance.TryGetMaterialInternal(hashCode, out material);
}
/// <summary>
/// Internal function returning the Font Material corresponding to the provided hash code.
/// </summary>
/// <param name="hashCode"></param>
/// <param name="material"></param>
/// <returns></returns>
bool TryGetMaterialInternal(int hashCode, out Material material)
{
material = null;
return m_FontMaterialReferenceLookup.TryGetValue(hashCode, out material);
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/MaterialReferenceManager.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/MaterialReferenceManager.cs",
"repo_id": "UnityCsReference",
"token_count": 4075
} | 466 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
#pragma warning disable 0649 // Disabled warnings.
namespace UnityEngine.TextCore.Text
{
[System.Serializable]
public class TextStyle
{
public static TextStyle NormalStyle
{
get
{
if (k_NormalStyle == null)
k_NormalStyle = new TextStyle("Normal", string.Empty, string.Empty);
return k_NormalStyle;
}
}
internal static TextStyle k_NormalStyle;
// PUBLIC PROPERTIES
/// <summary>
/// The name identifying this style. ex. <style="name">.
/// </summary>
public string name
{ get { return m_Name; } set { if (value != m_Name) m_Name = value; } }
/// <summary>
/// The hash code corresponding to the name of this style.
/// </summary>
public int hashCode
{ get { return m_HashCode; } set { if (value != m_HashCode) m_HashCode = value; } }
/// <summary>
/// The initial definition of the style. ex. <b> <u>.
/// </summary>
public string styleOpeningDefinition
{ get { return m_OpeningDefinition; } }
/// <summary>
/// The closing definition of the style. ex. </b> </u>.
/// </summary>
public string styleClosingDefinition
{ get { return m_ClosingDefinition; } }
public uint[] styleOpeningTagArray
{ get { return m_OpeningTagArray; } }
public uint[] styleClosingTagArray
{ get { return m_ClosingTagArray; } }
// PRIVATE FIELDS
[SerializeField]
private string m_Name;
[SerializeField]
private int m_HashCode;
[SerializeField]
private string m_OpeningDefinition;
[SerializeField]
private string m_ClosingDefinition;
[SerializeField]
private uint[] m_OpeningTagArray;
[SerializeField]
private uint[] m_ClosingTagArray;
[SerializeField]
internal uint[] m_OpeningTagUnicodeArray;
[SerializeField]
internal uint[] m_ClosingTagUnicodeArray;
/// <summary>
/// Constructor
/// </summary>
/// <param name="styleName">Name of the style.</param>
/// <param name="styleOpeningDefinition">Style opening definition.</param>
/// <param name="styleClosingDefinition">Style closing definition.</param>
internal TextStyle(string styleName, string styleOpeningDefinition, string styleClosingDefinition)
{
m_Name = styleName;
m_HashCode = TextUtilities.GetHashCodeCaseInSensitive(styleName);
m_OpeningDefinition = styleOpeningDefinition;
m_ClosingDefinition = styleClosingDefinition;
RefreshStyle();
}
/// <summary>
/// Function to update the content of the int[] resulting from changes to OpeningDefinition & ClosingDefinition.
/// </summary>
public void RefreshStyle()
{
m_HashCode = TextUtilities.GetHashCodeCaseInSensitive(m_Name);
int s1 = m_OpeningDefinition.Length;
m_OpeningTagArray = new uint[s1];
m_OpeningTagUnicodeArray = new uint[s1];
for (int i = 0; i < s1; i++)
{
m_OpeningTagArray[i] = m_OpeningDefinition[i];
m_OpeningTagUnicodeArray[i] = m_OpeningDefinition[i];
}
int s2 = m_ClosingDefinition.Length;
m_ClosingTagArray = new uint[s2];
m_ClosingTagUnicodeArray = new uint[s2];
for (int i = 0; i < s2; i++)
{
m_ClosingTagArray[i] = m_ClosingDefinition[i];
m_ClosingTagUnicodeArray[i] = m_ClosingDefinition[i];
}
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextStyle.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextStyle.cs",
"repo_id": "UnityCsReference",
"token_count": 1738
} | 467 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
using UnityEngine.TextCore.LowLevel;
namespace UnityEngine.TextCore.Text
{
/// <summary>
/// Helper structure to generate rendered text without string allocations.
/// </summary>
[VisibleToOtherModules("UnityEngine.UIElementsModule", "UnityEngine.IMGUIModule", "UnityEditor.GraphToolsFoundationModule")]
internal readonly struct RenderedText : IEquatable<RenderedText>, IEquatable<string>
{
public readonly string value;
public readonly int valueStart, valueLength;
public readonly string suffix;
public readonly char repeat;
public readonly int repeatCount;
public RenderedText(string value)
: this(value, 0, value?.Length ?? 0)
{}
public RenderedText(string value, string suffix)
: this(value, 0, value?.Length ?? 0, suffix)
{}
public RenderedText(string value, int start, int length, string suffix = null)
{
// clamp value arguments to valid ranges
if (string.IsNullOrEmpty(value))
{
start = 0;
length = 0;
}
else
{
if (start < 0) start = 0;
else if (start >= value.Length)
{
start = value.Length;
length = 0;
}
if (length < 0) length = 0;
else if (length > value.Length - start)
length = value.Length - start;
}
this.value = value;
this.valueStart = start;
this.valueLength = length;
this.suffix = suffix;
this.repeat = (char)0;
this.repeatCount = 0;
}
public RenderedText(char repeat, int repeatCount, string suffix = null)
{
if (repeatCount < 0)
repeatCount = 0;
this.value = null;
this.valueStart = 0;
this.valueLength = 0;
this.suffix = suffix;
this.repeat = repeat;
this.repeatCount = repeatCount;
}
public int CharacterCount
{
get
{
int count = valueLength + repeatCount;
if (suffix != null)
count += suffix.Length;
return count;
}
}
public struct Enumerator
{
private readonly RenderedText m_Source;
private const int k_ValueStage = 0;
private const int k_RepeatStage = 1;
private const int k_SuffixStage = 2;
private int m_Stage;
private int m_StageIndex;
private char m_Current;
public char Current => m_Current;
public Enumerator(in RenderedText source)
{
m_Source = source;
m_Stage = 0;
m_StageIndex = 0;
m_Current = default;
}
public bool MoveNext()
{
if (m_Stage == k_ValueStage)
{
if (m_Source.value != null)
{
int start = m_Source.valueStart;
int end = m_Source.valueStart + m_Source.valueLength;
if (m_StageIndex < start)
m_StageIndex = start;
if (m_StageIndex < end)
{
m_Current = m_Source.value[m_StageIndex];
++m_StageIndex;
return true;
}
}
m_Stage = k_ValueStage + 1;
m_StageIndex = 0;
}
if (m_Stage == k_RepeatStage)
{
if (m_StageIndex < m_Source.repeatCount)
{
m_Current = m_Source.repeat;
++m_StageIndex;
return true;
}
m_Stage = k_RepeatStage + 1;
m_StageIndex = 0;
}
if (m_Stage == k_SuffixStage)
{
if (m_Source.suffix != null && m_StageIndex < m_Source.suffix.Length)
{
m_Current = m_Source.suffix[m_StageIndex];
++m_StageIndex;
return true;
}
m_Stage = k_SuffixStage + 1;
m_StageIndex = 0;
}
return false;
}
public void Reset()
{
m_Stage = 0;
m_StageIndex = 0;
m_Current = default;
}
}
public Enumerator GetEnumerator() => new Enumerator(this);
public string CreateString()
{
var chars = new char[CharacterCount];
int writeIndex = 0;
foreach (var c in this)
chars[writeIndex++] = c;
return new string(chars);
}
public bool Equals(RenderedText other)
{
return value == other.value && valueStart == other.valueStart && valueLength == other.valueLength && suffix == other.suffix && repeat == other.repeat && repeatCount == other.repeatCount;
}
public bool Equals(string other)
{
var otherLength = other?.Length ?? 0;
var length = this.CharacterCount;
if (otherLength != length)
return false;
if (otherLength == 0) // both empty
return true;
int compIndex = 0;
foreach (var c in this)
// ReSharper disable once PossibleNullReferenceException
if (c != other[compIndex++])
return false;
return true;
}
public override bool Equals(object obj)
{
return (obj is string otherString && Equals(otherString)) ||
(obj is RenderedText otherRenderedText && Equals(otherRenderedText));
}
public override int GetHashCode()
{
return HashCode.Combine(value, valueStart, valueLength, suffix, repeat, repeatCount);
}
}
[Serializable]
struct MeshExtents
{
public Vector2 min;
public Vector2 max;
public MeshExtents(Vector2 min, Vector2 max)
{
this.min = min;
this.max = max;
}
public override string ToString()
{
string s = "Min (" + min.x.ToString("f2") + ", " + min.y.ToString("f2") + ") Max (" + max.x.ToString("f2") + ", " + max.y.ToString("f2") + ")";
return s;
}
}
struct XmlTagAttribute
{
public int nameHashCode;
public TagValueType valueType;
public int valueStartIndex;
public int valueLength;
public int valueHashCode;
}
internal struct RichTextTagAttribute
{
public int nameHashCode;
public int valueHashCode;
public TagValueType valueType;
public int valueStartIndex;
public int valueLength;
public TagUnitType unitType;
}
// TODO TextProcessingElement is defined twice in TMP...
[System.Diagnostics.DebuggerDisplay("Unicode ({unicode}) '{(char)unicode}'")]
internal struct TextProcessingElement
{
public TextProcessingElementType elementType;
public uint unicode;
public int stringIndex;
public int length;
}
/// <summary>
///
/// </summary>
struct TextBackingContainer
{
public uint[] Text
{
get { return m_Array; }
}
public int Capacity
{
get { return m_Array.Length; }
}
public int Count
{
get { return m_Count; }
set { m_Count = value; }
}
private uint[] m_Array;
private int m_Count;
public uint this[int index]
{
get { return m_Array[index]; }
set
{
if (index >= m_Array.Length)
Resize(index);
m_Array[index] = value;
}
}
public TextBackingContainer(int size)
{
m_Array = new uint[size];
m_Count = 0;
}
public void Resize(int size)
{
size = Mathf.NextPowerOfTwo(size + 1);
Array.Resize(ref m_Array, size);
}
}
internal struct CharacterSubstitution
{
public int index;
public uint unicode;
public CharacterSubstitution(int index, uint unicode)
{
this.index = index;
this.unicode = unicode;
}
}
/// <summary>
///
/// </summary>
internal struct Offset
{
public float left { get { return m_Left; } set { m_Left = value; } }
public float right { get { return m_Right; } set { m_Right = value; } }
public float top { get { return m_Top; } set { m_Top = value; } }
public float bottom { get { return m_Bottom; } set { m_Bottom = value; } }
public float horizontal { get { return m_Left; } set { m_Left = value; m_Right = value; } }
public float vertical { get { return m_Top; } set { m_Top = value; m_Bottom = value; } }
/// <summary>
///
/// </summary>
public static Offset zero { get { return k_ZeroOffset; } }
// =============================================
// Private backing fields for public properties.
// =============================================
float m_Left;
float m_Right;
float m_Top;
float m_Bottom;
static readonly Offset k_ZeroOffset = new Offset(0F, 0F, 0F, 0F);
/// <summary>
///
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <param name="top"></param>
/// <param name="bottom"></param>
public Offset(float left, float right, float top, float bottom)
{
m_Left = left;
m_Right = right;
m_Top = top;
m_Bottom = bottom;
}
/// <summary>
///
/// </summary>
/// <param name="horizontal"></param>
/// <param name="vertical"></param>
public Offset(float horizontal, float vertical)
{
m_Left = horizontal;
m_Right = horizontal;
m_Top = vertical;
m_Bottom = vertical;
}
public static bool operator ==(Offset lhs, Offset rhs)
{
return lhs.m_Left == rhs.m_Left &&
lhs.m_Right == rhs.m_Right &&
lhs.m_Top == rhs.m_Top &&
lhs.m_Bottom == rhs.m_Bottom;
}
public static bool operator !=(Offset lhs, Offset rhs)
{
return !(lhs == rhs);
}
public static Offset operator *(Offset a, float b)
{
return new Offset(a.m_Left * b, a.m_Right * b, a.m_Top * b, a.m_Bottom * b);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public bool Equals(Offset other)
{
return base.Equals(other);
}
}
/// <summary>
///
/// </summary>
internal struct HighlightState
{
public Color32 color;
public Offset padding;
public HighlightState(Color32 color, Offset padding)
{
this.color = color;
this.padding = padding;
}
public static bool operator ==(HighlightState lhs, HighlightState rhs)
{
return lhs.color.r == rhs.color.r &&
lhs.color.g == rhs.color.g &&
lhs.color.b == rhs.color.b &&
lhs.color.a == rhs.color.a &&
lhs.padding == rhs.padding;
}
public static bool operator !=(HighlightState lhs, HighlightState rhs)
{
return !(lhs == rhs);
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public bool Equals(HighlightState other)
{
return base.Equals(other);
}
}
// Structure used for Word Wrapping which tracks the state of execution when the last space or carriage return character was encountered.
struct WordWrapState
{
public int previousWordBreak;
public int totalCharacterCount;
public int visibleCharacterCount;
public int visibleSpaceCount;
public int visibleSpriteCount;
public int visibleLinkCount;
public int firstCharacterIndex;
public int firstVisibleCharacterIndex;
public int lastCharacterIndex;
public int lastVisibleCharIndex;
public int lineNumber;
public float maxCapHeight;
public float maxAscender;
public float maxDescender;
public float maxLineAscender;
public float maxLineDescender;
public float startOfLineAscender;
public float xAdvance;
public float preferredWidth;
public float preferredHeight;
public float previousLineScale;
public float pageAscender;
public int wordCount;
public FontStyles fontStyle;
public float fontScale;
public float fontScaleMultiplier;
public int italicAngle;
public float currentFontSize;
public float baselineOffset;
public float lineOffset;
public TextInfo textInfo;
public LineInfo lineInfo;
public Color32 vertexColor;
public Color32 underlineColor;
public Color32 strikethroughColor;
public Color32 highlightColor;
public HighlightState highlightState;
public FontStyleStack basicStyleStack;
public TextProcessingStack<int> italicAngleStack;
public TextProcessingStack<Color32> colorStack;
public TextProcessingStack<Color32> underlineColorStack;
public TextProcessingStack<Color32> strikethroughColorStack;
public TextProcessingStack<Color32> highlightColorStack;
public TextProcessingStack<HighlightState> highlightStateStack;
public TextProcessingStack<TextColorGradient> colorGradientStack;
public TextProcessingStack<float> sizeStack;
public TextProcessingStack<float> indentStack;
public TextProcessingStack<TextFontWeight> fontWeightStack;
public TextProcessingStack<int> styleStack;
public TextProcessingStack<float> baselineStack;
public TextProcessingStack<int> actionStack;
public TextProcessingStack<MaterialReference> materialReferenceStack;
public TextProcessingStack<TextAlignment> lineJustificationStack;
public int lastBaseGlyphIndex;
public int spriteAnimationId;
public FontAsset currentFontAsset;
public SpriteAsset currentSpriteAsset;
public Material currentMaterial;
public int currentMaterialIndex;
public Extents meshExtents;
public bool tagNoParsing;
public bool isNonBreakingSpace;
public bool isDrivenLineSpacing;
public Vector3 fxScale;
public Quaternion fxRotation;
}
[VisibleToOtherModules("UnityEngine.IMGUIModule", "UnityEngine.UIElementsModule")]
internal static class TextGeneratorUtilities
{
public static readonly Vector2 largePositiveVector2 = new Vector2(2147483647, 2147483647);
public static readonly Vector2 largeNegativeVector2 = new Vector2(-214748364, -214748364);
public const float largePositiveFloat = 32767;
public const float largeNegativeFloat = -32767;
const int
k_DoubleQuotes = 34,
k_GreaterThan = 62,
k_ZeroWidthSpace = 0x200B;
/// <summary>
/// Table used to convert character to uppercase.
/// </summary>
const string k_LookupStringU = "-------------------------------- !-#$%&-()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[-]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~-";
public static bool Approximately(float a, float b)
{
return (b - 0.0001f) < a && a < (b + 0.0001f);
}
/// <summary>
/// Method to convert Hex color values to Color32
/// </summary>
/// <param name="hexChars"></param>
/// <param name="tagCount"></param>
/// <returns></returns>
public static Color32 HexCharsToColor(char[] hexChars, int tagCount)
{
if (tagCount == 4)
{
byte r = (byte)(HexToInt(hexChars[1]) * 16 + HexToInt(hexChars[1]));
byte g = (byte)(HexToInt(hexChars[2]) * 16 + HexToInt(hexChars[2]));
byte b = (byte)(HexToInt(hexChars[3]) * 16 + HexToInt(hexChars[3]));
return new Color32(r, g, b, 255);
}
if (tagCount == 5)
{
byte r = (byte)(HexToInt(hexChars[1]) * 16 + HexToInt(hexChars[1]));
byte g = (byte)(HexToInt(hexChars[2]) * 16 + HexToInt(hexChars[2]));
byte b = (byte)(HexToInt(hexChars[3]) * 16 + HexToInt(hexChars[3]));
byte a = (byte)(HexToInt(hexChars[4]) * 16 + HexToInt(hexChars[4]));
return new Color32(r, g, b, a);
}
if (tagCount == 7)
{
byte r = (byte)(HexToInt(hexChars[1]) * 16 + HexToInt(hexChars[2]));
byte g = (byte)(HexToInt(hexChars[3]) * 16 + HexToInt(hexChars[4]));
byte b = (byte)(HexToInt(hexChars[5]) * 16 + HexToInt(hexChars[6]));
return new Color32(r, g, b, 255);
}
if (tagCount == 9)
{
byte r = (byte)(HexToInt(hexChars[1]) * 16 + HexToInt(hexChars[2]));
byte g = (byte)(HexToInt(hexChars[3]) * 16 + HexToInt(hexChars[4]));
byte b = (byte)(HexToInt(hexChars[5]) * 16 + HexToInt(hexChars[6]));
byte a = (byte)(HexToInt(hexChars[7]) * 16 + HexToInt(hexChars[8]));
return new Color32(r, g, b, a);
}
if (tagCount == 10)
{
byte r = (byte)(HexToInt(hexChars[7]) * 16 + HexToInt(hexChars[7]));
byte g = (byte)(HexToInt(hexChars[8]) * 16 + HexToInt(hexChars[8]));
byte b = (byte)(HexToInt(hexChars[9]) * 16 + HexToInt(hexChars[9]));
return new Color32(r, g, b, 255);
}
if (tagCount == 11)
{
byte r = (byte)(HexToInt(hexChars[7]) * 16 + HexToInt(hexChars[7]));
byte g = (byte)(HexToInt(hexChars[8]) * 16 + HexToInt(hexChars[8]));
byte b = (byte)(HexToInt(hexChars[9]) * 16 + HexToInt(hexChars[9]));
byte a = (byte)(HexToInt(hexChars[10]) * 16 + HexToInt(hexChars[10]));
return new Color32(r, g, b, a);
}
if (tagCount == 13)
{
byte r = (byte)(HexToInt(hexChars[7]) * 16 + HexToInt(hexChars[8]));
byte g = (byte)(HexToInt(hexChars[9]) * 16 + HexToInt(hexChars[10]));
byte b = (byte)(HexToInt(hexChars[11]) * 16 + HexToInt(hexChars[12]));
return new Color32(r, g, b, 255);
}
if (tagCount == 15)
{
byte r = (byte)(HexToInt(hexChars[7]) * 16 + HexToInt(hexChars[8]));
byte g = (byte)(HexToInt(hexChars[9]) * 16 + HexToInt(hexChars[10]));
byte b = (byte)(HexToInt(hexChars[11]) * 16 + HexToInt(hexChars[12]));
byte a = (byte)(HexToInt(hexChars[13]) * 16 + HexToInt(hexChars[14]));
return new Color32(r, g, b, a);
}
return new Color32(255, 255, 255, 255);
}
/// <summary>
/// Method to convert Hex Color values to Color32
/// </summary>
/// <param name="hexChars"></param>
/// <param name="startIndex"></param>
/// <param name="length"></param>
/// <returns></returns>
public static Color32 HexCharsToColor(char[] hexChars, int startIndex, int length)
{
if (length == 7)
{
byte r = (byte)(HexToInt(hexChars[startIndex + 1]) * 16 + HexToInt(hexChars[startIndex + 2]));
byte g = (byte)(HexToInt(hexChars[startIndex + 3]) * 16 + HexToInt(hexChars[startIndex + 4]));
byte b = (byte)(HexToInt(hexChars[startIndex + 5]) * 16 + HexToInt(hexChars[startIndex + 6]));
return new Color32(r, g, b, 255);
}
if (length == 9)
{
byte r = (byte)(HexToInt(hexChars[startIndex + 1]) * 16 + HexToInt(hexChars[startIndex + 2]));
byte g = (byte)(HexToInt(hexChars[startIndex + 3]) * 16 + HexToInt(hexChars[startIndex + 4]));
byte b = (byte)(HexToInt(hexChars[startIndex + 5]) * 16 + HexToInt(hexChars[startIndex + 6]));
byte a = (byte)(HexToInt(hexChars[startIndex + 7]) * 16 + HexToInt(hexChars[startIndex + 8]));
return new Color32(r, g, b, a);
}
return new Color32(255, 255, 255, 255);
}
/// <summary>
/// Method to convert Hex to Int
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static uint HexToInt(char hex)
{
switch (hex)
{
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'A':
return 10;
case 'B':
return 11;
case 'C':
return 12;
case 'D':
return 13;
case 'E':
return 14;
case 'F':
return 15;
case 'a':
return 10;
case 'b':
return 11;
case 'c':
return 12;
case 'd':
return 13;
case 'e':
return 14;
case 'f':
return 15;
}
return 15;
}
/// <summary>
/// Extracts a float value from char[] assuming we know the position of the start, end and decimal point.
/// </summary>
/// <param name="chars"></param>
/// <param name="startIndex"></param>
/// <param name="length"></param>
/// <returns></returns>
public static float ConvertToFloat(char[] chars, int startIndex, int length)
{
int lastIndex;
return ConvertToFloat(chars, startIndex, length, out lastIndex);
}
/// <summary>
/// Extracts a float value from char[] given a start index and length.
/// </summary>
/// <param name="chars"></param> The Char[] containing the numerical sequence.
/// <param name="startIndex"></param> The index of the start of the numerical sequence.
/// <param name="length"></param> The length of the numerical sequence.
/// <param name="lastIndex"></param> Index of the last character in the validated sequence.
/// <returns></returns>
public static float ConvertToFloat(char[] chars, int startIndex, int length, out int lastIndex)
{
if (startIndex == 0)
{
lastIndex = 0;
return largeNegativeFloat;
}
int endIndex = startIndex + length;
bool isIntegerValue = true;
float decimalPointMultiplier = 0;
// Set value multiplier checking the first character to determine if we are using '+' or '-'
int valueSignMultiplier = 1;
if (chars[startIndex] == '+')
{
valueSignMultiplier = 1;
startIndex += 1;
}
else if (chars[startIndex] == '-')
{
valueSignMultiplier = -1;
startIndex += 1;
}
float value = 0;
for (int i = startIndex; i < endIndex; i++)
{
uint c = chars[i];
if (c >= '0' && c <= '9' || c == '.')
{
if (c == '.')
{
isIntegerValue = false;
decimalPointMultiplier = 0.1f;
continue;
}
//Calculate integer and floating point value
if (isIntegerValue)
value = value * 10 + (c - 48) * valueSignMultiplier;
else
{
value = value + (c - 48) * decimalPointMultiplier * valueSignMultiplier;
decimalPointMultiplier *= 0.1f;
}
}
else if (c == ',')
{
if (i + 1 < endIndex && chars[i + 1] == ' ')
lastIndex = i + 1;
else
lastIndex = i;
return value;
}
}
lastIndex = endIndex;
return value;
}
/// <summary>
/// Function to pack scale information in the UV2 Channel.
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="scale"></param>
/// <returns></returns>
public static Vector2 PackUV(float x, float y, float scale)
{
Vector2 output;
output.x = (int)(x * 511);
output.y = (int)(y * 511);
output.x = (output.x * 4096) + output.y;
output.y = scale;
return output;
}
// /// <summary>
// /// Method to store the content of a string into an integer array.
// /// </summary>
// /// <param name="sourceText"></param>
// /// <param name="charBuffer"></param>
// /// <param name="styleStack"></param>
// /// <param name="generationSettings"></param>
// public static void StringToCharArray(string sourceText, ref int[] charBuffer, ref TextProcessingStack<int> styleStack, TextGenerationSettings generationSettings)
// {
// if (sourceText == null)
// {
// charBuffer[0] = 0;
// return;
// }
//
// if (charBuffer == null)
// charBuffer = new int[8];
//
// // Clear the Style stack.
// styleStack.SetDefault(0);
//
// int writeIndex = 0;
//
// for (int i = 0; i < sourceText.Length; i++)
// {
// if (sourceText[i] == 92 && sourceText.Length > i + 1)
// {
// switch ((int)sourceText[i + 1])
// {
// case 85: // \U00000000 for UTF-32 Unicode
// if (sourceText.Length > i + 9)
// {
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = GetUtf32(sourceText, i + 2);
// i += 9;
// writeIndex += 1;
// continue;
// }
// break;
// case 92: // \ escape
// if (!generationSettings.parseControlCharacters)
// break;
//
// if (sourceText.Length <= i + 2)
// break;
//
// if (writeIndex + 2 > charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = sourceText[i + 1];
// charBuffer[writeIndex + 1] = sourceText[i + 2];
// i += 2;
// writeIndex += 2;
// continue;
// case 110: // \n LineFeed
// if (!generationSettings.parseControlCharacters)
// break;
//
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = (char)10;
// i += 1;
// writeIndex += 1;
// continue;
// case 114: // \r
// if (!generationSettings.parseControlCharacters)
// break;
//
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = (char)13;
// i += 1;
// writeIndex += 1;
// continue;
// case 116: // \t Tab
// if (!generationSettings.parseControlCharacters)
// break;
//
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = (char)9;
// i += 1;
// writeIndex += 1;
// continue;
// case 117: // \u0000 for UTF-16 Unicode
// if (sourceText.Length > i + 5)
// {
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = (char)GetUtf16(sourceText, i + 2);
// i += 5;
// writeIndex += 1;
// continue;
// }
// break;
// }
// }
//
// // Handle UTF-32 in the input text (string). // Not sure this is needed //
// if (Char.IsHighSurrogate(sourceText[i]) && Char.IsLowSurrogate(sourceText[i + 1]))
// {
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = Char.ConvertToUtf32(sourceText[i], sourceText[i + 1]);
// i += 1;
// writeIndex += 1;
// continue;
// }
//
// //// Handle inline replacement of <stlye> and <br> tags.
// if (sourceText[i] == 60 && generationSettings.richText)
// {
// if (IsTagName(ref sourceText, "<BR>", i))
// {
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = 10;
// writeIndex += 1;
// i += 3;
//
// continue;
// }
// if (IsTagName(ref sourceText, "<STYLE=", i))
// {
// int srcOffset;
// if (ReplaceOpeningStyleTag(ref sourceText, i, out srcOffset, ref charBuffer, ref writeIndex, ref styleStack, ref generationSettings))
// {
// i = srcOffset;
// continue;
// }
// }
// else if (IsTagName(ref sourceText, "</STYLE>", i))
// {
// ReplaceClosingStyleTag(ref charBuffer, ref writeIndex, ref styleStack, ref generationSettings);
//
// // Strip </style> even if style is invalid.
// i += 7;
// continue;
// }
// }
//
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = sourceText[i];
// writeIndex += 1;
// }
//
// if (writeIndex == charBuffer.Length)
// ResizeInternalArray(ref charBuffer);
//
// charBuffer[writeIndex] = (char)0;
// }
public static void ResizeInternalArray<T>(ref T[] array)
{
int size = Mathf.NextPowerOfTwo(array.Length + 1);
Array.Resize(ref array, size);
}
public static void ResizeInternalArray<T>(ref T[] array, int size)
{
size = Mathf.NextPowerOfTwo(size + 1);
Array.Resize(ref array, size);
}
/// <summary>
/// Method to check for a matching rich text tag.
/// </summary>
/// <param name="text"></param>
/// <param name="tag"></param>
/// <param name="index"></param>
/// <returns></returns>
static bool IsTagName(ref string text, string tag, int index)
{
if (text.Length < index + tag.Length)
return false;
for (int i = 0; i < tag.Length; i++)
{
if (TextUtilities.ToUpperFast(text[index + i]) != tag[i])
return false;
}
return true;
}
/// <summary>
/// Method to check for a matching rich text tag.
/// </summary>
/// <param name="text"></param>
/// <param name="tag"></param>
/// <param name="index"></param>
/// <returns></returns>
static bool IsTagName(ref int[] text, string tag, int index)
{
if (text.Length < index + tag.Length)
return false;
for (int i = 0; i < tag.Length; i++)
{
if (TextUtilities.ToUpperFast((char)text[index + i]) != tag[i])
return false;
}
return true;
}
internal static void InsertOpeningTextStyle(TextStyle style, ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Return if we don't have a valid style.
if (style == null)
return;
// Increase style depth
textStyleStackDepth += 1;
// Push style hashcode onto stack
textStyleStacks[textStyleStackDepth].Push(style.hashCode);
// Replace <style> tag with opening definition
uint[] styleDefinition = style.styleOpeningTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth -= 1;
}
internal static void InsertClosingTextStyle(TextStyle style, ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Return if we don't have a valid style.
if (style == null) return;
// Increase style depth
textStyleStackDepth += 1;
// Push style hashcode onto stack
textStyleStacks[textStyleStackDepth].Push(style.hashCode);
uint[] styleDefinition = style.styleClosingTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth -= 1;
}
/// <summary>
/// Method to handle inline replacement of style tag by opening style definition.
/// </summary>
/// <param name="sourceText"></param>
/// <param name="srcIndex"></param>
/// <param name="srcOffset"></param>
/// <param name="charBuffer"></param>
/// <param name="writeIndex"></param>
/// <returns></returns>
public static bool ReplaceOpeningStyleTag(ref TextBackingContainer sourceText, int srcIndex, out int srcOffset, ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Validate <style> tag.
int styleHashCode = GetStyleHashCode(ref sourceText, srcIndex + 7, out srcOffset);
TextStyle style = GetStyle(generationSettings, styleHashCode);
// Return if we don't have a valid style.
if (style == null || srcOffset == 0) return false;
// Increase style depth
textStyleStackDepth += 1;
// Push style hashcode onto stack
textStyleStacks[textStyleStackDepth].Push(style.hashCode);
// Replace <style> tag with opening definition
uint[] styleDefinition = style.styleOpeningTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth -= 1;
return true;
}
/// <summary>
/// Method to handle inline replacement of style tag by opening style definition.
/// </summary>
/// <param name="sourceText"></param>
/// <param name="srcIndex"></param>
/// <param name="srcOffset"></param>
/// <param name="charBuffer"></param>
/// <param name="writeIndex"></param>
/// <returns></returns>
public static void ReplaceOpeningStyleTag(ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Get style from the Style Stack
int styleHashCode = textStyleStacks[textStyleStackDepth + 1].Pop();
TextStyle style = GetStyle(generationSettings, styleHashCode);
// Return if we don't have a valid style.
if (style == null) return;
// Increase style depth
textStyleStackDepth += 1;
// Replace <style> tag with opening definition
uint[] styleDefinition = style.styleOpeningTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth -= 1;
}
/// <summary>
/// Method to handle inline replacement of style tag by opening style definition.
/// </summary>
/// <param name="sourceText"></param>
/// <param name="srcIndex"></param>
/// <param name="srcOffset"></param>
/// <param name="charBuffer"></param>
/// <param name="writeIndex"></param>
/// <returns></returns>
static bool ReplaceOpeningStyleTag(ref uint[] sourceText, int srcIndex, out int srcOffset, ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Validate <style> tag.
int styleHashCode = GetStyleHashCode(ref sourceText, srcIndex + 7, out srcOffset);
TextStyle style = GetStyle(generationSettings, styleHashCode);
// Return if we don't have a valid style.
if (style == null || srcOffset == 0) return false;
// Increase style depth
textStyleStackDepth += 1;
// Push style hashcode onto stack
textStyleStacks[textStyleStackDepth].Push(style.hashCode);
// Replace <style> tag with opening definition
uint[] styleDefinition = style.styleOpeningTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth -= 1;
return true;
}
/// <summary>
/// Method to handle inline replacement of style tag by closing style definition.
/// </summary>
/// <param name="sourceText"></param>
/// <param name="srcIndex"></param>
/// <param name="charBuffer"></param>
/// <param name="writeIndex"></param>
/// <returns></returns>
public static void ReplaceClosingStyleTag(ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Get style from the Style Stack
int styleHashCode = textStyleStacks[textStyleStackDepth + 1].Pop();
TextStyle style = GetStyle(generationSettings, styleHashCode);
// Return if we don't have a valid style.
if (style == null) return;
// Increase style depth
textStyleStackDepth += 1;
// Replace <style> tag with opening definition
uint[] styleDefinition = style.styleClosingTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth -= 1;
}
/// <summary>
///
/// </summary>
/// <param name="style"></param>
/// <param name="srcIndex"></param>
/// <param name="charBuffer"></param>
/// <param name="writeIndex"></param>
/// <returns></returns>
internal static void InsertOpeningStyleTag(TextStyle style, ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Return if we don't have a valid style.
if (style == null) return;
textStyleStacks[0].Push(style.hashCode);
// Replace <style> tag with opening definition
uint[] styleDefinition = style.styleOpeningTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth = 0;
}
/// <summary>
///
/// </summary>
/// <param name="charBuffer"></param>
/// <param name="writeIndex"></param>
internal static void InsertClosingStyleTag(ref TextProcessingElement[] charBuffer, ref int writeIndex, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
// Get style from the Style Stack
int styleHashCode = textStyleStacks[0].Pop();
TextStyle style = GetStyle(generationSettings, styleHashCode);
// Replace <style> tag with opening definition
uint[] styleDefinition = style.styleClosingTagArray;
InsertTextStyleInTextProcessingArray(ref charBuffer, ref writeIndex, styleDefinition, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
textStyleStackDepth = 0;
}
private static void InsertTextStyleInTextProcessingArray(ref TextProcessingElement[] charBuffer, ref int writeIndex, uint[] styleDefinition, ref int textStyleStackDepth, ref TextProcessingStack<int>[] textStyleStacks, ref TextGenerationSettings generationSettings)
{
var tagNoParsing = generationSettings.tagNoParsing;
int styleLength = styleDefinition.Length;
// Make sure text processing buffer is of sufficient size
if (writeIndex + styleLength >= charBuffer.Length)
ResizeInternalArray(ref charBuffer, writeIndex + styleLength);
for (int i = 0; i < styleLength; i++)
{
uint c = styleDefinition[i];
if (c == '\\' && i + 1 < styleLength)
{
switch (styleDefinition[i + 1])
{
case '\\':
i += 1;
break;
case 'n':
c = 10;
i += 1;
break;
case 'r':
break;
case 't':
break;
case 'u':
// UTF16 format is "\uFF00" or u + 2 hex pairs.
if (i + 5 < styleLength)
{
c = GetUTF16(styleDefinition, i + 2);
i += 5;
}
break;
case 'U':
// UTF32 format is "\UFF00FF00" or U + 4 hex pairs.
if (i + 9 < styleLength)
{
c = GetUTF32(styleDefinition, i + 2);
i += 9;
}
break;
}
}
if (c == '<')
{
int hashCode = GetMarkupTagHashCode(styleDefinition, i + 1);
switch ((MarkupTag)hashCode)
{
case MarkupTag.NO_PARSE:
tagNoParsing = true;
break;
case MarkupTag.SLASH_NO_PARSE:
tagNoParsing = false;
break;
case MarkupTag.BR:
if (tagNoParsing) break;
charBuffer[writeIndex].unicode = 10;
writeIndex += 1;
i += 3;
continue;
case MarkupTag.CR:
if (tagNoParsing) break;
charBuffer[writeIndex].unicode = 13;
writeIndex += 1;
i += 3;
continue;
case MarkupTag.NBSP:
if (tagNoParsing) break;
charBuffer[writeIndex].unicode = 160;
writeIndex += 1;
i += 5;
continue;
case MarkupTag.ZWSP:
if (tagNoParsing) break;
charBuffer[writeIndex].unicode = 0x200B;
writeIndex += 1;
i += 5;
continue;
case MarkupTag.ZWJ:
if (tagNoParsing) break;
charBuffer[writeIndex].unicode = 0x200D;
writeIndex += 1;
i += 4;
continue;
case MarkupTag.SHY:
if (tagNoParsing) break;
charBuffer[writeIndex].unicode = 0xAD;
writeIndex += 1;
i += 4;
continue;
case MarkupTag.STYLE:
if (tagNoParsing) break;
if (ReplaceOpeningStyleTag(ref styleDefinition, i, out int offset, ref charBuffer, ref writeIndex, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings))
{
i = offset;
continue;
}
break;
case MarkupTag.SLASH_STYLE:
if (tagNoParsing) break;
ReplaceClosingStyleTag(ref charBuffer, ref writeIndex, ref textStyleStackDepth, ref textStyleStacks, ref generationSettings);
i += 7;
continue;
}
// Validate potential text markup element
// if (TryGetTextMarkupElement(tagDefinition, ref i, out TextProcessingElement markupElement))
// {
// m_TextProcessingArray[writeIndex] = markupElement;
// writeIndex += 1;
// continue;
// }
}
// Lookup character and glyph data
// TODO: Add future implementation for character and glyph lookups
charBuffer[writeIndex].unicode = c;
writeIndex += 1;
}
}
public static TextStyle GetStyle(TextGenerationSettings generationSetting, int hashCode)
{
TextStyle style = null;
TextStyleSheet styleSheet = generationSetting.styleSheet;
// Get Style from Style Sheet potentially assigned to text object.
if (styleSheet != null)
{
style = styleSheet.GetStyle(hashCode);
if (style != null)
return style;
}
// Use Global Style Sheet (if exists)
styleSheet = generationSetting.textSettings.defaultStyleSheet;
if (styleSheet != null)
style = styleSheet.GetStyle(hashCode);
return style;
}
/// <summary>
/// Get Hashcode for a given tag.
/// </summary>
/// <param name="text"></param>
/// <param name="index"></param>
/// <param name="closeIndex"></param>
/// <returns></returns>
public static int GetStyleHashCode(ref uint[] text, int index, out int closeIndex)
{
int hashCode = 0;
closeIndex = 0;
for (int i = index; i < text.Length; i++)
{
// Skip quote '"' character
if (text[i] == k_DoubleQuotes) continue;
// Break at '>'
if (text[i] == k_GreaterThan) { closeIndex = i; break; }
hashCode = (hashCode << 5) + hashCode ^ ToUpperASCIIFast((char)text[i]);
}
return hashCode;
}
/// <summary>
/// Get Hashcode for a given tag.
/// </summary>
/// <param name="text"></param>
/// <param name="index"></param>
/// <param name="closeIndex"></param>
/// <returns></returns>
public static int GetStyleHashCode(ref TextBackingContainer text, int index, out int closeIndex)
{
int hashCode = 0;
closeIndex = 0;
for (int i = index; i < text.Capacity; i++)
{
// Skip quote '"' character
if (text[i] == k_DoubleQuotes) continue;
// Break at '>'
if (text[i] == k_GreaterThan) { closeIndex = i; break; }
hashCode = (hashCode << 5) + hashCode ^ ToUpperASCIIFast((char)text[i]);
}
return hashCode;
}
public static uint GetUTF16(uint[] text, int i)
{
uint unicode = 0;
unicode += HexToInt((char)text[i]) << 12;
unicode += HexToInt((char)text[i + 1]) << 8;
unicode += HexToInt((char)text[i + 2]) << 4;
unicode += HexToInt((char)text[i + 3]);
return unicode;
}
public static uint GetUTF16(TextBackingContainer text, int i)
{
uint unicode = 0;
unicode += HexToInt((char)text[i]) << 12;
unicode += HexToInt((char)text[i + 1]) << 8;
unicode += HexToInt((char)text[i + 2]) << 4;
unicode += HexToInt((char)text[i + 3]);
return unicode;
}
public static uint GetUTF32(uint[] text, int i)
{
uint unicode = 0;
unicode += HexToInt((char)text[i]) << 28;
unicode += HexToInt((char)text[i + 1]) << 24;
unicode += HexToInt((char)text[i + 2]) << 20;
unicode += HexToInt((char)text[i + 3]) << 16;
unicode += HexToInt((char)text[i + 4]) << 12;
unicode += HexToInt((char)text[i + 5]) << 8;
unicode += HexToInt((char)text[i + 6]) << 4;
unicode += HexToInt((char)text[i + 7]);
return unicode;
}
public static uint GetUTF32(TextBackingContainer text, int i)
{
uint unicode = 0;
unicode += HexToInt((char)text[i]) << 28;
unicode += HexToInt((char)text[i + 1]) << 24;
unicode += HexToInt((char)text[i + 2]) << 20;
unicode += HexToInt((char)text[i + 3]) << 16;
unicode += HexToInt((char)text[i + 4]) << 12;
unicode += HexToInt((char)text[i + 5]) << 8;
unicode += HexToInt((char)text[i + 6]) << 4;
unicode += HexToInt((char)text[i + 7]);
return unicode;
}
/// <summary>
/// Get Hashcode for a given tag.
/// </summary>
/// <param name="text"></param>
/// <param name="index"></param>
/// <param name="closeIndex"></param>
/// <returns></returns>
static int GetTagHashCode(ref int[] text, int index, out int closeIndex)
{
int hashCode = 0;
closeIndex = 0;
for (int i = index; i < text.Length; i++)
{
// Skip quote '"' character
if (text[i] == 34)
continue;
// Break at '>'
if (text[i] == 62)
{
closeIndex = i;
break;
}
hashCode = (hashCode << 5) + hashCode ^ (int)TextUtilities.ToUpperASCIIFast((char)text[i]);
}
return hashCode;
}
/// <summary>
/// Get Hashcode for a given tag.
/// </summary>
/// <param name="text"></param>
/// <param name="index"></param>
/// <param name="closeIndex"></param>
/// <returns></returns>
static int GetTagHashCode(ref string text, int index, out int closeIndex)
{
int hashCode = 0;
closeIndex = 0;
for (int i = index; i < text.Length; i++)
{
// Skip quote '"' character
if (text[i] == 34)
continue;
// Break at '>'
if (text[i] == 62)
{
closeIndex = i;
break;
}
hashCode = (hashCode << 5) + hashCode ^ (int)TextUtilities.ToUpperASCIIFast(text[i]);
}
return hashCode;
}
/// <summary>
/// Store vertex attributes into the appropriate TMP_MeshInfo.
/// </summary>
/// <param name="i"></param>
/// <param name="generationSettings"></param>
/// <param name="textInfo"></param>
public static void FillCharacterVertexBuffers(int i, bool convertToLinearSpace, TextGenerationSettings generationSettings, TextInfo textInfo)
{
int materialIndex = textInfo.textElementInfo[i].materialReferenceIndex;
int indexX4 = textInfo.meshInfo[materialIndex].vertexCount;
// Check to make sure our current mesh buffer allocations can hold these new Quads.
if (indexX4 >= textInfo.meshInfo[materialIndex].vertexBufferSize)
textInfo.meshInfo[materialIndex].ResizeMeshInfo(Mathf.NextPowerOfTwo((indexX4 + 4) / 4), generationSettings.isIMGUI);
TextElementInfo[] textElementInfoArray = textInfo.textElementInfo;
textInfo.textElementInfo[i].vertexIndex = indexX4;
// Setup Vertices for Characters
if (generationSettings.inverseYAxis)
{
Vector3 axisOffset;
axisOffset.x = 0;
axisOffset.y = generationSettings.screenRect.height;
axisOffset.z = 0;
Vector3 position = textElementInfoArray[i].vertexBottomLeft.position;
position.y *= -1;
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].position = position + axisOffset;
position = textElementInfoArray[i].vertexTopLeft.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].position = position + axisOffset;
position = textElementInfoArray[i].vertexTopRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].position = position + axisOffset;
position = textElementInfoArray[i].vertexBottomRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].position = position + axisOffset;
}
else
{
textInfo.meshInfo[materialIndex].vertices[0 + indexX4] = position + axisOffset;
position = textElementInfoArray[i].vertexTopLeft.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertices[1 + indexX4] = position + axisOffset;
position = textElementInfoArray[i].vertexTopRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertices[2 + indexX4] = position + axisOffset;
position = textElementInfoArray[i].vertexBottomRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertices[3 + indexX4] = position + axisOffset;
}
}
else
{
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].position = textElementInfoArray[i].vertexBottomLeft.position;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].position = textElementInfoArray[i].vertexTopLeft.position;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].position = textElementInfoArray[i].vertexTopRight.position;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].position = textElementInfoArray[i].vertexBottomRight.position;
}
else
{
textInfo.meshInfo[materialIndex].vertices[0 + indexX4] = textElementInfoArray[i].vertexBottomLeft.position;
textInfo.meshInfo[materialIndex].vertices[1 + indexX4] = textElementInfoArray[i].vertexTopLeft.position;
textInfo.meshInfo[materialIndex].vertices[2 + indexX4] = textElementInfoArray[i].vertexTopRight.position;
textInfo.meshInfo[materialIndex].vertices[3 + indexX4] = textElementInfoArray[i].vertexBottomRight.position;
}
}
// Setup UVS0
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].uv0 = textElementInfoArray[i].vertexBottomLeft.uv;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].uv0 = textElementInfoArray[i].vertexTopLeft.uv;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].uv0 = textElementInfoArray[i].vertexTopRight.uv;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].uv0 = textElementInfoArray[i].vertexBottomRight.uv;
}
else
{
textInfo.meshInfo[materialIndex].uvs0[0 + indexX4] = textElementInfoArray[i].vertexBottomLeft.uv;
textInfo.meshInfo[materialIndex].uvs0[1 + indexX4] = textElementInfoArray[i].vertexTopLeft.uv;
textInfo.meshInfo[materialIndex].uvs0[2 + indexX4] = textElementInfoArray[i].vertexTopRight.uv;
textInfo.meshInfo[materialIndex].uvs0[3 + indexX4] = textElementInfoArray[i].vertexBottomRight.uv;
}
// Setup UVS2
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].uv2 = textElementInfoArray[i].vertexBottomLeft.uv2;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].uv2 = textElementInfoArray[i].vertexTopLeft.uv2;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].uv2 = textElementInfoArray[i].vertexTopRight.uv2;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].uv2 = textElementInfoArray[i].vertexBottomRight.uv2;
}
else
{
textInfo.meshInfo[materialIndex].uvs2[0 + indexX4] = textElementInfoArray[i].vertexBottomLeft.uv2;
textInfo.meshInfo[materialIndex].uvs2[1 + indexX4] = textElementInfoArray[i].vertexTopLeft.uv2;
textInfo.meshInfo[materialIndex].uvs2[2 + indexX4] = textElementInfoArray[i].vertexTopRight.uv2;
textInfo.meshInfo[materialIndex].uvs2[3 + indexX4] = textElementInfoArray[i].vertexBottomRight.uv2;
}
// setup Vertex Colors
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomLeft.color) : textElementInfoArray[i].vertexBottomLeft.color;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopLeft.color) : textElementInfoArray[i].vertexTopLeft.color;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopRight.color) : textElementInfoArray[i].vertexTopRight.color;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomRight.color) : textElementInfoArray[i].vertexBottomRight.color;
}
else
{
textInfo.meshInfo[materialIndex].colors32[0 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomLeft.color) : textElementInfoArray[i].vertexBottomLeft.color;
textInfo.meshInfo[materialIndex].colors32[1 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopLeft.color) : textElementInfoArray[i].vertexTopLeft.color;
textInfo.meshInfo[materialIndex].colors32[2 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopRight.color) : textElementInfoArray[i].vertexTopRight.color;
textInfo.meshInfo[materialIndex].colors32[3 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomRight.color) : textElementInfoArray[i].vertexBottomRight.color;
}
textInfo.meshInfo[materialIndex].vertexCount = indexX4 + 4;
}
/// <summary>
/// Fill Vertex Buffers for Sprites
/// </summary>
/// <param name="i"></param>
/// <param name="generationSettings"></param>
/// <param name="textInfo"></param>
public static void FillSpriteVertexBuffers(int i, bool convertToLinearSpace, TextGenerationSettings generationSettings, TextInfo textInfo)
{
int materialIndex = textInfo.textElementInfo[i].materialReferenceIndex;
int indexX4 = textInfo.meshInfo[materialIndex].vertexCount;
textInfo.meshInfo[materialIndex].applySDF = false;
TextElementInfo[] textElementInfoArray = textInfo.textElementInfo;
textInfo.textElementInfo[i].vertexIndex = indexX4;
// Handle potential axis inversion
if (generationSettings.inverseYAxis)
{
Vector3 axisOffset;
axisOffset.x = 0;
axisOffset.y = generationSettings.screenRect.height;
axisOffset.z = 0;
Vector3 position = textElementInfoArray[i].vertexBottomLeft.position;
position.y *= -1;
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].position = position + axisOffset;
position = textElementInfoArray[i].vertexTopLeft.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].position = position + axisOffset;
position = textElementInfoArray[i].vertexTopRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].position = position + axisOffset;
position = textElementInfoArray[i].vertexBottomRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].position = position + axisOffset;
}
else
{
textInfo.meshInfo[materialIndex].vertices[0 + indexX4] = position + axisOffset;
position = textElementInfoArray[i].vertexTopLeft.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertices[1 + indexX4] = position + axisOffset;
position = textElementInfoArray[i].vertexTopRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertices[2 + indexX4] = position + axisOffset;
position = textElementInfoArray[i].vertexBottomRight.position;
position.y *= -1;
textInfo.meshInfo[materialIndex].vertices[3 + indexX4] = position + axisOffset;
}
}
else
{
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].position = textElementInfoArray[i].vertexBottomLeft.position;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].position = textElementInfoArray[i].vertexTopLeft.position;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].position = textElementInfoArray[i].vertexTopRight.position;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].position = textElementInfoArray[i].vertexBottomRight.position;
}
else
{
textInfo.meshInfo[materialIndex].vertices[0 + indexX4] = textElementInfoArray[i].vertexBottomLeft.position;
textInfo.meshInfo[materialIndex].vertices[1 + indexX4] = textElementInfoArray[i].vertexTopLeft.position;
textInfo.meshInfo[materialIndex].vertices[2 + indexX4] = textElementInfoArray[i].vertexTopRight.position;
textInfo.meshInfo[materialIndex].vertices[3 + indexX4] = textElementInfoArray[i].vertexBottomRight.position;
}
}
// Setup UVS0
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].uv0 = textElementInfoArray[i].vertexBottomLeft.uv;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].uv0 = textElementInfoArray[i].vertexTopLeft.uv;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].uv0 = textElementInfoArray[i].vertexTopRight.uv;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].uv0 = textElementInfoArray[i].vertexBottomRight.uv;
}
else
{
textInfo.meshInfo[materialIndex].uvs0[0 + indexX4] = textElementInfoArray[i].vertexBottomLeft.uv;
textInfo.meshInfo[materialIndex].uvs0[1 + indexX4] = textElementInfoArray[i].vertexTopLeft.uv;
textInfo.meshInfo[materialIndex].uvs0[2 + indexX4] = textElementInfoArray[i].vertexTopRight.uv;
textInfo.meshInfo[materialIndex].uvs0[3 + indexX4] = textElementInfoArray[i].vertexBottomRight.uv;
}
// Setup UVS2
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].uv2 = textElementInfoArray[i].vertexBottomLeft.uv2;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].uv2 = textElementInfoArray[i].vertexTopLeft.uv2;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].uv2 = textElementInfoArray[i].vertexTopRight.uv2;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].uv2 = textElementInfoArray[i].vertexBottomRight.uv2;
}
else
{
textInfo.meshInfo[materialIndex].uvs2[0 + indexX4] = textElementInfoArray[i].vertexBottomLeft.uv2;
textInfo.meshInfo[materialIndex].uvs2[1 + indexX4] = textElementInfoArray[i].vertexTopLeft.uv2;
textInfo.meshInfo[materialIndex].uvs2[2 + indexX4] = textElementInfoArray[i].vertexTopRight.uv2;
textInfo.meshInfo[materialIndex].uvs2[3 + indexX4] = textElementInfoArray[i].vertexBottomRight.uv2;
}
// setup Vertex Colors
if (textInfo.vertexDataLayout == VertexDataLayout.VBO)
{
textInfo.meshInfo[materialIndex].vertexData[0 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomLeft.color) : textElementInfoArray[i].vertexBottomLeft.color;
textInfo.meshInfo[materialIndex].vertexData[1 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopLeft.color) : textElementInfoArray[i].vertexTopLeft.color;
textInfo.meshInfo[materialIndex].vertexData[2 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopRight.color) : textElementInfoArray[i].vertexTopRight.color;
textInfo.meshInfo[materialIndex].vertexData[3 + indexX4].color = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomRight.color) : textElementInfoArray[i].vertexBottomRight.color;
}
else
{
textInfo.meshInfo[materialIndex].colors32[0 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomLeft.color) : textElementInfoArray[i].vertexBottomLeft.color;
textInfo.meshInfo[materialIndex].colors32[1 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopLeft.color) : textElementInfoArray[i].vertexTopLeft.color;
textInfo.meshInfo[materialIndex].colors32[2 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexTopRight.color) : textElementInfoArray[i].vertexTopRight.color;
textInfo.meshInfo[materialIndex].colors32[3 + indexX4] = convertToLinearSpace ? GammaToLinear(textElementInfoArray[i].vertexBottomRight.color) : textElementInfoArray[i].vertexBottomRight.color;
}
textInfo.meshInfo[materialIndex].vertexCount = indexX4 + 4;
}
// Function to offset vertices position to account for line spacing changes.
public static void AdjustLineOffset(int startIndex, int endIndex, float offset, TextInfo textInfo)
{
Vector3 vertexOffset = new Vector3(0, offset, 0);
for (int i = startIndex; i <= endIndex; i++)
{
textInfo.textElementInfo[i].bottomLeft -= vertexOffset;
textInfo.textElementInfo[i].topLeft -= vertexOffset;
textInfo.textElementInfo[i].topRight -= vertexOffset;
textInfo.textElementInfo[i].bottomRight -= vertexOffset;
textInfo.textElementInfo[i].ascender -= vertexOffset.y;
textInfo.textElementInfo[i].baseLine -= vertexOffset.y;
textInfo.textElementInfo[i].descender -= vertexOffset.y;
if (textInfo.textElementInfo[i].isVisible)
{
textInfo.textElementInfo[i].vertexBottomLeft.position -= vertexOffset;
textInfo.textElementInfo[i].vertexTopLeft.position -= vertexOffset;
textInfo.textElementInfo[i].vertexTopRight.position -= vertexOffset;
textInfo.textElementInfo[i].vertexBottomRight.position -= vertexOffset;
}
}
}
/// <summary>
/// Function to increase the size of the Line Extents Array.
/// </summary>
/// <param name="size"></param>
/// <param name="textInfo"></param>
public static void ResizeLineExtents(int size, TextInfo textInfo)
{
size = size > 1024 ? size + 256 : Mathf.NextPowerOfTwo(size + 1);
LineInfo[] tempLineInfo = new LineInfo[size];
for (int i = 0; i < size; i++)
{
if (i < textInfo.lineInfo.Length)
tempLineInfo[i] = textInfo.lineInfo[i];
else
{
tempLineInfo[i].lineExtents.min = largePositiveVector2;
tempLineInfo[i].lineExtents.max = largeNegativeVector2;
tempLineInfo[i].ascender = largeNegativeFloat;
tempLineInfo[i].descender = largePositiveFloat;
}
}
textInfo.lineInfo = tempLineInfo;
}
public static FontStyles LegacyStyleToNewStyle(FontStyle fontStyle)
{
switch (fontStyle)
{
case FontStyle.Bold:
return FontStyles.Bold;
case FontStyle.Italic:
return FontStyles.Italic;
case FontStyle.BoldAndItalic:
return FontStyles.Bold | FontStyles.Italic;
default:
return FontStyles.Normal;
}
}
public static TextAlignment LegacyAlignmentToNewAlignment(TextAnchor anchor)
{
switch (anchor)
{
case TextAnchor.UpperLeft:
return TextAlignment.TopLeft;
case TextAnchor.UpperCenter:
return TextAlignment.TopCenter;
case TextAnchor.UpperRight:
return TextAlignment.TopRight;
case TextAnchor.MiddleLeft:
return TextAlignment.MiddleLeft;
case TextAnchor.MiddleCenter:
return TextAlignment.MiddleCenter;
case TextAnchor.MiddleRight:
return TextAlignment.MiddleRight;
case TextAnchor.LowerLeft:
return TextAlignment.BottomLeft;
case TextAnchor.LowerCenter:
return TextAlignment.BottomCenter;
case TextAnchor.LowerRight:
return TextAlignment.BottomRight;
default:
return TextAlignment.TopLeft;
}
}
[VisibleToOtherModules("UnityEngine.UIElementsModule")]
internal static UnityEngine.TextCore.HorizontalAlignment GetHorizontalAlignment(TextAnchor anchor)
{
switch (anchor)
{
case TextAnchor.LowerLeft:
case TextAnchor.MiddleLeft:
case TextAnchor.UpperLeft:
return UnityEngine.TextCore.HorizontalAlignment.Left;
case TextAnchor.LowerCenter:
case TextAnchor.MiddleCenter:
case TextAnchor.UpperCenter:
return UnityEngine.TextCore.HorizontalAlignment.Center;
case TextAnchor.LowerRight:
case TextAnchor.MiddleRight:
case TextAnchor.UpperRight:
return UnityEngine.TextCore.HorizontalAlignment.Right;
default:
return UnityEngine.TextCore.HorizontalAlignment.Left;
}
}
[VisibleToOtherModules("UnityEngine.UIElementsModule")]
internal static UnityEngine.TextCore.VerticalAlignment GetVerticalAlignment(TextAnchor anchor)
{
switch (anchor)
{
case TextAnchor.LowerLeft:
case TextAnchor.LowerCenter:
case TextAnchor.LowerRight:
return UnityEngine.TextCore.VerticalAlignment.Bottom;
case TextAnchor.MiddleLeft:
case TextAnchor.MiddleCenter:
case TextAnchor.MiddleRight:
return UnityEngine.TextCore.VerticalAlignment.Middle;
case TextAnchor.UpperLeft:
case TextAnchor.UpperCenter:
case TextAnchor.UpperRight:
return UnityEngine.TextCore.VerticalAlignment.Top;
default:
return UnityEngine.TextCore.VerticalAlignment.Top;
}
}
public static uint ConvertToUTF32(uint highSurrogate, uint lowSurrogate)
{
return ((highSurrogate - CodePoint.HIGH_SURROGATE_START) * 0x400) + ((lowSurrogate - CodePoint.LOW_SURROGATE_START) + CodePoint.UNICODE_PLANE01_START);
}
/// <summary>
///
/// </summary>
/// <param name="styleDefinition"></param>
/// <param name="readIndex"></param>
/// <returns></returns>
public static int GetMarkupTagHashCode(TextBackingContainer styleDefinition, int readIndex)
{
int hashCode = 0;
int maxReadIndex = readIndex + 16;
int styleDefinitionLength = styleDefinition.Capacity;
for (; readIndex < maxReadIndex && readIndex < styleDefinitionLength; readIndex++)
{
uint c = styleDefinition[readIndex];
if (c == '>' || c == '=' || c == ' ')
return hashCode;
hashCode = ((hashCode << 5) + hashCode) ^ (int)ToUpperASCIIFast(c);
}
return hashCode;
}
/// <summary>
///
/// </summary>
/// <param name="tagDefinition"></param>
/// <param name="readIndex"></param>
/// <returns></returns>
public static int GetMarkupTagHashCode(uint[] styleDefinition, int readIndex)
{
int hashCode = 0;
int maxReadIndex = readIndex + 16;
int tagDefinitionLength = styleDefinition.Length;
for (; readIndex < maxReadIndex && readIndex < tagDefinitionLength; readIndex++)
{
uint c = styleDefinition[readIndex];
if (c == '>' || c == '=' || c == ' ')
return hashCode;
hashCode = ((hashCode << 5) + hashCode) ^ (int)ToUpperASCIIFast((uint)c);
}
return hashCode;
}
/// <summary>
/// Get uppercase version of this ASCII character.
/// </summary>
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static char ToUpperASCIIFast(char c)
{
if (c > k_LookupStringU.Length - 1)
return c;
return k_LookupStringU[c];
}
/// <summary>
/// Get uppercase version of this ASCII character.
/// </summary>
//[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint ToUpperASCIIFast(uint c)
{
if (c > k_LookupStringU.Length - 1)
return c;
return k_LookupStringU[(int)c];
}
/// <summary>
/// Get uppercase version of this ASCII character.
/// </summary>
public static char ToUpperFast(char c)
{
if (c > k_LookupStringU.Length - 1)
return c;
return k_LookupStringU[c];
}
/// <summary>
/// Method which returns the number of parameters used in a tag attribute and populates an array with such values.
/// </summary>
/// <param name="chars">Char[] containing the tag attribute and data</param>
/// <param name="startIndex">The index of the first char of the data</param>
/// <param name="length">The length of the data</param>
/// <param name="parameters">The number of parameters contained in the Char[]</param>
/// <returns></returns>
public static int GetAttributeParameters(char[] chars, int startIndex, int length, ref float[] parameters)
{
int endIndex = startIndex;
int attributeCount = 0;
while (endIndex < startIndex + length)
{
parameters[attributeCount] = ConvertToFloat(chars, startIndex, length, out endIndex);
length -= (endIndex - startIndex) + 1;
startIndex = endIndex + 1;
attributeCount += 1;
}
return attributeCount;
}
public static bool IsBitmapRendering(GlyphRenderMode glyphRenderMode)
{
return glyphRenderMode == GlyphRenderMode.RASTER || glyphRenderMode == GlyphRenderMode.RASTER_HINTED || glyphRenderMode == GlyphRenderMode.SMOOTH || glyphRenderMode == GlyphRenderMode.SMOOTH_HINTED;
}
public static bool IsBaseGlyph(uint c)
{
return !(c >= 0x300 && c <= 0x36F || c >= 0x1AB0 && c <= 0x1AFF || c >= 0x1DC0 && c <= 0x1DFF || c >= 0x20D0 && c <= 0x20FF || c >= 0xFE20 && c <= 0xFE2F ||
// Thai Marks
c == 0xE31 || c >= 0xE34 && c <= 0xE3A || c >= 0xE47 && c <= 0xE4E ||
// Hebrew Marks
c >= 0x591 && c <= 0x5BD || c == 0x5BF || c >= 0x5C1 && c <= 0x5C2 || c >= 0x5C4 && c <= 0x5C5 || c == 0x5C7 ||
// Arabic Marks
c >= 0x610 && c <= 0x61A || c >= 0x64B && c <= 0x65F || c == 0x670 || c >= 0x6D6 && c <= 0x6DC || c >= 0x6DF && c <= 0x6E4 || c >= 0x6E7 && c <= 0x6E8 || c >= 0x6EA && c <= 0x6ED ||
c >= 0x8D3 && c <= 0x8E1 || c >= 0x8E3 && c <= 0x8FF ||
c >= 0xFBB2 && c <= 0xFBC1
);
}
public static Color MinAlpha(this Color c1, Color c2)
{
float a = c1.a < c2.a ? c1.a : c2.a;
return new Color(c1.r, c1.g, c1.b, a);
}
internal static Color32 GammaToLinear(Color32 c)
{
return new Color32(GammaToLinear(c.r), GammaToLinear(c.g), GammaToLinear(c.b), c.a);
}
static byte GammaToLinear(byte value)
{
float v = value / 255f;
if (v <= 0.04045f)
return (byte)(v / 12.92f * 255f);
if (v < 1.0f)
return (byte)(Mathf.Pow((v + 0.055f) / 1.055f, 2.4f) * 255);
if (v == 1.0f)
return 255;
return (byte)(Mathf.Pow(v, 2.2f) * 255);
}
public static bool IsValidUTF16(TextBackingContainer text, int index)
{
for (int i = 0; i < 4; i++)
{
uint c = text[index + i];
if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'))
return false;
}
return true;
}
public static bool IsValidUTF32(TextBackingContainer text, int index)
{
for (int i = 0; i < 8; i++)
{
uint c = text[index + i];
if (!(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c >= 'A' && c <= 'F'))
return false;
}
return true;
}
internal static bool IsEmoji(uint c)
{
return /*c == 0x23 || c == 0x2A || c >= 0x30 && c <= 0x39 || c == 0xA9 || c == 0xAE || */
c == 0x200D || c == 0x203C || c == 0x2049 || c == 0x20E3 || c == 0x2122 || c == 0x2139 || c >= 0x2194 && c <= 0x2199 || c >= 0x21A9 && c <= 0x21AA || c >= 0x231A && c <= 0x231B || c == 0x2328 || c == 0x2388 || c == 0x23CF || c >= 0x23E9 && c <= 0x23F3 || c >= 0x23F8 && c <= 0x23FA || c == 0x24C2 || c >= 0x25AA && c <= 0x25AB || c == 0x25B6 || c == 0x25C0 || c >= 0x25FB && c <= 0x25FE || c >= 0x2600 && c <= 0x2605 || c >= 0x2607 && c <= 0x2612 || c >= 0x2614 && c <= 0x2685 || c >= 0x2690 && c <= 0x2705 || c >= 0x2708 && c <= 0x2712 || c == 0x2714 || c == 0x2716 || c == 0x271D || c == 0x2721 || c == 0x2728 || c >= 0x2733 && c <= 0x2734 || c == 0x2744 || c == 0x2747 || c == 0x274C || c == 0x274E || c >= 0x2753 && c <= 0x2755 || c == 0x2757 || c >= 0x2763 && c <= 0x2767 || c >= 0x2795 && c <= 0x2797 || c == 0x27A1 || c == 0x27B0 || c == 0x27BF || c >= 0x2934 && c <= 0x2935 || c >= 0x2B05 && c <= 0x2B07 || c >= 0x2B1B && c <= 0x2B1C || c == 0x2B50 || c == 0x2B55 ||
c == 0x3030 || c == 0x303D || c == 0x3297 || c == 0x3299 ||
c == 0xFE0F ||
c >= 0x1F000 && c <= 0x1F0FF || c >= 0x1F10D && c <= 0x1F10F || c == 0x1F12F || c >= 0x1F16C && c <= 0x1F171 || c >= 0x1F17E && c <= 0x1F17F || c == 0x1F18E || c >= 0x1F191 && c <= 0x1F19A || c >= 0x1F1AD && c <= 0x1F1FF || c >= 0x1F201 && c <= 0x1F20F || c == 0x1F21A || c == 0x1F22F || c >= 0x1F232 && c <= 0x1F23A || c >= 0x1F23C && c <= 0x1F23F || c >= 0x1F249 && c <= 0x1F53D || c >= 0x1F546 && c <= 0x1F64F || c >= 0x1F680 && c <= 0x1F6FF || c >= 0x1F774 && c <= 0x1F77F || c >= 0x1F7D5 && c <= 0x1F7FF || c >= 0x1F80C && c <= 0x1F80F || c >= 0x1F848 && c <= 0x1F84F || c >= 0x1F85A && c <= 0x1F85F || c >= 0x1F888 && c <= 0x1F88F || c >= 0x1F8AE && c <= 0x1F8FF || c >= 0x1F90C && c <= 0x1F93A || c >= 0x1F93C && c <= 0x1F945 || c >= 0x1F947 && c <= 0x1FAFF || c >= 0x1FC00 && c <= 0x1FFFD ||
c >= 0xE0020 && c <= 0xE007F;
}
internal static bool IsHangul(uint c)
{
return c >= 0x1100 && c <= 0x11ff || /* Hangul Jamo */
c >= 0xA960 && c <= 0xA97F || /* Hangul Jamo Extended-A */
c >= 0xD7B0 && c <= 0xD7FF || /* Hangul Jamo Extended-B */
c >= 0x3130 && c <= 0x318F || /* Hangul Compatibility Jamo */
c >= 0xFFA0 && c <= 0xFFDC || /* Halfwidth Jamo */
c >= 0xAC00 && c <= 0xD7AF; /* Hangul Syllables */
}
internal static bool IsCJK(uint c)
{
return
c >= 0x3000 && c <= 0x303F || /* CJK Symbols and Punctuation */
c >= 0x16FE0 && c <= 0x16FF || /* CJK Ideographic Symbols and Punctuation */
c >= 0x3100 && c <= 0x312F || /* Bopomofo */
c >= 0x31A0 && c <= 0x31BF || /* Bopomofo Extended */
c >= 0x4E00 && c <= 0x9FFF || /* CJK Unified Ideographs (Han) */
c >= 0x3400 && c <= 0x4DBF || /* CJK Extension A */
c >= 0x20000 && c <= 0x2A6DF || /* CJK Extension B */
c >= 0x2A700 && c <= 0x2B73F || /* CJK Extension C */
c >= 0x2B740 && c <= 0x2B81F || /* CJK Extension D */
c >= 0x2B820 && c <= 0x2CEAF || /* CJK Extension E */
c >= 0x2CEB0 && c <= 0x2EBE0 || /* CJK Extension F */
c >= 0x30000 && c <= 0x3134A || /* CJK Extension G */
c >= 0xF900 && c <= 0xFAFF || /* CJK Compatibility Ideographs */
c >= 0x2F800 && c <= 0x2FA1F || /* CJK Compatibility Ideographs Supplement */
c >= 0x2F00 && c <= 0x2FDF || /* CJK Radicals / Kangxi Radicals */
c >= 0x2E80 && c <= 0x2EFF || /* CJK Radicals Supplement */
c >= 0x31C0 && c <= 0x31EF || /* CJK Strokes */
c >= 0x2FF0 && c <= 0x2FFF || /* Ideographic Description Characters */
c >= 0x3040 && c <= 0x309F || /* Hiragana */
c >= 0x1B100 && c <= 0x1B12F || /* Kana Extended-A */
c >= 0x1AFF0 && c <= 0x1AFFF || /* Kana Extended-B */
c >= 0x1B000 && c <= 0x1B0FF || /* Kana Supplement */
c >= 0x1B130 && c <= 0x1B16F || /* Small Kana Extension */
c >= 0x3190 && c <= 0x319F || /* Kanbun */
c >= 0x30A0 && c <= 0x30FF || /* Katakana */
c >= 0x31F0 && c <= 0x31FF || /* Katakana Phonetic Extensions */
c >= 0xFF65 && c <= 0xFF9F; /* Halfwidth Katakana */
}
}
}
| UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorUtilities.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 46433
} | 468 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEditor;
using UnityEngine.TextCore;
namespace UnityEngine.TextCore.Text
{
internal struct GlyphProxy
{
public uint index;
public GlyphRect glyphRect;
public GlyphMetrics metrics;
public int atlasIndex;
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetEditorUtilities.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetEditorUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 157
} | 469 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using System.Collections.Generic;
namespace UnityEditor.TextCore.Text
{
internal enum SpriteAssetImportFormats { None = 0, TexturePackerJsonArray = 0x1 };
internal class TexturePacker_JsonArray
{
[System.Serializable]
public struct SpriteFrame
{
public float x;
public float y;
public float w;
public float h;
public override string ToString()
{
string s = "x: " + x.ToString("f2") + " y: " + y.ToString("f2") + " h: " + h.ToString("f2") + " w: " + w.ToString("f2");
return s;
}
}
[System.Serializable]
public struct SpriteSize
{
public float w;
public float h;
public override string ToString()
{
string s = "w: " + w.ToString("f2") + " h: " + h.ToString("f2");
return s;
}
}
[System.Serializable]
public struct Frame
{
public string filename;
public SpriteFrame frame;
public bool rotated;
public bool trimmed;
public SpriteFrame spriteSourceSize;
public SpriteSize sourceSize;
public Vector2 pivot;
}
[System.Serializable]
public struct Meta
{
public string app;
public string version;
public string image;
public string format;
public SpriteSize size;
public float scale;
public string smartupdate;
}
[System.Serializable]
public class SpriteDataObject
{
public List<Frame> frames;
public Meta meta;
}
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SpriteAssetImportFormats.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/SpriteAssetImportFormats.cs",
"repo_id": "UnityCsReference",
"token_count": 953
} | 470 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.TextCore.Text;
namespace UnityEditor.TextCore.Text
{
[CustomPropertyDrawer(typeof(TextStyle))]
internal class TextStylePropertyDrawer : PropertyDrawer
{
public static readonly float height = 95f;
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
return height;
}
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
SerializedProperty nameProperty = property.FindPropertyRelative("m_Name");
SerializedProperty hashCodeProperty = property.FindPropertyRelative("m_HashCode");
SerializedProperty openingDefinitionProperty = property.FindPropertyRelative("m_OpeningDefinition");
SerializedProperty closingDefinitionProperty = property.FindPropertyRelative("m_ClosingDefinition");
SerializedProperty openingDefinitionArray = property.FindPropertyRelative("m_OpeningTagArray");
SerializedProperty closingDefinitionArray = property.FindPropertyRelative("m_ClosingTagArray");
EditorGUIUtility.labelWidth = 86;
position.height = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
float labelHeight = position.height + 2f;
EditorGUI.BeginChangeCheck();
Rect rect0 = new Rect(position.x, position.y, (position.width) / 2 + 5, position.height);
EditorGUI.PropertyField(rect0, nameProperty);
if (EditorGUI.EndChangeCheck())
{
// Recompute HashCode if name has changed.
hashCodeProperty.intValue = TextUtilities.GetHashCodeCaseInSensitive(nameProperty.stringValue);
property.serializedObject.ApplyModifiedProperties();
// Dictionary needs to be updated since HashCode has changed.
TextStyleSheet styleSheet = property.serializedObject.targetObject as TextStyleSheet;
styleSheet.RefreshStyles();
}
// HashCode
Rect rect1 = new Rect(rect0.x + rect0.width + 5, position.y, 65, position.height);
GUI.Label(rect1, "HashCode");
GUI.enabled = false;
rect1.x += 65;
rect1.width = position.width / 2 - 75;
EditorGUI.PropertyField(rect1, hashCodeProperty, GUIContent.none);
GUI.enabled = true;
// Text Tags
EditorGUI.BeginChangeCheck();
// Opening Tags
position.y += labelHeight;
GUI.Label(position, "Opening Tags");
Rect textRect1 = new Rect(110, position.y, position.width - 86, 35);
openingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect1, openingDefinitionProperty.stringValue);
if (EditorGUI.EndChangeCheck())
{
// If any properties have changed, we need to update the Opening and Closing Arrays.
int size = openingDefinitionProperty.stringValue.Length;
// Adjust array size to match new string length.
if (openingDefinitionArray.arraySize != size) openingDefinitionArray.arraySize = size;
for (int i = 0; i < size; i++)
{
SerializedProperty element = openingDefinitionArray.GetArrayElementAtIndex(i);
element.intValue = openingDefinitionProperty.stringValue[i];
}
}
EditorGUI.BeginChangeCheck();
// Closing Tags
position.y += 38;
GUI.Label(position, "Closing Tags");
Rect textRect2 = new Rect(110, position.y, position.width - 86, 35);
closingDefinitionProperty.stringValue = EditorGUI.TextArea(textRect2, closingDefinitionProperty.stringValue);
if (EditorGUI.EndChangeCheck())
{
// If any properties have changed, we need to update the Opening and Closing Arrays.
int size = closingDefinitionProperty.stringValue.Length;
// Adjust array size to match new string length.
if (closingDefinitionArray.arraySize != size) closingDefinitionArray.arraySize = size;
for (int i = 0; i < size; i++)
{
SerializedProperty element = closingDefinitionArray.GetArrayElementAtIndex(i);
element.intValue = closingDefinitionProperty.stringValue[i];
}
}
}
}
[CustomEditor(typeof(TextStyleSheet)), CanEditMultipleObjects]
internal class TextStyleSheetEditor : Editor
{
TextStyleSheet m_StyleSheet;
SerializedProperty m_StyleListProp;
int m_SelectedElement = -1;
int m_Page;
bool m_IsStyleSheetDirty;
void OnEnable()
{
m_StyleSheet = target as TextStyleSheet;
m_StyleListProp = serializedObject.FindProperty("m_StyleList");
}
public override void OnInspectorGUI()
{
Event currentEvent = Event.current;
serializedObject.Update();
m_IsStyleSheetDirty = false;
int arraySize = m_StyleListProp.arraySize;
int itemsPerPage = (Screen.height - 100) / 110;
if (arraySize > 0)
{
// Display each Style entry using the StyleDrawer PropertyDrawer.
for (int i = itemsPerPage * m_Page; i < arraySize && i < itemsPerPage * (m_Page + 1); i++)
{
// Define the start of the selection region of the element.
Rect elementStartRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
SerializedProperty styleProperty = m_StyleListProp.GetArrayElementAtIndex(i);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(styleProperty);
EditorGUILayout.EndVertical();
if (EditorGUI.EndChangeCheck())
{
//
}
// Define the end of the selection region of the element.
Rect elementEndRegion = GUILayoutUtility.GetRect(0f, 0f, GUILayout.ExpandWidth(true));
// Check for Item selection
Rect selectionArea = new Rect(elementStartRegion.x, elementStartRegion.y, elementEndRegion.width, elementEndRegion.y - elementStartRegion.y);
if (DoSelectionCheck(selectionArea))
{
if (m_SelectedElement == i)
{
m_SelectedElement = -1;
}
else
{
m_SelectedElement = i;
GUIUtility.keyboardControl = 0;
}
}
// Handle Selection Highlighting
if (m_SelectedElement == i)
TextCoreEditorUtilities.DrawBox(selectionArea, 2f, new Color32(40, 192, 255, 255));
}
}
// STYLE LIST MANAGEMENT
Rect rect = EditorGUILayout.GetControlRect(false, 20);
float totalWidth = rect.width;
rect.width = totalWidth * 0.175f;
// Move Style up.
bool guiEnabled = GUI.enabled;
if (m_SelectedElement == -1 || m_SelectedElement == 0) { GUI.enabled = false; }
if (GUI.Button(rect, "Up"))
{
SwapStyleElements(m_SelectedElement, m_SelectedElement - 1);
}
GUI.enabled = guiEnabled;
// Move Style down.
rect.x += rect.width;
if (m_SelectedElement == arraySize - 1) { GUI.enabled = false; }
if (GUI.Button(rect, "Down"))
{
SwapStyleElements(m_SelectedElement, m_SelectedElement + 1);
}
GUI.enabled = guiEnabled;
// Add Style
rect.x += rect.width + totalWidth * 0.3f;
if (GUI.Button(rect, "+"))
{
int index = m_SelectedElement == -1 ? 0 : m_SelectedElement;
if (index > arraySize)
index = arraySize;
// Copy selected element
m_StyleListProp.InsertArrayElementAtIndex(index);
// Select newly inserted element
m_SelectedElement = index + 1;
serializedObject.ApplyModifiedProperties();
m_StyleSheet.RefreshStyles();
}
// Delete style
rect.x += rect.width;
if (m_SelectedElement == -1 || m_SelectedElement >= arraySize) GUI.enabled = false;
if (GUI.Button(rect, "-"))
{
int index = m_SelectedElement == -1 ? 0 : m_SelectedElement;
m_StyleListProp.DeleteArrayElementAtIndex(index);
m_SelectedElement = -1;
serializedObject.ApplyModifiedProperties();
m_StyleSheet.RefreshStyles();
return;
}
// Return if we can't display any items.
if (itemsPerPage == 0) return;
// DISPLAY PAGE CONTROLS
int shiftMultiplier = currentEvent.shift ? 10 : 1; // Page + Shift goes 10 page forward
Rect pagePos = EditorGUILayout.GetControlRect(false, 20);
pagePos.width = totalWidth * 0.35f;
// Previous Page
if (m_Page > 0) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Previous"))
m_Page -= 1 * shiftMultiplier;
// PAGE COUNTER
GUI.enabled = true;
pagePos.x += pagePos.width;
pagePos.width = totalWidth * 0.30f;
int totalPages = (int)(arraySize / (float)itemsPerPage + 0.999f);
GUI.Label(pagePos, "Page " + (m_Page + 1) + " / " + totalPages, TM_EditorStyles.centeredLabel);
// Next Page
pagePos.x += pagePos.width;
pagePos.width = totalWidth * 0.35f;
if (itemsPerPage * (m_Page + 1) < arraySize) GUI.enabled = true;
else GUI.enabled = false;
if (GUI.Button(pagePos, "Next"))
m_Page += 1 * shiftMultiplier;
// Clamp page range
m_Page = Mathf.Clamp(m_Page, 0, arraySize / itemsPerPage);
if (serializedObject.ApplyModifiedProperties())
{
TextEventManager.ON_TEXT_STYLE_PROPERTY_CHANGED(true);
if (m_IsStyleSheetDirty)
{
m_IsStyleSheetDirty = false;
m_StyleSheet.RefreshStyles();
}
}
// Clear selection if mouse event was not consumed.
GUI.enabled = true;
if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0)
m_SelectedElement = -1;
}
// Check if any of the Style elements were clicked on.
static bool DoSelectionCheck(Rect selectionArea)
{
Event currentEvent = Event.current;
switch (currentEvent.type)
{
case EventType.MouseDown:
if (selectionArea.Contains(currentEvent.mousePosition) && currentEvent.button == 0)
{
currentEvent.Use();
return true;
}
break;
}
return false;
}
void SwapStyleElements(int selectedIndex, int newIndex)
{
m_StyleListProp.MoveArrayElement(selectedIndex, newIndex);
m_SelectedElement = newIndex;
m_IsStyleSheetDirty = true;
}
}
}
| UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextStyleSheetEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextStyleSheetEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 5857
} | 471 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace UnityEditor
{
/// <summary>GridPalette stores settings for Palette assets when shown in the Palette window.</summary>
public class GridPalette : ScriptableObject
{
/// <summary>Controls the sizing of cells for a Palette.</summary>
public enum CellSizing
{
/// <summary>Automatically resizes the Palette cells by the size of Sprites in the Palette.</summary>
Automatic = 0,
/// <summary>Size of Palette cells will be changed manually by the user.</summary>
Manual = 100
}
/// <summary>Determines the sizing of cells for a Palette.</summary>
[SerializeField]
public CellSizing cellSizing;
[SerializeField]
private TransparencySortMode m_TransparencySortMode = TransparencySortMode.Default;
[SerializeField]
private Vector3 m_TransparencySortAxis = new Vector3(0.0f, 0.0f, 1.0f);
/// <summary>
/// Determines the transparency sorting mode of renderers in the Palette
/// </summary>
public TransparencySortMode transparencySortMode
{
get => m_TransparencySortMode;
set => m_TransparencySortMode = value;
}
/// <summary>
/// Determines the sorting axis if the transparency sort mode is set to Custom Axis Sort
/// </summary>
public Vector3 transparencySortAxis
{
get => m_TransparencySortAxis;
set => m_TransparencySortAxis = value;
}
}
}
| UnityCsReference/Modules/TilemapEditor/Editor/Managed/Grid/GridPalette.cs/0 | {
"file_path": "UnityCsReference/Modules/TilemapEditor/Editor/Managed/Grid/GridPalette.cs",
"repo_id": "UnityCsReference",
"token_count": 663
} | 472 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
namespace TreeEditor
{
public class TreeMaterial
{
public Material material;
public bool tileV;
}
}
| UnityCsReference/Modules/TreeEditor/Includes/TreeMaterial.cs/0 | {
"file_path": "UnityCsReference/Modules/TreeEditor/Includes/TreeMaterial.cs",
"repo_id": "UnityCsReference",
"token_count": 103
} | 473 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditorInternal;
namespace UnityEditor.UIAutomation
{
// Note: all input mouse positions should be in GUIView coordinates as the EventUtility class dispatches events as
// they were coming from GUIView. Use ConvertEditorWindowCoordsToGuiViewCoords and ConvertGuiViewCoordsToEditorWindowCoords
// to convert between coordic
static class EventUtility
{
internal static bool Click(EditorWindow window, Vector2 mousePosition)
{
return Click(window, mousePosition, EventModifiers.None);
}
internal static bool Click(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers)
{
return Click(window, mousePosition, modifiers, 0);
}
internal static bool Click(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers, int mouseButton)
{
var anyEventsUsed = false;
var evt = new Event()
{
mousePosition = mousePosition,
modifiers = modifiers,
button = mouseButton
};
evt.type = EventType.MouseDown;
anyEventsUsed |= window.SendEvent(evt);
evt.type = EventType.MouseUp;
anyEventsUsed |= window.SendEvent(evt);
UpdateFakeMouseCursorPosition(window, mousePosition);
return anyEventsUsed;
}
public static bool KeyDownAndUp(EditorWindow window, KeyCode keyCode)
{
return KeyDownAndUp(window, keyCode, EventModifiers.None);
}
public static bool KeyDownAndUp(EditorWindow window, KeyCode keyCode, EventModifiers modifiers)
{
var anyEventsUsed = false;
anyEventsUsed |= KeyDown(window, keyCode, modifiers);
anyEventsUsed |= KeyUp(window, keyCode, modifiers);
return anyEventsUsed;
}
public static bool KeyDown(EditorWindow window, KeyCode keyCode)
{
return KeyDown(window, keyCode, EventModifiers.None);
}
public static bool KeyDown(EditorWindow window, KeyCode keyCode, EventModifiers modifiers)
{
var anyEventsUsed = false;
var evt = new Event()
{
type = EventType.KeyDown,
keyCode = keyCode,
modifiers = modifiers
};
anyEventsUsed |= window.SendEvent(evt);
evt.character = (char)keyCode;
evt.keyCode = KeyCode.None;
anyEventsUsed |= window.SendEvent(evt);
return anyEventsUsed;
}
public static bool KeyUp(EditorWindow window, KeyCode keyCode)
{
return KeyUp(window, keyCode, EventModifiers.None);
}
public static bool KeyUp(EditorWindow window, KeyCode keyCode, EventModifiers modifiers)
{
var evt = new Event()
{
type = EventType.KeyUp,
keyCode = keyCode,
modifiers = modifiers
};
return window.SendEvent(evt);
}
public static void UpdateMouseMove(EditorWindow window, Vector2 mousePosition)
{
var evt = new Event()
{
type = EventType.MouseMove,
};
window.SendEvent(evt);
UpdateFakeMouseCursorPosition(window, mousePosition);
}
// ----------------------------------------------------------
// Drag and drop (simulates the drag and drop handling in the editor)
// ----------------------------------------------------------
public static void DragAndDrop(EditorWindow window, Vector2 mousePositionStart, Vector2 mousePositionEnd)
{
DragAndDrop(window, mousePositionStart, mousePositionEnd, EventModifiers.None);
}
public static void DragAndDrop(EditorWindow window, Vector2 mousePositionStart, Vector2 mousePositionEnd, EventModifiers modifiers)
{
BeginDragAndDrop(window, mousePositionStart, modifiers);
UpdateDragAndDrop(window, (mousePositionStart + mousePositionStart) * 0.5f);
EndDragAndDrop(window, mousePositionEnd, modifiers);
}
public static bool BeginDragAndDrop(EditorWindow window, Vector2 mousePosition)
{
return BeginDragAndDrop(window, mousePosition, EventModifiers.None);
}
public static bool BeginDragAndDrop(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers)
{
var anyEventsUsed = false;
InternalEditorUtility.PrepareDragAndDropTesting(window);
var evt = new Event()
{
mousePosition = mousePosition,
modifiers = modifiers
};
evt.type = EventType.MouseDown;
evt.clickCount = 1;
anyEventsUsed |= window.SendEvent(evt);
evt.clickCount = 0;
evt.type = EventType.MouseDrag;
anyEventsUsed |= window.SendEvent(evt);
// Some drag and drop handling requires to small mouse drag distance before starting a drag and drop session
evt.mousePosition = new Vector2(evt.mousePosition.x, evt.mousePosition.y + 20);
anyEventsUsed |= window.SendEvent(evt);
// Send first DragUpdated event
evt.type = EventType.DragUpdated;
anyEventsUsed |= window.SendEvent(evt);
window.Repaint();
return anyEventsUsed;
}
public static bool EndDragAndDrop(EditorWindow window, Vector2 mousePosition)
{
return EndDragAndDrop(window, mousePosition, EventModifiers.None);
}
public static bool EndDragAndDrop(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers)
{
var anyEventsUsed = false;
var evt = new Event()
{
mousePosition = mousePosition,
modifiers = modifiers
};
evt.type = EventType.DragUpdated;
anyEventsUsed |= window.SendEvent(evt);
evt.type = EventType.DragPerform;
anyEventsUsed |= window.SendEvent(evt);
return anyEventsUsed;
}
public static bool UpdateDragAndDrop(EditorWindow window, Vector2 mousePosition)
{
return UpdateDragAndDrop(window, mousePosition, EventModifiers.None);
}
public static bool UpdateDragAndDrop(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers)
{
var anyEventsUsed = false;
var evt = new Event()
{
type = EventType.DragUpdated,
mousePosition = mousePosition,
modifiers = modifiers
};
anyEventsUsed |= window.SendEvent(evt);
UpdateFakeMouseCursorPosition(window, mousePosition);
return anyEventsUsed;
}
// ----------------------------------------------------------
// Mouse dragging (simulates simple mousedown, mouse drag and mouse up)
// ----------------------------------------------------------
static Vector2 s_PrevMousePosition;
public static void Drag(EditorWindow window, Vector2 mousePositionStart, Vector2 mousePositionEnd)
{
Drag(window, mousePositionStart, mousePositionEnd, EventModifiers.None);
}
public static void Drag(EditorWindow window, Vector2 mousePositionStart, Vector2 mousePositionEnd, EventModifiers modifiers)
{
BeginDrag(window, mousePositionStart, modifiers);
EndDrag(window, mousePositionEnd, modifiers);
}
public static void BeginDrag(EditorWindow window, Vector2 mousePosition)
{
BeginDrag(window, mousePosition, EventModifiers.None);
}
public static void BeginDrag(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers)
{
s_PrevMousePosition = mousePosition;
var evt = new Event()
{
mousePosition = mousePosition,
modifiers = modifiers
};
evt.type = EventType.MouseDown;
evt.clickCount = 1;
window.SendEvent(evt);
evt.clickCount = 0;
evt.type = EventType.MouseDrag;
window.SendEvent(evt);
}
public static void EndDrag(EditorWindow window, Vector2 mousePosition)
{
EndDrag(window, mousePosition, EventModifiers.None);
}
public static void EndDrag(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers)
{
var evt = new Event()
{
mousePosition = mousePosition,
modifiers = modifiers,
delta = mousePosition - s_PrevMousePosition
};
s_PrevMousePosition = mousePosition;
evt.type = EventType.MouseDrag;
window.SendEvent(evt);
evt.type = EventType.MouseUp;
window.SendEvent(evt);
}
public static void UpdateDrag(EditorWindow window, Vector2 mousePosition)
{
UpdateDrag(window, mousePosition, EventModifiers.None);
}
public static void UpdateDrag(EditorWindow window, Vector2 mousePosition, EventModifiers modifiers)
{
window.SendEvent(new Event()
{
type = EventType.MouseDrag,
mousePosition = mousePosition,
modifiers = modifiers,
delta = mousePosition - s_PrevMousePosition
});
s_PrevMousePosition = mousePosition;
}
// These are not public so hardcoded here
const float kDockAreaTopMarginAndTabHeight = DockArea.kFloatingWindowTopBorderWidth + DockArea.kTabHeight + 1;
public static Vector2 ConvertEditorWindowCoordsToGuiViewCoords(Vector2 editorWindowPosition)
{
return new Vector2(editorWindowPosition.x, editorWindowPosition.y + kDockAreaTopMarginAndTabHeight);
}
public static Vector2 ConvertGuiViewCoordsToEditorWindowCoords(Vector2 guiViewPosition)
{
return new Vector2(guiViewPosition.x, guiViewPosition.y - kDockAreaTopMarginAndTabHeight);
}
static void UpdateFakeMouseCursorPosition(EditorWindow window, Vector2 mousePosition)
{
TestEditorWindow testWindow = window as TestEditorWindow;
if (testWindow != null)
testWindow.fakeCursor.position = ConvertGuiViewCoordsToEditorWindowCoords(mousePosition);
}
}
internal class Easing
{
public static float Linear(float k)
{
return k;
}
public class Quadratic
{
public static float In(float k)
{
return k * k;
}
public static float Out(float k)
{
return k * (2f - k);
}
public static float InOut(float k)
{
var eased = 2 * k * k;
if (k > 0.5)
eased = 4 * k - eased - 1;
return eased;
}
}
}
struct Wait
{
readonly double endTime;
public Wait(double seconds)
{
endTime = EditorApplication.timeSinceStartup + seconds;
}
public bool keepWaiting
{
get { return EditorApplication.timeSinceStartup < endTime; }
}
// static utility methods
public static void Seconds(double seconds)
{
s_Wait = new Wait(seconds);
}
public static bool waiting
{
get { return s_Wait.keepWaiting; }
}
static Wait s_Wait;
}
}
| UnityCsReference/Modules/UIAutomationEditor/EventUtility.cs/0 | {
"file_path": "UnityCsReference/Modules/UIAutomationEditor/EventUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 5322
} | 474 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderClassDragger : BuilderDragger
{
static readonly string s_DraggableStyleClassPillClassName = "unity-builder-class-pill--draggable";
string m_ClassNameBeingDragged;
public BuilderClassDragger(
BuilderPaneWindow paneWindow,
VisualElement root, BuilderSelection selection,
BuilderViewport viewport, BuilderParentTracker parentTracker)
: base(paneWindow, root, selection, viewport, parentTracker)
{
}
protected override VisualElement CreateDraggedElement()
{
var classPillTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(
BuilderConstants.UIBuilderPackagePath + "/BuilderClassPill.uxml");
var pill = classPillTemplate.CloneTree();
pill.AddToClassList(s_DraggableStyleClassPillClassName);
return pill;
}
protected override void FillDragElement(VisualElement pill)
{
pill.Q<Label>().text = m_ClassNameBeingDragged;
}
protected override bool StartDrag(VisualElement target, Vector2 mousePosition, VisualElement pill)
{
m_ClassNameBeingDragged = target.GetProperty(BuilderConstants.ExplorerStyleClassPillClassNameVEPropertyName) as string;
// if a ChildSubDocument is open, make sure that style class is part of active stylesheet, otherwise refuse drag
if (!paneWindow.document.activeOpenUXMLFile.isChildSubDocument)
return true;
if (target.IsParentSelector())
return false;
foreach (var openUSSFile in paneWindow.document.openUSSFiles)
{
var currentStyleSheet = openUSSFile.styleSheet;
if (currentStyleSheet.FindSelector(m_ClassNameBeingDragged) != null)
{
return true;
}
}
return false;
}
protected override void PerformAction(VisualElement destination, DestinationPane pane, Vector2 localMousePosition, int index = -1)
{
if (BuilderSharedStyles.IsDocumentElement(destination))
return;
var className = m_ClassNameBeingDragged.TrimStart('.');
destination.AddToClassList(className);
// Update VisualTreeAsset.
BuilderAssetUtilities.AddStyleClassToElementInAsset(
paneWindow.document, destination, className);
selection.NotifyOfHierarchyChange(null);
selection.NotifyOfStylingChange(null);
}
protected override bool IsPickedElementValid(VisualElement element)
{
if (element == null)
return false;
if (element.GetVisualElementAsset() == null)
return false;
if (!element.IsPartOfActiveVisualTreeAsset(paneWindow.document))
return false;
return true;
}
protected override bool SupportsDragInEmptySpace(VisualElement element)
{
return false;
}
protected override bool SupportsPlacementIndicator()
{
return false;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Draggers/BuilderClassDragger.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Draggers/BuilderClassDragger.cs",
"repo_id": "UnityCsReference",
"token_count": 1478
} | 475 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor;
namespace Unity.UI.Builder
{
internal class BuilderStyleSheetsWindow : BuilderPaneWindow
{
BuilderStyleSheets m_StyleSheetsPane;
//[MenuItem(BuilderConstants.BuilderMenuEntry + " StyleSheets")]
public static void ShowWindow()
{
GetWindowAndInit<BuilderStyleSheetsWindow>();
}
protected override void OnEnable()
{
base.OnEnable();
SetTitleContent("UI Builder StyleSheets");
}
public override void CreateUI()
{
var root = rootVisualElement;
var viewportWindow = document.primaryViewportWindow;
if (viewportWindow == null)
return;
var selection = viewportWindow.selection;
var viewport = viewportWindow.viewport;
var classDragger = new BuilderClassDragger(this, root, selection, viewport, viewport.parentTracker);
var styleSheetsDragger = new BuilderStyleSheetsDragger(this, root, selection);
m_StyleSheetsPane = new BuilderStyleSheets(this, viewport, selection, classDragger, styleSheetsDragger, null, null);
selection.AddNotifier(m_StyleSheetsPane);
root.Add(m_StyleSheetsPane);
// Command Handler
commandHandler.RegisterPane(m_StyleSheetsPane);
}
public override void ClearUI()
{
if (m_StyleSheetsPane == null)
return;
var selection = document.primaryViewportWindow?.selection;
if (selection != null)
selection.RemoveNotifier(m_StyleSheetsPane);
m_StyleSheetsPane.RemoveFromHierarchy();
m_StyleSheetsPane = null;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheetsWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheetsWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 824
} | 476 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Profiling;
using Unity.Properties;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderInspectorAttributes : BuilderUxmlAttributesView, IBuilderInspectorSection
{
BuilderSelection m_Selection;
public VisualElement root => fieldsContainer;
// ReSharper disable MemberCanBePrivate.Global
internal const string inspectorAttributeRefreshMarkerName = "BuilderInspectorAttributes.Refresh";
// ReSharper restore MemberCanBePrivate.Global
static readonly ProfilerMarker k_RefreshMarker = new (inspectorAttributeRefreshMarkerName);
public BuilderInspectorAttributes(BuilderInspector inspector) : base(inspector)
{
this.inspector = inspector;
m_Selection = inspector.selection;
fieldsContainer = inspector.Q<PersistedFoldout>("inspector-attributes-foldout");
}
bool m_IgnoreChangeToInlineValue = false;
/// <inheritdoc/>
protected override bool IsAttributeIgnored(UxmlAttributeDescription attribute)
{
return base.IsAttributeIgnored(attribute) || (attribute.name is "data-source" or "data-source-type" or "data-source-path");
}
public override void Refresh()
{
using var marker = k_RefreshMarker.Auto();
var currentVisualElement = inspector.currentVisualElement;
base.Refresh();
if (currentVisualElement != null && m_Selection.selectionType == BuilderSelectionType.ElementInTemplateInstance &&
string.IsNullOrEmpty(currentVisualElement.name))
{
var helpBox = new HelpBox();
helpBox.AddToClassList(BuilderConstants.InspectorClassHelpBox);
helpBox.text = BuilderConstants.NoNameElementAttributes;
fieldsContainer.Insert(0, helpBox);
}
// Forward focus to the panel header.
fieldsContainer
.Query()
.Where(e => e.focusable)
.ForEach((e) => inspector.AddFocusable(e));
}
internal override void UpdateAttributeOverrideStyle(VisualElement fieldElement)
{
base.UpdateAttributeOverrideStyle(fieldElement);
var hasAnyBoundField = fieldsContainer.Q(className: BuilderConstants.InspectorLocalStyleBindingClassName) != null
|| fieldsContainer.Q(className: BuilderConstants.InspectorLocalStyleUnresolvedBindingClassName) != null;
fieldsContainer.EnableInClassList(BuilderConstants.InspectorCategoryFoldoutBindingClassName, hasAnyBoundField);
var hasOverriddenField = BuilderInspectorUtilities.HasOverriddenField(fieldsContainer);
fieldsContainer.EnableInClassList(BuilderConstants.InspectorCategoryFoldoutOverrideClassName, hasOverriddenField);
}
public void Enable()
{
fieldsContainer.contentContainer.SetEnabled(true);
}
public void Disable()
{
fieldsContainer.contentContainer.SetEnabled(false);
}
protected override void UpdateFieldStatus(VisualElement fieldElement)
{
inspector.UpdateFieldStatus(fieldElement, null);
var hasOverriddenField = BuilderInspectorUtilities.HasOverriddenField(fieldsContainer);
fieldsContainer.EnableInClassList(BuilderConstants.InspectorCategoryFoldoutOverrideClassName, hasOverriddenField);
}
protected override void NotifyAttributesChanged(string attributeName = null)
{
var changeType = attributeName == BuilderConstants.UxmlNameAttr ? BuilderHierarchyChangeType.ElementName : BuilderHierarchyChangeType.Attributes;
// During inline editing, if the value used in the field changes from being bound to being inline,
// no changes to the asset must be made.
// Instead, we force a visual update of the asset to see the inline value in canvas.
if (m_IgnoreChangeToInlineValue)
{
m_IgnoreChangeToInlineValue = false;
m_Selection.ForceVisualAssetUpdateWithoutSave(inspector.currentVisualElement, changeType);
}
else
{
m_Selection.NotifyOfHierarchyChange(inspector, inspector.currentVisualElement, changeType);
}
}
protected override void BuildAttributeFieldContextualMenu(DropdownMenu menu, BuilderStyleRow styleRow)
{
if (styleRow != null)
{
if (m_Selection.selectionType != BuilderSelectionType.ElementInTemplateInstance)
{
var fieldElement = styleRow.GetLinkedFieldElements()[0]; // Assume default case of only 1 field per row.
var csPropertyName = fieldElement.GetProperty(BuilderConstants.InspectorAttributeBindingPropertyNameVEPropertyName) as string;
var container = currentElement;
var isBindableElement = UxmlSerializedDataRegistry.GetDescription(attributesUxmlOwner.fullTypeName) != null;
var isBindableProperty = PropertyContainer.IsPathValid(ref container, csPropertyName);
// Do show binding related actions if the underlying property is not bindable or if the element is
// not using the new serialization system to define attributes.
if (isBindableElement && isBindableProperty)
{
var hasDataBinding = false;
var vea = inspector.currentVisualElement.GetVisualElementAsset();
if (vea != null)
{
hasDataBinding = BuilderBindingUtility.TryGetBinding(csPropertyName, out _, out _);
}
if (hasDataBinding)
{
menu.AppendAction(BuilderConstants.ContextMenuEditBindingMessage,
(a) => BuilderBindingUtility.OpenBindingWindowToEdit(csPropertyName, inspector),
(a) => DropdownMenuAction.Status.Normal,
fieldElement);
menu.AppendAction(BuilderConstants.ContextMenuRemoveBindingMessage,
(a) => { BuilderBindingUtility.DeleteBinding(fieldElement, csPropertyName); },
(a) => DropdownMenuAction.Status.Normal,
fieldElement);
DataBindingUtility.TryGetLastUIBindingResult(new BindingId(csPropertyName), inspector.currentVisualElement,
out var bindingResult);
if (bindingResult.status == BindingStatus.Success)
{
menu.AppendAction(BuilderConstants.ContextMenuEditInlineValueMessage,
(a) => { inspector.EnableInlineValueEditing(fieldElement); },
(a) => DropdownMenuAction.Status.Normal,
fieldElement);
}
menu.AppendAction(
BuilderConstants.ContextMenuUnsetInlineValueMessage,
(a) =>
{
inspector.UnsetBoundFieldInlineValue(a);
},
action =>
{
var attributeDescription = fieldElement.GetLinkedAttributeDescription();
var attributeName = attributeDescription.name;
return (attributesUxmlOwner != null && attributesUxmlOwner.HasAttribute(attributeName))
? DropdownMenuAction.Status.Normal
: DropdownMenuAction.Status.Disabled;
},
fieldElement);
}
else
{
menu.AppendAction(BuilderConstants.ContextMenuAddBindingMessage,
(a) => BuilderBindingUtility.OpenBindingWindowToCreate(csPropertyName, inspector),
(a) => DropdownMenuAction.Status.Normal,
fieldElement);
}
menu.AppendSeparator();
}
}
base.BuildAttributeFieldContextualMenu(menu, styleRow);
}
}
protected override BuilderStyleRow CreateSerializedAttributeRow(UxmlSerializedAttributeDescription attribute, string propertyPath,
VisualElement parent = null)
{
var row = base.CreateSerializedAttributeRow(attribute, propertyPath, parent);
var propertyField = row.Q<PropertyField>();
propertyField?.RegisterCallback<SerializedPropertyBindEvent>(OnSerializedPropertyBindCallback);
return row;
}
public override void SetInlineValue(VisualElement fieldElement, string property)
{
m_IgnoreChangeToInlineValue = true;
base.SetInlineValue(fieldElement, property);
}
private void OnSerializedPropertyBindCallback(SerializedPropertyBindEvent e)
{
var targetVE = e.target as VisualElement;
var attributeField = targetVE.GetFirstAncestorOfType<UxmlSerializedDataAttributeField>();
inspector.RegisterFieldToInlineEditingEvents(attributeField);
targetVE.UnregisterCallback<SerializedPropertyBindEvent>(OnSerializedPropertyBindCallback);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorAttributes.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/BuilderInspectorAttributes.cs",
"repo_id": "UnityCsReference",
"token_count": 4712
} | 477 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
using BuilderLibraryItem = UnityEngine.UIElements.TreeViewItemData<Unity.UI.Builder.BuilderLibraryTreeItem>;
using TreeViewItem = UnityEngine.UIElements.TreeViewItemData<Unity.UI.Builder.BuilderLibraryTreeItem>;
namespace Unity.UI.Builder
{
class BuilderLibraryPlainView : BuilderLibraryView
{
public class LibraryPlainViewItem : VisualElement
{
readonly BuilderLibraryItem m_TreeItem;
readonly VisualElement m_Icon;
public int Id => m_TreeItem.id;
public VisualElement content { get; }
public LibraryPlainViewItem(BuilderLibraryItem libraryTreeItem)
{
m_TreeItem = libraryTreeItem;
var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(BuilderConstants.LibraryUIPath + "/BuilderLibraryPlainViewItem.uxml");
template.CloneTree(this);
var styleSheet = BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.LibraryUIPath + "/BuilderLibraryPlainViewItem.uss");
styleSheets.Add(styleSheet);
content = ElementAt(0);
if (m_TreeItem.data == null)
{
content.AddToClassList(k_PlainViewNoHoverVariantUssClassName);
content.Clear();
return;
}
m_Icon = this.Q<VisualElement>("icon");
this.Q<Label>().text = m_TreeItem.data.name;
SetIcon(m_TreeItem.data.largeIcon);
}
public void SwitchToDarkSkinIcon() => SetIcon(m_TreeItem.data.darkSkinLargeIcon);
public void SwitchToLightSkinIcon() => SetIcon(m_TreeItem.data.lightSkinLargeIcon);
void SetIcon(Texture2D icon)
{
var styleBackgroundImage = m_Icon.style.backgroundImage;
styleBackgroundImage.value = new Background { texture = icon };
m_Icon.style.backgroundImage = styleBackgroundImage;
}
}
const string k_PlainViewFoldoutStyle = "unity-builder-library__controls-category-foldout";
const string k_PlainViewNoHoverVariantUssClassName = "plain-view__item--no-hover";
const string k_PlainViewSelectedVariantUssClassName = "plain-view__item--selected";
const string k_ViewSelectedWithNoFocusVariantUssClassName = "plain-view__item--selected-no-focus";
const string k_ContentContainerName = "content";
readonly VisualElement m_ContentContainer;
readonly List<LibraryPlainViewItem> m_DummyItems = new List<LibraryPlainViewItem>();
readonly List<LibraryPlainViewItem> m_PlainViewItems = new List<LibraryPlainViewItem>();
readonly IEnumerable<TreeViewItem> m_Items;
LibraryPlainViewItem m_SelectedItem;
[SerializeField]
int m_SelectedItemId;
public override VisualElement primaryFocusable => m_ContentContainer;
public BuilderLibraryPlainView(IEnumerable<TreeViewItem> items)
{
var builderTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(BuilderConstants.LibraryUIPath + "/BuilderLibraryPlainView.uxml");
builderTemplate.CloneTree(this);
m_Items = items;
m_ContentContainer = this.Q<VisualElement>(k_ContentContainerName);
m_ContentContainer.focusable = true;
m_ContentContainer.RegisterCallback<FocusEvent>(OnFocusEvent);
m_ContentContainer.RegisterCallback<BlurEvent>(OnBlurEvent);
}
void OnBlurEvent(BlurEvent evt)
{
if (m_SelectedItem != null)
{
m_SelectedItem.content.RemoveFromClassList(k_PlainViewSelectedVariantUssClassName);
if (!EditorGUIUtility.isProSkin)
m_SelectedItem.SwitchToLightSkinIcon();
m_SelectedItem.content.AddToClassList(k_ViewSelectedWithNoFocusVariantUssClassName);
}
}
void OnFocusEvent(FocusEvent evt)
{
if (m_SelectedItem != null)
{
m_SelectedItem.content.RemoveFromClassList(k_ViewSelectedWithNoFocusVariantUssClassName);
if (!EditorGUIUtility.isProSkin)
m_SelectedItem.SwitchToDarkSkinIcon();
m_SelectedItem.content.AddToClassList(k_PlainViewSelectedVariantUssClassName);
}
}
public override void SetupView(BuilderLibraryDragger dragger, BuilderTooltipPreview tooltipPreview,
BuilderPaneContent builderPaneContent, BuilderPaneWindow builderPaneWindow,
VisualElement documentElement, BuilderSelection selection)
{
base.SetupView(dragger, tooltipPreview, builderPaneContent, builderPaneWindow, documentElement, selection);
FillView(m_Items);
}
public override VisualElement contentContainer => m_ContentContainer == null ? this : m_ContentContainer;
void FillView(IEnumerable<TreeViewItem> items, VisualElement itemsParent = null)
{
foreach (var item in items)
{
var libraryTreeItem = item.data;
if (libraryTreeItem.isHeader)
{
var categoryFoldout = new LibraryFoldout {text = libraryTreeItem.name};
if (libraryTreeItem.isEditorOnly)
{
categoryFoldout.tag = BuilderConstants.EditorOnlyTag;
categoryFoldout.Q(LibraryFoldout.TagLabelName).AddToClassList(BuilderConstants.TagPillClassName);
}
categoryFoldout.AddToClassList(k_PlainViewFoldoutStyle);
Add(categoryFoldout);
FillView(item.children, categoryFoldout);
continue;
}
var plainViewItem = new LibraryPlainViewItem(item);
plainViewItem.AddManipulator(new ContextualMenuManipulator(OnContextualMenuPopulateEvent));
plainViewItem.RegisterCallback<MouseDownEvent, LibraryPlainViewItem>(OnPlainViewItemMouseDown, plainViewItem);
LinkToTreeViewItem(plainViewItem, libraryTreeItem);
// The element set up is not yet completed at this point.
// SetupView has to be called as well.
plainViewItem.RegisterCallback<AttachToPanelEvent>(e =>
{
RegisterControlContainer(plainViewItem);
});
plainViewItem.RegisterCallback<MouseDownEvent>(e =>
{
if (e.clickCount == 2 && e.button == (int)MouseButton.LeftMouse)
{
AddItemToTheDocument(libraryTreeItem);
}
});
itemsParent?.Add(plainViewItem);
m_PlainViewItems.Add(plainViewItem);
}
}
internal override void OnViewDataReady()
{
base.OnViewDataReady();
OverwriteFromViewData(this, viewDataKey);
DoSelected(m_SelectedItemId);
if (!m_ContentContainer.IsFocused())
OnBlurEvent(null);
}
void OnPlainViewItemMouseDown(MouseDownEvent evt, LibraryPlainViewItem plainViewItem)
{
if (evt.button != (int)MouseButton.LeftMouse)
return;
DoSelected(plainViewItem.Id);
}
void DoSelected(int itemId)
{
m_SelectedItemId = itemId;
if (m_SelectedItem != null)
{
m_SelectedItem.content.RemoveFromClassList(k_PlainViewSelectedVariantUssClassName);
m_SelectedItem.content.RemoveFromClassList(k_ViewSelectedWithNoFocusVariantUssClassName);
if (!EditorGUIUtility.isProSkin)
m_SelectedItem.SwitchToLightSkinIcon();
}
foreach (var plainViewItem in m_PlainViewItems)
{
if (plainViewItem.Id.Equals(itemId))
{
m_SelectedItem = plainViewItem;
m_SelectedItem.content.AddToClassList(k_PlainViewSelectedVariantUssClassName);
if (!EditorGUIUtility.isProSkin)
m_SelectedItem.SwitchToDarkSkinIcon();
SaveViewData();
}
}
}
void OnContextualMenuPopulateEvent(ContextualMenuPopulateEvent evt)
{
if (m_Dragger.active)
{
evt.StopImmediatePropagation();
return;
}
var libraryItem = GetLibraryTreeItem(evt.elementTarget);
evt.menu.AppendAction(
"Add",
action => { AddItemToTheDocument(libraryItem); },
action => DropdownMenuAction.Status.Normal);
}
public override void Refresh() {}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibraryPlainView.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Library/BuilderLibraryPlainView.cs",
"repo_id": "UnityCsReference",
"token_count": 4341
} | 478 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderPreviewWindow : EditorWindow
{
ObjectField m_UxmlAssetField;
VisualElement m_Container;
[SerializeField]
VisualTreeAsset m_CurrentVisualTreeAsset;
internal override BindingLogLevel defaultBindingLogLevel => BindingLogLevel.None;
//[MenuItem("Tests/UI Builder/Document Preview")]
public static void ShowWindow()
{
var window = GetWindow<BuilderPreviewWindow>();
window.titleContent = new GUIContent("Builder Document Preview");
window.Show();
}
public void OnEnable()
{
var root = rootVisualElement;
// Load styles.
root.styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UIBuilderPackagePath + "/Builder.uss"));
if (EditorGUIUtility.isProSkin)
root.styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UIBuilderPackagePath + "/BuilderDark.uss"));
else
root.styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UIBuilderPackagePath + "/BuilderLight.uss"));
// Load template.
var builderTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(BuilderConstants.UIBuilderPackagePath + "/BuilderPreviewWindow.uxml");
builderTemplate.CloneTree(root);
// Init field.
m_UxmlAssetField = root.Q<ObjectField>();
m_UxmlAssetField.objectType = typeof(VisualTreeAsset);
m_UxmlAssetField.RegisterValueChangedCallback(VisualTreeAssetChanged);
m_Container = root.Q("container");
// Clone tree if we have an asset loaded.
m_UxmlAssetField.value = m_CurrentVisualTreeAsset;
CloneTree();
}
void VisualTreeAssetChanged(ChangeEvent<Object> evt)
{
m_CurrentVisualTreeAsset = evt.newValue as VisualTreeAsset;
CloneTree();
}
void CloneTree()
{
m_Container.Clear();
if (m_CurrentVisualTreeAsset == null)
return;
m_CurrentVisualTreeAsset.CloneTree(m_Container);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Previews/BuilderPreviewWindow.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Previews/BuilderPreviewWindow.cs",
"repo_id": "UnityCsReference",
"token_count": 1053
} | 479 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor;
using UnityEngine;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal static class BuilderInspectorUtilities
{
public static bool HasOverriddenField(VisualElement ve)
{
return ve.Q(className: BuilderConstants.InspectorLocalStyleOverrideClassName) != null;
}
public static VisualElement FindInspectorField(BuilderInspector inspector, string propertyPath)
{
if (propertyPath.Contains("style."))
{
var bindingPath = propertyPath.Replace("style.", "");
bindingPath = BuilderNameUtilities.ConvertStyleCSharpNameToUssName(bindingPath);
if (inspector.styleFields.m_StyleFields.TryGetValue(bindingPath, out var fields))
{
foreach (var field in fields)
{
// We can have multiple fields with the same binding path. Return the one that has the value info.
if (field.HasProperty(BuilderConstants.InspectorFieldValueInfoVEPropertyName))
{
return field;
}
}
}
}
var dataFields = inspector.Query<BuilderUxmlAttributesView.UxmlSerializedDataAttributeField>();
BuilderUxmlAttributesView.UxmlSerializedDataAttributeField dataField = null;
dataFields.ForEach(x =>
{
var serializedAttribute =
x.GetLinkedAttributeDescription() as UxmlSerializedAttributeDescription;
if (serializedAttribute.serializedField.Name == propertyPath)
{
dataField = x;
}
});
return dataField;
}
internal static string GetBindingProperty(VisualElement fieldElement)
{
string bindingProperty = null;
if (fieldElement.HasProperty(BuilderConstants.InspectorStylePropertyNameVEPropertyName))
{
bindingProperty = fieldElement.GetProperty(BuilderConstants.InspectorStyleBindingPropertyNameVEPropertyName) as string;
}
else if (fieldElement.HasLinkedAttributeDescription())
{
bindingProperty = fieldElement.GetProperty(BuilderConstants.InspectorAttributeBindingPropertyNameVEPropertyName) as string;
}
return bindingProperty;
}
public static bool HasBinding(BuilderInspector inspector, VisualElement fieldElement)
{
if (inspector.attributeSection.currentFieldSource == BuilderUxmlAttributesView.AttributeFieldSource.UxmlTraits)
{
return false;
}
var selectionIsSelector = BuilderSharedStyles.IsSelectorElement(inspector.currentVisualElement);
if (selectionIsSelector)
{
return false;
}
var bindingProperty = GetBindingProperty(fieldElement);
return inspector.attributeSection.uxmlSerializedData is VisualElement.UxmlSerializedData serializedData &&
serializedData.HasBindingInternal(bindingProperty);
}
// Useful for loading the Builder inspector's icons
public static Texture2D LoadIcon(string iconName, string subfolder = "")
{
return EditorGUIUtility.Load(EditorGUIUtility.isProSkin
? $"{BuilderConstants.IconsResourcesPath}/Dark/Inspector/{subfolder}{iconName}.png"
: $"{BuilderConstants.IconsResourcesPath}/Light/Inspector/{subfolder}{iconName}.png") as Texture2D;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderInspectorUtilities.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderInspectorUtilities.cs",
"repo_id": "UnityCsReference",
"token_count": 1713
} | 480 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class BuilderUxmlTypeAttributeFieldFactory : IBuilderUxmlAttributeFieldFactory
{
static readonly Dictionary<Type, TypeInfo> s_CachedTypeInfos = new Dictionary<Type, TypeInfo>();
static readonly UnityEngine.Pool.ObjectPool<BuilderAttributeTypeName> s_TypeNameItemPool = new(
() => new BuilderAttributeTypeName(),
null,
c => c.ClearType());
static TypeInfo GetTypeInfo(Type type)
{
if (!s_CachedTypeInfos.TryGetValue(type, out var typeInfo))
s_CachedTypeInfos[type] = typeInfo = new TypeInfo(type);
return typeInfo;
}
public readonly struct TypeInfo
{
public readonly Type type;
public readonly string value;
public TypeInfo(Type type)
{
this.type = type;
value = type.GetFullNameWithAssembly();
}
}
public bool CanCreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute)
{
var attributeType = attribute.GetType();
return (attributeType.IsGenericType && !attributeType.GetGenericArguments()[0].IsEnum && attributeType.GetGenericArguments()[0] is Type);
}
public VisualElement CreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
var attributeType = attribute.GetType();
var desiredType = attributeType.GetGenericArguments()[0];
var fieldLabel = BuilderNameUtilities.ConvertDashToHuman(attribute.name);
return CreateField(desiredType, fieldLabel, attributeOwner, attributeUxmlOwner, attribute, onValueChange);
}
public VisualElement CreateField(Type desiredType, string label, object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
var uiField = new TextField(label) { isDelayed = true };
var completer = new FieldSearchCompleter<TypeInfo>();
completer.SetupCompleterField(uiField, true);
// When possible, the popup should have the same width as the input field, so that the auto-complete
// characters will try to match said input field.
completer.matcherCallback += (str, info) => info.value.IndexOf(str, StringComparison.OrdinalIgnoreCase) >= 0;
completer.itemHeight = 36;
completer.dataSourceCallback += () =>
{
var desiredTypeInfo = new TypeInfo(desiredType);
return TypeCache.GetTypesDerivedFrom(desiredType)
.Where(t => !t.IsGenericType)
// Remove UIBuilder types from the list
.Where(t => t.Assembly != GetType().Assembly)
.Select(GetTypeInfo)
.Append(desiredTypeInfo);
};
completer.getTextFromDataCallback += info => info.value;
completer.makeItem = () => s_TypeNameItemPool.Get();
completer.destroyItem = e =>
{
if (e is BuilderAttributeTypeName typeItem)
s_TypeNameItemPool.Release(typeItem);
};
completer.bindItem = (v, i) =>
{
if (v is BuilderAttributeTypeName l)
l.SetType(completer.results[i].type, completer.textField.text);
};
uiField.RegisterValueChangedCallback(e =>
{
// null and empty string are considered equal in this case
if (string.IsNullOrEmpty(e.newValue) && string.IsNullOrEmpty(e.previousValue))
return;
OnValidatedTypeAttributeChange(e, desiredType
, attributeOwner, attribute, onValueChange);
});
uiField.userData = completer;
return uiField;
}
public void SetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, object value)
{
var strValue = string.Empty;
if (value is Type typeValue)
{
var fullTypeName = typeValue.AssemblyQualifiedName;
var fullTypeNameSplit = fullTypeName.Split(',');
strValue = $"{fullTypeNameSplit[0]},{fullTypeNameSplit[1]}";
}
else if (value is string str)
{
strValue = str;
}
(field as TextField).SetValueWithoutNotify(strValue);
}
public void ResetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute)
{
var a = attribute as TypedUxmlAttributeDescription<Type>;
var f = field as TextField;
if (a.defaultValue == null)
f.SetValueWithoutNotify(string.Empty);
else
f.SetValueWithoutNotify(a.defaultValue.ToString());
}
public void ResetFieldValueToInline(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute)
{
var a = attribute as TypedUxmlAttributeDescription<Type>;
var value = a.GetValueFromBag(attributeUxmlOwner, CreationContext.Default);
var f = field as TextField;
f.SetValueWithoutNotify(value.ToString());
}
void OnValidatedTypeAttributeChange(ChangeEvent<string> evt, Type desiredType
, object attributeOwner, UxmlAttributeDescription attribute
, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange)
{
var field = evt.elementTarget as TextField;
var typeName = evt.newValue;
var fullTypeName = typeName;
if (field == null || evt.target == field.labelElement)
return;
Type type = null;
if (!string.IsNullOrEmpty(typeName))
{
type = Type.GetType(fullTypeName, false);
// Try some auto-fixes.
if (type == null)
{
fullTypeName = typeName + ", UnityEngine.CoreModule";
type = Type.GetType(fullTypeName, false);
}
if (type == null)
{
fullTypeName = typeName + ", UnityEditor";
type = Type.GetType(fullTypeName, false);
}
if (type == null && typeName.Contains("."))
{
var split = typeName.Split('.');
fullTypeName = typeName + $", {split[0]}.{split[1]}Module";
type = Type.GetType(fullTypeName, false);
}
if (type == null)
{
Builder.ShowWarning(string.Format(BuilderConstants.TypeAttributeInvalidTypeMessage, field.label));
evt.StopPropagation();
return;
}
else if (!desiredType.IsAssignableFrom(type))
{
Builder.ShowWarning(string.Format(BuilderConstants.TypeAttributeMustDeriveFromMessage, field.label,
desiredType.FullName));
evt.StopPropagation();
return;
}
}
field.value = fullTypeName;
onValueChange?.Invoke(field, attribute, fullTypeName, fullTypeName);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlTypeAttributeField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlTypeAttributeField.cs",
"repo_id": "UnityCsReference",
"token_count": 3726
} | 481 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
[Flags]
internal enum OverlayContent
{
Content = 1 << 0,
Padding = 1 << 1,
Border = 1 << 2,
Margin = 1 << 3,
All = Content | Padding | Border | Margin
}
internal class OverlayData
{
public OverlayData(VisualElement ve, float alpha)
{
this.element = ve;
this.alpha = alpha;
this.defaultAlpha = alpha;
this.fadeOutRate = 0;
}
public VisualElement element;
public float alpha;
public float defaultAlpha;
public float fadeOutRate;
public OverlayContent content;
}
internal abstract class BaseOverlayPainter
{
protected Dictionary<VisualElement, OverlayData> m_OverlayData = new Dictionary<VisualElement, OverlayData>();
protected List<VisualElement> m_CleanUpOverlay = new List<VisualElement>();
public void Draw()
{
Draw(GUIClip.topmostRect);
}
public virtual void Draw(Rect clipRect)
{
PaintAllOverlay(clipRect);
foreach (var ve in m_CleanUpOverlay)
{
m_OverlayData.Remove(ve);
}
m_CleanUpOverlay.Clear();
}
void PaintAllOverlay(Rect clipRect)
{
using (new GUIClip.ParentClipScope(Matrix4x4.identity, clipRect))
{
HandleUtility.ApplyWireMaterial();
GL.PushMatrix();
foreach (var kvp in m_OverlayData)
{
var overlayData = kvp.Value;
overlayData.alpha -= overlayData.fadeOutRate;
DrawOverlayData(overlayData);
if (overlayData.alpha < Mathf.Epsilon)
{
m_CleanUpOverlay.Add(kvp.Key);
}
}
GL.PopMatrix();
}
}
public int overlayCount
{
get { return m_OverlayData.Count; }
}
public void ClearOverlay()
{
m_OverlayData.Clear();
}
protected abstract void DrawOverlayData(OverlayData overlayData);
protected void DrawRect(Rect rect, Color color, float alpha)
{
float x0 = rect.x;
float x3 = rect.xMax;
float y0 = rect.yMax;
float y3 = rect.y;
color.a = alpha;
GL.Begin(GL.TRIANGLES);
GL.Color(color);
GL.Vertex3(x0, y0, 0);
GL.Vertex3(x3, y0, 0);
GL.Vertex3(x0, y3, 0);
GL.Vertex3(x3, y0, 0);
GL.Vertex3(x3, y3, 0);
GL.Vertex3(x0, y3, 0);
GL.End();
}
protected void DrawBorder(Rect rect, Color color, float alpha)
{
rect.xMin++;
rect.xMax--;
rect.yMin++;
rect.yMax--;
color.a = alpha;
GL.Begin(GL.LINES);
GL.Color(color);
GL.Vertex3(rect.xMin, rect.yMin, 0);
GL.Vertex3(rect.xMax, rect.yMin, 0);
GL.Vertex3(rect.xMax, rect.yMin, 0);
GL.Vertex3(rect.xMax, rect.yMax, 0);
GL.Vertex3(rect.xMax, rect.yMax, 0);
GL.Vertex3(rect.xMin, rect.yMax, 0);
GL.Vertex3(rect.xMin, rect.yMax, 0);
GL.Vertex3(rect.xMin, rect.yMin, 0);
GL.End();
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/ElementHierarchyView/BaseOverlayPainter.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/ElementHierarchyView/BaseOverlayPainter.cs",
"repo_id": "UnityCsReference",
"token_count": 2018
} | 482 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class ModalPopup : VisualElement
{
static readonly string s_UssClassName = "unity-modal-popup";
static readonly string s_InvisibleClassName = "unity-modal-popup--invisible";
Label m_Title;
VisualElement m_Container;
[Serializable]
public new class UxmlSerializedData : VisualElement.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField] string title;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags title_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new ModalPopup();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
if (ShouldWriteAttributeValue(title_UxmlAttributeFlags))
{
var e = (ModalPopup)obj;
e.title = title;
}
}
}
public string title
{
get { return m_Title.text; }
set { m_Title.text = value; }
}
public override VisualElement contentContainer => m_Container == null ? this : m_Container;
public ModalPopup()
{
AddToClassList(s_UssClassName);
AddToClassList(s_InvisibleClassName);
// Load styles.
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UtilitiesPath + "/ModalPopup/ModalPopup.uss"));
if (EditorGUIUtility.isProSkin)
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UtilitiesPath + "/ModalPopup/ModalPopupDark.uss"));
else
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UtilitiesPath + "/ModalPopup/ModalPopupLight.uss"));
var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(BuilderConstants.UtilitiesPath + "/ModalPopup/ModalPopup.uxml");
template.CloneTree(this);
m_Title = this.Q<Label>("title");
m_Container = this.Q("content-container");
var window = this.Q("window");
window.RegisterCallback<MouseUpEvent>(StopPropagation);
this.RegisterCallback<MouseUpEvent>(HideOnClick);
}
public void Show()
{
RemoveFromClassList(s_InvisibleClassName);
}
public void Hide()
{
AddToClassList(s_InvisibleClassName);
}
void HideOnClick(MouseUpEvent evt)
{
Hide();
}
void StopPropagation(MouseUpEvent evt)
{
evt.StopPropagation();
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/ModalPopup/ModalPopup.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/ModalPopup/ModalPopup.cs",
"repo_id": "UnityCsReference",
"token_count": 1376
} | 483 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using JetBrains.Annotations;
using System;
using UnityEngine;
using UnityEngine.TextCore.Text;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
[UsedImplicitly]
class FontDefinitionStyleField : MultiTypeField
{
[Serializable]
public new class UxmlSerializedData : MultiTypeField.UxmlSerializedData
{
public override object CreateInstance() => new FontDefinitionStyleField();
}
const string k_UssPath = BuilderConstants.UtilitiesPath + "/StyleField/FontDefinitionStyleField.uss";
const string k_FieldInputName = "unity-visual-input";
const string k_FontDefinitionStyleFieldContainerName = "unity-font-definition-style-field-container";
const string k_FontDefinitionStyleFieldContainerClassName = "unity-font-definition-style-field__container";
public FontDefinitionStyleField() : this(null) {}
public FontDefinitionStyleField(string label) : base(label)
{
AddType(typeof(FontAsset), "Font Asset");
AddType(typeof(Font), "Font");
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(k_UssPath));
var fieldContainer = new VisualElement {name = k_FontDefinitionStyleFieldContainerName};
fieldContainer.AddToClassList(k_FontDefinitionStyleFieldContainerClassName);
var fieldInput = this.Q(k_FieldInputName);
// Move visual input over to field container
fieldContainer.Add(fieldInput);
Add(fieldContainer);
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FontDefinitionStyleField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FontDefinitionStyleField.cs",
"repo_id": "UnityCsReference",
"token_count": 622
} | 484 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using JetBrains.Annotations;
using UnityEngine.UIElements;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements.StyleSheets;
using System;
namespace Unity.UI.Builder
{
internal struct BuilderTextShadow
{
public Dimension offsetX;
public Dimension offsetY;
public Dimension blurRadius;
public Color color;
public BuilderTextShadow(StyleTextShadow styleTextShadow)
{
var textShadow = styleTextShadow.value;
offsetX = new Dimension(textShadow.offset.x, Dimension.Unit.Pixel);
offsetY = new Dimension(textShadow.offset.y, Dimension.Unit.Pixel);
blurRadius = new Dimension(textShadow.blurRadius, Dimension.Unit.Pixel);
color = textShadow.color;
}
public BuilderTextShadow(TextShadow textShadow)
{
offsetX = new Dimension(textShadow.offset.x, Dimension.Unit.Pixel);
offsetY = new Dimension(textShadow.offset.y, Dimension.Unit.Pixel);
blurRadius = new Dimension(textShadow.blurRadius, Dimension.Unit.Pixel);
color = textShadow.color;
}
}
[UsedImplicitly]
class TextShadowStyleField : BaseField<BuilderTextShadow>
{
public class TextShadowStyleFieldConverter : UxmlAttributeConverter<BuilderTextShadow>
{
public override BuilderTextShadow FromString(string value) => throw new NotImplementedException();
public override string ToString(BuilderTextShadow value) => throw new NotImplementedException();
}
[Serializable]
public new class UxmlSerializedData : BaseField<BuilderTextShadow>.UxmlSerializedData
{
public override object CreateInstance() => new TextShadowStyleField();
}
static readonly string s_FieldClassName = "unity-text-shadow-style-field";
static readonly string s_UxmlPath = BuilderConstants.UtilitiesPath + "/StyleField/TextShadowStyleField.uxml";
static readonly string s_UssPath = BuilderConstants.UtilitiesPath + "/StyleField/TextFoldoutStyleField.uss";
private static readonly string s_TextShadowFieldName = "text-shadow-field";
static readonly string s_OffsetXFieldName = s_TextShadowFieldName + "-offset-x";
static readonly string s_OffsetYFieldName = s_TextShadowFieldName + "-offset-y";
static readonly string s_BlurRadiusFieldName = s_TextShadowFieldName + "-blur-radius";
private static readonly string s_ColorFieldName = s_TextShadowFieldName + "-color";
DimensionStyleField m_OffsetXField;
DimensionStyleField m_OffsetYField;
DimensionStyleField m_BlurRadiusField;
ColorField m_ColorField;
public TextShadowStyleField() : this(null) {}
public TextShadowStyleField(string label) : base(label)
{
AddToClassList(s_FieldClassName);
styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(s_UssPath));
var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(s_UxmlPath);
template.CloneTree(this);
m_OffsetXField = this.Q<DimensionStyleField>(s_OffsetXFieldName);
m_OffsetYField = this.Q<DimensionStyleField>(s_OffsetYFieldName);
m_BlurRadiusField = this.Q<DimensionStyleField>(s_BlurRadiusFieldName);
m_OffsetXField.dragStep = BuilderConstants.DimensionStyleFieldReducedDragStep;
m_OffsetYField.dragStep = BuilderConstants.DimensionStyleFieldReducedDragStep;
m_BlurRadiusField.dragStep = BuilderConstants.DimensionStyleFieldReducedDragStep;
m_ColorField = this.Q<ColorField>(s_ColorFieldName);
m_OffsetXField.RegisterValueChangedCallback(e =>
{
UpdateTextShadowField();
e.StopPropagation();
});
m_OffsetYField.RegisterValueChangedCallback(e =>
{
UpdateTextShadowField();
e.StopPropagation();
});
m_BlurRadiusField.RegisterValueChangedCallback(e =>
{
UpdateTextShadowField();
e.StopPropagation();
});
m_ColorField.RegisterValueChangedCallback(e =>
{
UpdateTextShadowField();
e.StopPropagation();
});
}
public override void SetValueWithoutNotify(BuilderTextShadow newValue)
{
base.SetValueWithoutNotify(newValue);
RefreshSubFields();
}
void RefreshSubFields()
{
m_OffsetXField.SetValueWithoutNotify(value.offsetX.ToString());
m_OffsetYField.SetValueWithoutNotify(value.offsetY.ToString());
m_BlurRadiusField.SetValueWithoutNotify(value.blurRadius.ToString());
m_ColorField.SetValueWithoutNotify(value.color);
}
void UpdateTextShadowField()
{
// Rebuild value from sub fields
BuilderTextShadow builderTextShadow;
builderTextShadow.offsetX = new Dimension { value = m_OffsetXField.length, unit = m_OffsetXField.unit };
builderTextShadow.offsetY = new Dimension { value = m_OffsetYField.length, unit = m_OffsetYField.unit };
builderTextShadow.blurRadius = new Dimension { value = m_BlurRadiusField.length, unit = m_BlurRadiusField.unit };
builderTextShadow.color = m_ColorField.value;
value = builderTextShadow;
}
public bool OnFieldValueChange(StyleProperty styleProperty, StyleSheet styleSheet)
{
var stylePropertyValueCount = styleProperty.values.Length;
var isNewValue = stylePropertyValueCount == 0;
// Assume that TextShadow style property is made of 2+ values at all times at this point
// If the current style property is saved as a different type than the new style type,
// we need to re-save it here as the new type. We do this by just removing the current value.
if (!isNewValue && stylePropertyValueCount != 4 ||
!isNewValue && styleProperty.values[0].valueType != StyleValueType.Dimension ||
!isNewValue && styleProperty.values[1].valueType != StyleValueType.Dimension ||
!isNewValue && styleProperty.values[2].valueType != StyleValueType.Dimension ||
!isNewValue && styleProperty.values[3].valueType != StyleValueType.Color)
{
Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage);
styleProperty.values = new StyleValueHandle[0];
isNewValue = true;
}
var offsetX = new Dimension {value = m_OffsetXField.length, unit = m_OffsetXField.unit};
var offsetY = new Dimension {value = m_OffsetYField.length, unit = m_OffsetYField.unit};
var blurRadius = new Dimension {value = m_BlurRadiusField.length, unit = m_BlurRadiusField.unit};
if (isNewValue)
{
styleSheet.AddValue(styleProperty, offsetX);
styleSheet.AddValue(styleProperty, offsetY);
styleSheet.AddValue(styleProperty, blurRadius);
styleSheet.AddValue(styleProperty, m_ColorField.value);
}
else
{
styleSheet.SetValue(styleProperty.values[0], offsetX);
styleSheet.SetValue(styleProperty.values[1], offsetY);
styleSheet.SetValue(styleProperty.values[2], blurRadius);
styleSheet.SetValue(styleProperty.values[3], m_ColorField.value);
}
return isNewValue;
}
internal void UpdateSubFieldVisualInputTooltips(string offsetXTooltip, string offsetYTooltip, string blurRadiusTooltip, string colorTooltip)
{
m_OffsetXField.visualInput.tooltip = offsetXTooltip;
m_OffsetYField.visualInput.tooltip = offsetYTooltip;
m_BlurRadiusField.visualInput.tooltip = blurRadiusTooltip;
m_ColorField.visualInput.tooltip = colorTooltip;
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/TextShadowStyleField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/TextShadowStyleField.cs",
"repo_id": "UnityCsReference",
"token_count": 3494
} | 485 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Globalization;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.UIElements.StyleSheets;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
internal class UssExportOptions
{
public UssExportOptions()
{
propertyIndent = " ";
exportDefaultValues = true;
}
public UssExportOptions(UssExportOptions opts)
: base()
{
propertyIndent = opts.propertyIndent;
exportDefaultValues = opts.exportDefaultValues;
}
public string propertyIndent { get; set; }
public bool useColorCode { get; set; }
public bool exportDefaultValues { get; set; }
}
internal class StyleSheetToUss
{
static int ColorComponent(float component)
{
return (int)Math.Round(component * byte.MaxValue, 0, MidpointRounding.AwayFromZero);
}
public static string ToUssString(Color color, bool useColorCode = false)
{
string str;
string alpha = color.a.ToString("0.##", CultureInfo.InvariantCulture.NumberFormat);
if (alpha != "1")
{
str = UnityString.Format("rgba({0}, {1}, {2}, {3:F2})", ColorComponent(color.r),
ColorComponent(color.g),
ColorComponent(color.b),
alpha);
}
else if (!useColorCode)
{
str = UnityString.Format("rgb({0}, {1}, {2})",
ColorComponent(color.r),
ColorComponent(color.g),
ColorComponent(color.b));
}
else
{
str = UnityString.Format("#{0}", ColorUtility.ToHtmlStringRGB(color));
}
return str;
}
public static string ValueHandleToUssString(StyleSheet sheet, UssExportOptions options, string propertyName, StyleValueHandle handle)
{
string str = "";
switch (handle.valueType)
{
case StyleValueType.Keyword:
str = sheet.ReadKeyword(handle).ToString().ToLower();
break;
case StyleValueType.Float:
{
var num = sheet.ReadFloat(handle);
if (num == 0)
{
str = "0";
}
else
{
str = num.ToString(CultureInfo.InvariantCulture.NumberFormat);
if (IsLength(propertyName))
str += "px";
}
}
break;
case StyleValueType.Dimension:
var dim = sheet.ReadDimension(handle);
if (dim.value == 0 && !dim.unit.IsTimeUnit())
str = "0";
else
str = dim.ToString();
break;
case StyleValueType.Color:
UnityEngine.Color color = sheet.ReadColor(handle);
str = ToUssString(color, options.useColorCode);
break;
case StyleValueType.ResourcePath:
str = $"resource('{sheet.ReadResourcePath(handle)}')";
break;
case StyleValueType.Enum:
str = sheet.ReadEnum(handle);
break;
case StyleValueType.String:
str = $"\"{sheet.ReadString(handle)}\"";
break;
case StyleValueType.MissingAssetReference:
str = $"url('{sheet.ReadMissingAssetReferenceUrl(handle)}')";
break;
case StyleValueType.AssetReference:
var assetRef = sheet.ReadAssetReference(handle);
str = GetPathValueFromAssetRef(assetRef);
break;
case StyleValueType.Variable:
str = sheet.ReadVariable(handle);
break;
case StyleValueType.ScalableImage:
var image = sheet.ReadScalableImage(handle);
var normalImage = image.normalImage;
str = GetPathValueFromAssetRef(normalImage);
break;
default:
throw new ArgumentException("Unhandled type " + handle.valueType);
}
return str;
}
private static string GetPathValueFromAssetRef(UnityEngine.Object assetRef)
{
var assetPath = URIHelpers.MakeAssetUri(assetRef);
return assetRef == null ? "none" : $"url(\"{assetPath}\")";
}
public static void ValueHandlesToUssString(StringBuilder sb, StyleSheet sheet, UssExportOptions options, string propertyName, StyleValueHandle[] values, ref int valueIndex, int valueCount = -1)
{
for (; valueIndex < values.Length && valueCount != 0; --valueCount)
{
var propertyValue = values[valueIndex++];
switch (propertyValue.valueType)
{
case StyleValueType.Function:
// First param: function name
sb.Append(sheet.ReadFunctionName(propertyValue));
sb.Append("(");
// Second param: number of arguments
var nbParams = (int)sheet.ReadFloat(values[valueIndex++]);
ValueHandlesToUssString(sb, sheet, options, propertyName, values, ref valueIndex, nbParams);
sb.Append(")");
break;
case StyleValueType.CommaSeparator:
sb.Append(",");
break;
default:
{
var propertyValueStr = ValueHandleToUssString(sheet, options, propertyName, propertyValue);
sb.Append(propertyValueStr);
break;
}
}
if (valueIndex < values.Length && values[valueIndex].valueType != StyleValueType.CommaSeparator && valueCount != 1)
{
sb.Append(" ");
}
}
}
static bool IsLength(string name)
{
if (BuilderConstants.SpecialSnowflakeLengthStyles.Contains(name))
return true;
return false;
}
public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleRule rule, StringBuilder sb)
{
foreach (var property in rule.properties)
{
if (property.name == BuilderConstants.SelectedStyleRulePropertyName)
continue;
sb.Append(options.propertyIndent);
sb.Append(property.name);
sb.Append(":");
ToUssString(sheet, options, property, sb);
sb.Append(";");
sb.Append(BuilderConstants.newlineCharFromEditorSettings);
}
}
public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleProperty property, StringBuilder sb)
{
if (property.name == "cursor" && property.values.Length > 1 && !property.IsVariable())
{
for (var i = 0; i < property.values.Length; i++)
{
var propertyValueStr = ValueHandleToUssString(sheet, options, property.name, property.values[i]);
sb.Append(" ");
sb.Append(propertyValueStr);
}
}
else
{
var valueIndex = 0;
sb.Append(" ");
ValueHandlesToUssString(sb, sheet, options, property.name, property.values, ref valueIndex);
}
}
public static void ToUssString(StyleSelectorRelationship previousRelationship, StyleSelectorPart[] parts, StringBuilder sb)
{
if (previousRelationship != StyleSelectorRelationship.None)
sb.Append(previousRelationship == StyleSelectorRelationship.Child ? " > " : " ");
foreach (var selectorPart in parts)
{
switch (selectorPart.type)
{
case StyleSelectorType.Wildcard:
sb.Append('*');
break;
case StyleSelectorType.Type:
sb.Append(selectorPart.value);
break;
case StyleSelectorType.Class:
sb.Append('.');
sb.Append(selectorPart.value);
break;
case StyleSelectorType.PseudoClass:
sb.Append(':');
sb.Append(selectorPart.value);
break;
case StyleSelectorType.ID:
sb.Append('#');
sb.Append(selectorPart.value);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
public static string ToUssSelector(StyleComplexSelector complexSelector)
{
var sb = new StringBuilder();
foreach (var selector in complexSelector.selectors)
{
ToUssString(selector.previousRelationship, selector.parts, sb);
}
return sb.ToString();
}
public static string ToUssString(StyleSheet sheet, StyleComplexSelector complexSelector, StringBuilder stringBuilder = null)
{
var inlineBuilder = stringBuilder == null ? new StringBuilder() : stringBuilder;
ToUssString(sheet, new UssExportOptions(), complexSelector, inlineBuilder);
var result = inlineBuilder.ToString();
return result;
}
public static void ToUssString(StyleSheet sheet, UssExportOptions options, StyleComplexSelector complexSelector, StringBuilder sb)
{
foreach (var selector in complexSelector.selectors)
ToUssString(selector.previousRelationship, selector.parts, sb);
sb.Append(" {");
sb.Append(BuilderConstants.newlineCharFromEditorSettings);
ToUssString(sheet, options, complexSelector.rule, sb);
sb.Append("}");
sb.Append(BuilderConstants.newlineCharFromEditorSettings);
}
public static string ToUssString(StyleSheet sheet, UssExportOptions options = null)
{
if (options == null)
options = new UssExportOptions();
var sb = new StringBuilder();
if (sheet.imports != null)
{
for (var i = 0; i < sheet.imports.Length; ++i)
{
var import = sheet.imports[i];
if (!import.styleSheet)
continue;
var stylesheetImportPath = GetPathValueFromAssetRef(import.styleSheet);
// Skip invalid references.
if (stylesheetImportPath == "none")
continue;
sb.Append($"@import {stylesheetImportPath};");
sb.Append(BuilderConstants.newlineCharFromEditorSettings);
}
}
if (sheet.complexSelectors != null)
{
bool isFirst = true;
for (var complexSelectorIndex = 0; complexSelectorIndex < sheet.complexSelectors.Length; ++complexSelectorIndex)
{
var complexSelector = sheet.complexSelectors[complexSelectorIndex];
// Omit special selection rule.
if (complexSelector.selectors.Length > 0 &&
complexSelector.selectors[0].parts.Length > 0 &&
(complexSelector.selectors[0].parts[0].value == BuilderConstants.SelectedStyleSheetSelectorName
|| complexSelector.selectors[0].parts[0].value.StartsWith(BuilderConstants.StyleSelectorElementName)
)
)
continue;
if (isFirst)
isFirst = false;
else
sb.Append(BuilderConstants.newlineCharFromEditorSettings);
ToUssString(sheet, options, complexSelector, sb);
}
}
return sb.ToString();
}
public static void WriteStyleSheet(StyleSheet sheet, string path, UssExportOptions options = null)
{
File.WriteAllText(path, ToUssString(sheet, options));
}
}
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleSheetToUss.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StyleSheetToUss.cs",
"repo_id": "UnityCsReference",
"token_count": 7033
} | 486 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Reflection;
using UnityEngine;
using UnityEngine.UIElements;
namespace Unity.UI.Builder
{
#pragma warning disable CS0618 // Type or member is obsolete
internal static class IUXMLFactoryExtensions
{
internal static readonly string s_TraitsNotFoundMessage = "UI Builder: IUxmlFactory.m_Traits field has not been found! Update the reflection code!";
internal static readonly string s_UxmlTypeNotFoundMessage = "UI Builder: IUxmlFactory.uxmlType property has not been found! Update the reflection code!";
public static BaseUxmlTraits GetTraits(this IBaseUxmlFactory factory)
{
var traitsField = factory.GetType()
.GetField("m_Traits", BindingFlags.Instance | BindingFlags.NonPublic);
if (traitsField == null)
{
Debug.LogError(s_TraitsNotFoundMessage);
return null;
}
return traitsField.GetValue(factory) as BaseUxmlTraits;
}
public static Type GetUxmlType(this IBaseUxmlFactory factory)
{
var uxmlTypeProperty = factory.GetType()
.GetProperty("uxmlType");
if (uxmlTypeProperty == null)
{
Debug.LogError(s_UxmlTypeNotFoundMessage);
return null;
}
return uxmlTypeProperty.GetValue(factory) as Type;
}
}
#pragma warning restore CS0618 // Type or member is obsolete
}
| UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualTreeAssetExtensions/IUxmlFactoryExtensions.cs/0 | {
"file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/VisualTreeAssetExtensions/IUxmlFactoryExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 671
} | 487 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Properties;
namespace UnityEngine.UIElements
{
public partial struct BackgroundSize
{
internal class PropertyBag : ContainerPropertyBag<BackgroundSize>
{
class SizeTypeProperty : Property<BackgroundSize, BackgroundSizeType>
{
public override string Name { get; } = nameof(sizeType);
public override bool IsReadOnly { get; } = false;
public override BackgroundSizeType GetValue(ref BackgroundSize container) => container.sizeType;
public override void SetValue(ref BackgroundSize container, BackgroundSizeType value) => container.sizeType = value;
}
class XProperty : Property<BackgroundSize, Length>
{
public override string Name { get; } = nameof(x);
public override bool IsReadOnly { get; } = false;
public override Length GetValue(ref BackgroundSize container) => container.x;
public override void SetValue(ref BackgroundSize container, Length value) => container.x = value;
}
class YProperty : Property<BackgroundSize, Length>
{
public override string Name { get; } = nameof(y);
public override bool IsReadOnly { get; } = false;
public override Length GetValue(ref BackgroundSize container) => container.y;
public override void SetValue(ref BackgroundSize container, Length value) => container.y = value;
}
public PropertyBag()
{
AddProperty(new SizeTypeProperty());
AddProperty(new XProperty());
AddProperty(new YProperty());
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/BackgroundSize.PropertyBag.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/BackgroundSize.PropertyBag.cs",
"repo_id": "UnityCsReference",
"token_count": 779
} | 488 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using Unity.Properties;
using UnityEngine.Assertions;
using UnityEngine.Pool;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEngine.UIElements
{
/// <summary>
/// Options to change the log level for warnings that occur during the update of data bindings.
/// </summary>
/// <remarks>
/// This option can be changed using <see cref="Binding.SetGlobalLogLevel"/> or <see cref="Binding.SetPanelLogLevel"/>.
/// Changing the global level won't change the log level of a panel if it already has an override.
/// </remarks>
public enum BindingLogLevel
{
/// <summary>
/// Never log warnings.
/// </summary>
[InspectorName("No logs")]
None,
/// <summary>
/// Log warnings only once when the result of the binding changes.
/// </summary>
[InspectorName("One log per result")]
Once,
/// <summary>
/// Log warnings to the console when a binding is updated.
/// </summary>
[InspectorName("All logs")]
All,
}
sealed class DataBindingManager : IDisposable
{
private readonly List<BindingData> m_BindingDataLocalPool = new List<BindingData>(64);
static readonly PropertyName k_RequestBindingPropertyName = "__unity-binding-request";
static readonly BindingId k_ClearBindingsToken = "$__BindingManager--ClearAllBindings";
internal static BindingLogLevel globalLogLevel = BindingLogLevel.All;
BindingLogLevel? m_LogLevel;
internal BindingLogLevel logLevel
{
get => m_LogLevel ?? globalLogLevel;
set => m_LogLevel = value;
}
// Also used in tests.
internal void ResetLogLevel()
{
m_LogLevel = null;
}
readonly struct BindingRequest
{
public readonly BindingId bindingId;
public readonly Binding binding;
public readonly bool shouldProcess;
public BindingRequest(in BindingId bindingId, Binding binding, bool shouldProcess = true)
{
this.bindingId = bindingId;
this.binding = binding;
this.shouldProcess = shouldProcess;
}
public BindingRequest CancelRequest()
{
return new BindingRequest(bindingId, binding, false);
}
}
struct BindingDataCollection : IDisposable
{
Dictionary<BindingId, BindingData> m_BindingPerId;
List<BindingData> m_Bindings;
public static BindingDataCollection Create()
{
var collection = new BindingDataCollection();
collection.m_BindingPerId = DictionaryPool<BindingId, BindingData>.Get();
collection.m_Bindings = ListPool<BindingData>.Get();
return collection;
}
public void AddBindingData(BindingData bindingData)
{
if (m_BindingPerId.TryGetValue(bindingData.target.bindingId, out var toRemove))
{
m_Bindings.Remove(toRemove);
}
m_BindingPerId[bindingData.target.bindingId] = bindingData;
m_Bindings.Add(bindingData);
}
public bool TryGetBindingData(in BindingId bindingId, out BindingData data)
{
return m_BindingPerId.TryGetValue(bindingId, out data);
}
public bool RemoveBindingData(BindingData bindingData)
{
if (!m_BindingPerId.TryGetValue(bindingData.target.bindingId, out var toRemove))
return false;
return m_Bindings.Remove(toRemove) && m_BindingPerId.Remove(toRemove.target.bindingId);
}
public List<BindingData> GetBindings()
{
return m_Bindings;
}
public int GetBindingCount()
{
return m_Bindings.Count;
}
public void Dispose()
{
if (m_BindingPerId != null)
DictionaryPool<BindingId, BindingData>.Release(m_BindingPerId);
m_BindingPerId = null;
if (m_Bindings != null)
ListPool<BindingData>.Release(m_Bindings);
m_Bindings = null;
}
}
internal class BindingData
{
public long version;
public BindingTarget target;
public Binding binding;
private DataSourceContext m_LastContext;
public object localDataSource { get; set; }
public void Reset()
{
++version;
target = default;
binding = default;
localDataSource = default;
m_LastContext = default;
m_SourceToUILastUpdate = null;
m_UIToSourceLastUpdate = null;
}
public DataSourceContext context
{
get => m_LastContext;
set
{
if (m_LastContext.dataSource == value.dataSource && m_LastContext.dataSourcePath == value.dataSourcePath)
return;
var previous = m_LastContext;
m_LastContext = value;
binding.OnDataSourceChanged(new DataSourceContextChanged(target.element, target.bindingId, previous, value));
binding.MarkDirty();
}
}
public BindingResult? m_SourceToUILastUpdate;
public BindingResult? m_UIToSourceLastUpdate;
}
internal readonly struct ChangesFromUI
{
public readonly long version;
public readonly Binding binding;
public readonly BindingData bindingData;
public ChangesFromUI(BindingData bindingData)
{
this.bindingData = bindingData;
this.version = bindingData.version;
this.binding = bindingData.binding;
}
public bool IsValid => version == bindingData.version && binding == bindingData.binding;
}
static readonly List<BindingData> s_Empty = new List<BindingData>();
class HierarchyBindingTracker : IDisposable
{
class HierarchicalBindingsSorter : HierarchyTraversal
{
public HashSet<VisualElement> boundElements { get; set; }
public List<VisualElement> results { get; set; }
public override void TraverseRecursive(VisualElement element, int depth)
{
if (boundElements.Count == results.Count)
return;
if (boundElements.Contains(element))
results.Add(element);
Recurse(element, depth);
}
}
readonly BaseVisualElementPanel m_Panel;
readonly HierarchicalBindingsSorter m_BindingSorter;
readonly Dictionary<VisualElement, BindingDataCollection> m_BindingDataPerElement;
readonly HashSet<VisualElement> m_BoundElements;
readonly List<VisualElement> m_OrderedBindings;
bool m_IsDirty;
public int GetTrackedElementsCount()
{
return m_BoundElements.Count;
}
public List<VisualElement> GetBoundElements()
{
if (m_IsDirty)
OrderBindings(m_Panel.visualTree);
return m_OrderedBindings;
}
public IEnumerable<VisualElement> GetUnorderedBoundElements()
{
return m_BoundElements;
}
public HierarchyBindingTracker(BaseVisualElementPanel panel)
{
m_Panel = panel;
m_BindingSorter = new HierarchicalBindingsSorter();
m_BindingDataPerElement = new Dictionary<VisualElement, BindingDataCollection>();
m_BoundElements = new HashSet<VisualElement>();
m_OrderedBindings = new List<VisualElement>();
m_IsDirty = true;
m_OnPropertyChanged = OnPropertyChanged;
}
public void SetDirty()
{
m_IsDirty = true;
}
public bool TryGetBindingCollection(VisualElement element, out BindingDataCollection collection)
{
return m_BindingDataPerElement.TryGetValue(element, out collection);
}
public bool IsTrackingElement(VisualElement element)
{
return m_BoundElements.Contains(element);
}
public void StartTrackingBinding(VisualElement element, BindingData binding)
{
BindingDataCollection collection;
if (m_BoundElements.Add(element))
{
collection = BindingDataCollection.Create();
m_BindingDataPerElement.Add(element, collection);
element.RegisterCallback(m_OnPropertyChanged, m_BindingDataPerElement);
}
else if (!m_BindingDataPerElement.TryGetValue(element, out collection))
{
throw new InvalidOperationException("Trying to add a binding to an element which doesn't have a binding collection. This is an internal bug. Please report using `Help > Report a Bug...`");
}
binding.binding.MarkDirty();
collection.AddBindingData(binding);
m_BindingDataPerElement[element] = collection;
SetDirty();
}
private EventCallback<PropertyChangedEvent, Dictionary<VisualElement, BindingDataCollection>> m_OnPropertyChanged;
private void OnPropertyChanged(PropertyChangedEvent evt, Dictionary<VisualElement, BindingDataCollection> bindingCollection)
{
if (evt.target is not VisualElement target)
throw new InvalidOperationException($"Trying to track property changes on a non '{nameof(VisualElement)}'. This is an internal bug. Please report using `Help > Report a Bug...`");
if (!bindingCollection.TryGetValue(target, out var collection))
throw new InvalidOperationException($"Trying to track property changes on a '{nameof(VisualElement)}' that is not being tracked. This is an internal bug. Please report using `Help > Report a Bug...`");
if (collection.TryGetBindingData(evt.property, out var bindingData) &&
target.TryGetBinding(evt.property, out var current) &&
bindingData.binding == current)
m_Panel.dataBindingManager.m_DetectedChangesFromUI.Add(new ChangesFromUI(bindingData));
}
public void StopTrackingBinding(VisualElement element, BindingData binding)
{
if (m_BoundElements.Contains(element) && m_BindingDataPerElement.TryGetValue(element, out var collection))
{
collection.RemoveBindingData(binding);
if (collection.GetBindingCount() == 0)
{
StopTrackingElement(element);
element.UnregisterCallback(m_OnPropertyChanged);
}
else
{
m_BindingDataPerElement[element] = collection;
}
}
else
{
throw new InvalidOperationException("Trying to remove a binding to an element which doesn't have a binding collection. This is an internal bug. Please report using `Help > Report a Bug...`");
}
SetDirty();
}
public void StopTrackingElement(VisualElement element)
{
if (m_BindingDataPerElement.TryGetValue(element, out var collection))
{
collection.Dispose();
}
m_BindingDataPerElement.Remove(element);
m_BoundElements.Remove(element);
SetDirty();
}
public void Dispose()
{
foreach (var kvp in m_BindingDataPerElement)
{
kvp.Value.Dispose();
}
m_BindingDataPerElement.Clear();
m_BoundElements.Clear();
m_OrderedBindings.Clear();
}
void OrderBindings(VisualElement root)
{
m_OrderedBindings.Clear();
m_BindingSorter.boundElements = m_BoundElements;
m_BindingSorter.results = m_OrderedBindings;
m_BindingSorter.Traverse(root);
m_IsDirty = false;
}
}
class HierarchyDataSourceTracker : IDisposable
{
private readonly List<SourceInfo> m_SourceInfosPool = new List<SourceInfo>();
private SourceInfo GetPooledSourceInfo()
{
SourceInfo info;
if (m_SourceInfosPool.Count > 0)
{
info = m_SourceInfosPool[^1];
m_SourceInfosPool.RemoveAt(m_SourceInfosPool.Count - 1);
}
else
info = new SourceInfo();
return info;
}
private void ReleasePooledSourceInfo(SourceInfo info)
{
info.lastVersion = long.MinValue;
info.refCount = 0;
info.detectedChangesNoAlloc?.Clear();
m_SourceInfosPool.Add(info);
}
class SourceInfo
{
private List<PropertyPath> m_DetectedChanges;
public long lastVersion { get; set; }
public int refCount { get; set; }
public List<PropertyPath> detectedChanges => m_DetectedChanges ??= new List<PropertyPath>();
public List<PropertyPath> detectedChangesNoAlloc => m_DetectedChanges;
}
class InvalidateDataSourcesTraversal : HierarchyTraversal
{
readonly HierarchyDataSourceTracker m_DataSourceTracker;
readonly HashSet<VisualElement> m_VisitedElements;
public InvalidateDataSourcesTraversal(HierarchyDataSourceTracker dataSourceTracker)
{
m_DataSourceTracker = dataSourceTracker;
m_VisitedElements = new HashSet<VisualElement>();
}
public void Invalidate(List<VisualElement> addedOrMovedElements, HashSet<VisualElement> removedElements)
{
m_VisitedElements.Clear();
for (var i = 0; i < addedOrMovedElements.Count; ++i)
{
var element = addedOrMovedElements[i];
Traverse(element);
}
foreach (var element in removedElements)
{
// If the element was visited as part of the addedOrMovedElements list, it means the removed
// element is still part of the hierarchy and was already treated .
if (m_VisitedElements.Contains(element))
continue;
Traverse(element);
}
}
public override void TraverseRecursive(VisualElement element, int depth)
{
if (m_VisitedElements.Contains(element))
return;
if (depth > 0 && null != element.dataSource)
return;
m_VisitedElements.Add(element);
m_DataSourceTracker.RemoveHierarchyDataSourceContextFromElement(element);
Recurse(element, depth);
}
}
readonly DataBindingManager m_DataBindingManager;
private readonly Dictionary<VisualElement, DataSourceContext> m_ResolvedHierarchicalDataSourceContext;
readonly Dictionary<Binding, int> m_BindingRefCount;
readonly Dictionary<object, SourceInfo> m_SourceInfos;
private readonly HashSet<object> m_SourcesToRemove;
readonly InvalidateDataSourcesTraversal m_InvalidateResolvedDataSources;
readonly EventHandler<BindablePropertyChangedEventArgs> m_Handler;
readonly EventCallback<PropertyChangedEvent, VisualElement> m_VisualElementHandler;
public HierarchyDataSourceTracker(DataBindingManager manager)
{
m_DataBindingManager = manager;
m_ResolvedHierarchicalDataSourceContext = new Dictionary<VisualElement, DataSourceContext>();
m_BindingRefCount = new Dictionary<Binding, int>();
m_SourceInfos = new Dictionary<object, SourceInfo>();
m_SourcesToRemove = new HashSet<object>();
m_InvalidateResolvedDataSources = new InvalidateDataSourcesTraversal(this);
m_Handler = TrackPropertyChanges;
m_VisualElementHandler = OnVisualElementPropertyChanged;
}
internal void IncreaseBindingRefCount(ref BindingData bindingData)
{
var binding = bindingData.binding;
if (null == binding)
return;
if (!m_BindingRefCount.TryGetValue(binding, out var refCount))
{
refCount = 0;
}
if (binding is IDataSourceProvider dataSourceProvider)
{
IncreaseRefCount(dataSourceProvider.dataSource);
bindingData.localDataSource = dataSourceProvider.dataSource;
}
m_BindingRefCount[binding] = refCount + 1;
}
internal void DecreaseBindingRefCount(ref BindingData bindingData)
{
var binding = bindingData.binding;
if (null == binding)
return;
if (!m_BindingRefCount.TryGetValue(binding, out var refCount))
{
throw new InvalidOperationException("Trying to release a binding that isn't tracked. This is an internal bug. Please report using `Help > Report a Bug...`");
}
if (refCount == 1)
{
m_BindingRefCount.Remove(binding);
}
else
{
m_BindingRefCount[binding] = refCount - 1;
}
if (binding is IDataSourceProvider dataSourceProvider)
DecreaseRefCount(dataSourceProvider.dataSource);
}
internal void IncreaseRefCount(object dataSource)
{
if (null == dataSource)
return;
m_SourcesToRemove.Remove(dataSource);
if (!m_SourceInfos.TryGetValue(dataSource, out var info))
{
m_SourceInfos[dataSource] = info = GetPooledSourceInfo();
if (dataSource is INotifyBindablePropertyChanged notifier)
notifier.propertyChanged += m_Handler;
if (dataSource is VisualElement element)
element.RegisterCallback(m_VisualElementHandler, element);
}
++info.refCount;
}
private void OnVisualElementPropertyChanged(PropertyChangedEvent evt, VisualElement element)
{
TrackPropertyChanges(element, evt.property);
}
internal void DecreaseRefCount(object dataSource)
{
if (null == dataSource)
return;
if (!m_SourceInfos.TryGetValue(dataSource, out var info) || info.refCount == 0)
throw new InvalidOperationException("Trying to release a data source that isn't tracked. This is an internal bug. Please report using `Help > Report a Bug...`");
if (info.refCount == 1)
{
info.refCount = 0;
m_SourcesToRemove.Add(dataSource);
if (dataSource is INotifyBindablePropertyChanged notifier)
notifier.propertyChanged -= m_Handler;
if (dataSource is VisualElement element)
element.UnregisterCallback(m_VisualElementHandler);
}
else
{
--info.refCount;
}
}
public int GetRefCount(object dataSource)
{
return m_SourceInfos.TryGetValue(dataSource, out var info) ? info.refCount : 0;
}
public int GetTrackedDataSourcesCount()
{
return m_ResolvedHierarchicalDataSourceContext.Count;
}
public bool IsTrackingDataSource(VisualElement element)
{
return m_ResolvedHierarchicalDataSourceContext.ContainsKey(element);
}
public List<PropertyPath> GetChangesFromSource(object dataSource)
{
return m_SourceInfos.TryGetValue(dataSource, out var info) ? info.detectedChangesNoAlloc : null;
}
public void ClearChangesFromSource(object dataSource)
{
if (!m_SourceInfos.TryGetValue(dataSource, out var info))
return;
info.detectedChangesNoAlloc?.Clear();
}
public void InvalidateCachedDataSource(HashSet<VisualElement> elements, HashSet<VisualElement> removedElements)
{
var toInvalidate = ListPool<VisualElement>.Get();
try
{
foreach (var element in elements)
toInvalidate.Add(element);
m_InvalidateResolvedDataSources.Invalidate(toInvalidate, removedElements);
}
finally
{
ListPool<VisualElement>.Release(toInvalidate);
}
}
public DataSourceContext GetResolvedDataSourceContext(VisualElement element, BindingData bindingData)
{
object localDataSource = null;
PropertyPath localDataSourcePath = default;
if (bindingData.binding is IDataSourceProvider dataSourceProvider)
{
localDataSource = dataSourceProvider.dataSource;
localDataSourcePath = dataSourceProvider.dataSourcePath;
}
var lastLocalDataSource = bindingData.localDataSource;
var resolvedDataSource = localDataSource;
PropertyPath resolvedDataSourcePath = localDataSourcePath;
try
{
if (null == localDataSource)
{
// We need to untrack previous local source.
DecreaseRefCount(lastLocalDataSource);
var resolvedHierarchicalContext = GetHierarchicalDataSourceContext(element);
resolvedDataSource = resolvedHierarchicalContext.dataSource;
resolvedDataSourcePath = !localDataSourcePath.IsEmpty
? PropertyPath.Combine(resolvedHierarchicalContext.dataSourcePath, localDataSourcePath)
: resolvedHierarchicalContext.dataSourcePath;
return new DataSourceContext(resolvedDataSource, resolvedDataSourcePath);
}
// We need to update the source
if (localDataSource != lastLocalDataSource)
{
DecreaseRefCount(lastLocalDataSource);
IncreaseRefCount(localDataSource);
}
}
finally
{
bindingData.localDataSource = localDataSource;
var newResolvedContext = new DataSourceContext(resolvedDataSource, resolvedDataSourcePath);
bindingData.context = newResolvedContext;
}
return new DataSourceContext(resolvedDataSource, resolvedDataSourcePath);
}
private void TrackPropertyChanges(object sender, BindablePropertyChangedEventArgs args)
=> TrackPropertyChanges(sender, args.propertyName);
private void TrackPropertyChanges(object sender, PropertyPath propertyPath)
{
if (!m_SourceInfos.TryGetValue(sender, out var info))
return;
var list = info.detectedChanges;
list.Add(propertyPath);
}
public bool TryGetLastVersion(object source, out long version)
{
if (null != source && m_SourceInfos.TryGetValue(source, out var sourceInfo))
{
version = sourceInfo.lastVersion;
return true;
}
version = -1;
return false;
}
public void UpdateVersion(object source, long version)
{
var info = m_SourceInfos[source];
info.lastVersion = version;
m_SourceInfos[source] = info;
}
internal object GetHierarchyDataSource(VisualElement element)
{
return GetHierarchicalDataSourceContext(element).dataSource;
}
internal DataSourceContext GetHierarchicalDataSourceContext(VisualElement element)
{
if (m_ResolvedHierarchicalDataSourceContext.TryGetValue(element, out var context))
return context;
var current = element;
var path = default(PropertyPath);
while (null != current)
{
if (!current.dataSourcePath.IsEmpty)
path = PropertyPath.Combine(current.dataSourcePath, path);
if (null != current.dataSource)
{
var source = current.dataSource;
return m_ResolvedHierarchicalDataSourceContext[element] = new DataSourceContext(source, path);
}
current = current.hierarchy.parent;
}
return m_ResolvedHierarchicalDataSourceContext[element] = new DataSourceContext(null, path);
}
internal void RemoveHierarchyDataSourceContextFromElement(VisualElement element)
{
m_ResolvedHierarchicalDataSourceContext.Remove(element);
}
public void Dispose()
{
m_ResolvedHierarchicalDataSourceContext.Clear();
m_BindingRefCount.Clear();
m_SourcesToRemove.Clear();
m_SourceInfosPool.Clear();
m_SourceInfos.Clear();
}
public void ClearSourceCache()
{
foreach (var toRemove in m_SourcesToRemove)
{
if (m_SourceInfos.TryGetValue(toRemove, out var info))
{
if (info.refCount == 0)
{
m_SourceInfos.Remove(toRemove);
ReleasePooledSourceInfo(info);
}
else
{
throw new InvalidOperationException("Trying to release a data source that is still being referenced. This is an internal bug. Please report using `Help > Report a Bug...`");
}
}
else
{
throw new InvalidOperationException("Trying to release a data source that isn't tracked. This is an internal bug. Please report using `Help > Report a Bug...`");
}
}
m_SourcesToRemove.Clear();
}
}
readonly BaseVisualElementPanel m_Panel;
readonly HierarchyDataSourceTracker m_DataSourceTracker;
readonly HierarchyBindingTracker m_BindingsTracker;
readonly List<ChangesFromUI> m_DetectedChangesFromUI;
internal DataBindingManager(BaseVisualElementPanel panel)
{
m_Panel = panel;
m_DataSourceTracker = new HierarchyDataSourceTracker(this);
m_BindingsTracker = new HierarchyBindingTracker(panel);
m_DetectedChangesFromUI = new List<ChangesFromUI>();
}
internal int GetTrackedDataSourcesCount()
{
return m_DataSourceTracker.GetTrackedDataSourcesCount();
}
internal bool IsTrackingDataSource(VisualElement element)
{
return m_DataSourceTracker.IsTrackingDataSource(element);
}
internal bool TryGetLastVersion(object source, out long version)
{
return m_DataSourceTracker.TryGetLastVersion(source, out version);
}
internal void UpdateVersion(object source, long version)
{
m_DataSourceTracker.UpdateVersion(source, version);
}
internal void CacheUIBindingResult(BindingData bindingData, BindingResult result)
{
bindingData.m_SourceToUILastUpdate = result;
}
internal bool TryGetLastUIBindingResult(BindingData bindingData, out BindingResult result)
{
if (bindingData.m_SourceToUILastUpdate.HasValue)
{
result = bindingData.m_SourceToUILastUpdate.Value;
return true;
}
result = default;
return false;
}
internal void CacheSourceBindingResult(BindingData bindingData, BindingResult result)
{
bindingData.m_UIToSourceLastUpdate = result;
}
internal bool TryGetLastSourceBindingResult(BindingData bindingData, out BindingResult result)
{
if (bindingData.m_UIToSourceLastUpdate.HasValue)
{
result = bindingData.m_UIToSourceLastUpdate.Value;
return true;
}
result = default;
return false;
}
internal DataSourceContext GetResolvedDataSourceContext(VisualElement element, BindingData bindingData)
{
return element.panel == m_Panel
? m_DataSourceTracker.GetResolvedDataSourceContext(element, bindingData)
: default;
}
internal bool TryGetSource(VisualElement element, out object dataSource)
{
if (element.panel == m_Panel)
{
dataSource = m_DataSourceTracker.GetHierarchyDataSource(element);
return true;
}
dataSource = null;
return false;
}
// Internal for tests
internal object TrackHierarchyDataSource(VisualElement element)
{
return element.panel == m_Panel
? m_DataSourceTracker.GetHierarchicalDataSourceContext(element).dataSource
: null;
}
// Internal for tests
internal int GetRefCount(object dataSource)
{
return m_DataSourceTracker.GetRefCount(dataSource);
}
internal int GetBoundElementsCount()
{
return m_BindingsTracker.GetTrackedElementsCount();
}
internal IEnumerable<VisualElement> GetBoundElements()
{
return m_BindingsTracker.GetBoundElements();
}
internal IEnumerable<VisualElement> GetUnorderedBoundElements()
{
return m_BindingsTracker.GetUnorderedBoundElements();
}
internal List<ChangesFromUI> GetChangedDetectedFromUI()
{
return m_DetectedChangesFromUI;
}
internal List<PropertyPath> GetChangedDetectedFromSource(object dataSource)
{
return m_DataSourceTracker.GetChangesFromSource(dataSource);
}
internal void ClearChangesFromSource(object dataSource)
{
m_DataSourceTracker.ClearChangesFromSource(dataSource);
}
internal List<BindingData> GetBindingData(VisualElement element)
{
return element.panel == m_Panel
? m_BindingsTracker.TryGetBindingCollection(element, out var collection)
? collection.GetBindings()
: s_Empty
: s_Empty;
}
internal bool TryGetBindingData(VisualElement element, in BindingId bindingId, out BindingData bindingData)
{
bindingData = default;
if (element.panel == m_Panel && m_BindingsTracker.TryGetBindingCollection(element, out var collection))
{
return collection.TryGetBindingData(bindingId, out bindingData);
}
bindingData = default;
return false;
}
internal void RegisterBinding(VisualElement element, in BindingId bindingId, Binding binding)
{
Assert.IsFalse(null == binding);
Assert.IsFalse(((PropertyPath) bindingId).IsEmpty, $"[UI Toolkit] Could not register binding on element of type '{element.GetType().Name}': target property path is empty.");
if (m_BindingsTracker.TryGetBindingCollection(element, out var collection) &&
collection.TryGetBindingData(bindingId, out var bindingData))
{
bindingData.binding.OnDeactivated(new BindingActivationContext(element, bindingId));
var currentResolvedContext = m_DataSourceTracker.GetResolvedDataSourceContext(element, bindingData);
var provider = bindingData.binding as IDataSourceProvider;
var newSource = provider?.dataSource;
var newSourcePath = provider?.dataSourcePath ?? default;
if (currentResolvedContext.dataSource != newSource || currentResolvedContext.dataSourcePath != newSourcePath)
bindingData.binding.OnDataSourceChanged(new DataSourceContextChanged(element, bindingId, currentResolvedContext, new DataSourceContext(newSource, newSourcePath)));
m_DataSourceTracker.DecreaseBindingRefCount(ref bindingData);
}
var newBindingData = GetPooledBindingData(new BindingTarget(element, bindingId), binding);
m_DataSourceTracker.IncreaseBindingRefCount(ref newBindingData);
m_BindingsTracker.StartTrackingBinding(element, newBindingData);
binding.OnActivated(new BindingActivationContext(element, bindingId));
}
internal void UnregisterBinding(VisualElement element, in BindingId bindingId)
{
if (!m_BindingsTracker.TryGetBindingCollection(element, out var collection))
return;
if (collection.TryGetBindingData(bindingId, out var bindingData))
{
var currentResolvedContext = m_DataSourceTracker.GetResolvedDataSourceContext(element, bindingData);
var provider = bindingData.binding as IDataSourceProvider;
var newSource = provider?.dataSource;
var newSourcePath = provider?.dataSourcePath ?? default;
if (currentResolvedContext.dataSource != newSource || currentResolvedContext.dataSourcePath != newSourcePath)
bindingData.binding.OnDataSourceChanged(new DataSourceContextChanged(element, bindingId, currentResolvedContext, new DataSourceContext(newSource, newSourcePath)));
bindingData.binding.OnDeactivated(new BindingActivationContext(element, bindingId));
m_DataSourceTracker.DecreaseBindingRefCount(ref bindingData);
m_BindingsTracker.StopTrackingBinding(element, bindingData);
ReleasePoolBindingData(bindingData);
}
}
/// <summary>
/// Transfers the currently registered bindings back to the element.
/// </summary>
/// <param name="element"></param>
internal void TransferBindingRequests(VisualElement element)
{
if (!m_BindingsTracker.IsTrackingElement(element))
return;
if (m_BindingsTracker.TryGetBindingCollection(element, out var collection))
{
var bindings = collection.GetBindings();
while (bindings.Count > 0)
{
var binding = bindings[^1];
CreateBindingRequest(element, binding.target.bindingId, binding.binding);
UnregisterBinding(element, binding.target.bindingId);
}
}
m_BindingsTracker.StopTrackingElement(element);
}
public void InvalidateCachedDataSource(HashSet<VisualElement> addedOrMovedElements, HashSet<VisualElement> removedElements)
{
m_DataSourceTracker.InvalidateCachedDataSource(addedOrMovedElements, removedElements);
}
public void Dispose()
{
m_BindingsTracker.Dispose();
m_DataSourceTracker.Dispose();
m_DetectedChangesFromUI.Clear();
}
public static void CreateBindingRequest(VisualElement target, in BindingId bindingId, Binding binding)
{
var requests = (List<BindingRequest>) target.GetProperty(k_RequestBindingPropertyName);
if (requests == null)
{
requests = new List<BindingRequest>();
target.SetProperty(k_RequestBindingPropertyName, requests);
}
// When processing multiple requests to the same binding id, we should only process the very last one.
for (var i = 0; i < requests.Count; ++i)
{
var request = requests[i];
if (request.bindingId == bindingId)
{
requests[i] = request.CancelRequest();
}
}
requests.Add(new BindingRequest(bindingId, binding));
}
public static void CreateClearAllBindingsRequest(VisualElement target)
{
CreateBindingRequest(target, k_ClearBindingsToken, null);
}
public void ProcessBindingRequests(VisualElement element)
{
var requests = (List<BindingRequest>) element.GetProperty(k_RequestBindingPropertyName);
if (requests == null)
return;
for (var index = 0; index < requests.Count; index++)
{
var request = requests[index];
if (!request.shouldProcess)
continue;
if (request.bindingId == k_ClearBindingsToken)
{
ClearAllBindings(element);
continue;
}
if (request.bindingId == BindingId.Invalid)
{
var panel = element.panel;
var panelName = (panel as Panel)?.name ?? panel.visualTree.name;
Debug.LogError(
$"[UI Toolkit] Trying to set a binding on `{(string.IsNullOrWhiteSpace(element.name) ? "<no name>" : element.name)} ({TypeUtility.GetTypeDisplayName(element.GetType())})` without setting the \"property\" attribute is not supported ({panelName}).");
continue;
}
if (request.binding != null)
RegisterBinding(element, request.bindingId, request.binding);
else
UnregisterBinding(element, request.bindingId);
}
requests.Clear();
}
void ClearAllBindings(VisualElement element)
{
var list = ListPool<BindingData>.Get();
try
{
list.AddRange(GetBindingData(element));
foreach (var bindingData in list)
{
UnregisterBinding(element, bindingData.target.bindingId);
}
}
finally
{
ListPool<BindingData>.Release(list);
}
}
internal static bool AnyPendingBindingRequests(VisualElement element)
{
var requests = (List<BindingRequest>) element.GetProperty(k_RequestBindingPropertyName);
if (requests == null)
return false;
return requests.Count > 0;
}
internal static IEnumerable<(Binding binding, BindingId bindingId)> GetBindingRequests(VisualElement element)
{
var requests = (List<BindingRequest>) element.GetProperty(k_RequestBindingPropertyName);
if (requests == null)
{
yield break;
}
// We'll only return at most a single request per target property, as all the other requests will be discarded in the end.
var visited = HashSetPool<BindingId>.Get();
try
{
for (var i = requests.Count - 1; i >= 0; --i)
{
var request = requests[i];
if (visited.Add(request.bindingId))
yield return (request.binding, request.bindingId);
}
}
finally
{
HashSetPool<BindingId>.Release(visited);
}
}
internal static bool TryGetBindingRequest(VisualElement element, in BindingId bindingId, out Binding binding)
{
var requests = (List<BindingRequest>) element.GetProperty(k_RequestBindingPropertyName);
if (requests == null)
{
binding = null;
return false;
}
// Here, we will only return the last request for the provided target property, as it is the one that will be used in the end.
for (var i = requests.Count - 1; i >= 0; --i)
{
var request = requests[i];
if (bindingId != request.bindingId)
continue;
binding = request.binding;
return true;
}
binding = null;
return false;
}
public void DirtyBindingOrder()
{
m_BindingsTracker.SetDirty();
}
public void TrackDataSource(object previous, object current)
{
m_DataSourceTracker.DecreaseRefCount(previous);
m_DataSourceTracker.IncreaseRefCount(current);
}
// Internal for tests
internal (int boundElementsCount, int trackedDataSourcesCount) GetTrackedInfo()
{
var boundElements = m_BindingsTracker.GetTrackedElementsCount();
var dataSources = m_DataSourceTracker.GetTrackedDataSourcesCount();
return (boundElements, dataSources);
}
public void ClearSourceCache()
{
m_DataSourceTracker.ClearSourceCache();
}
public BindingData GetPooledBindingData(BindingTarget target, Binding binding)
{
BindingData data;
if (m_BindingDataLocalPool.Count > 0)
{
data = m_BindingDataLocalPool[^1];
m_BindingDataLocalPool.RemoveAt(m_BindingDataLocalPool.Count - 1);
}
else
data = new BindingData();
data.target = target;
data.binding = binding;
return data;
}
public void ReleasePoolBindingData(BindingData data)
{
data.Reset();
m_BindingDataLocalPool.Add(data);
}
}
}
| UnityCsReference/Modules/UIElements/Core/Bindings/DataBindingManager.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/DataBindingManager.cs",
"repo_id": "UnityCsReference",
"token_count": 21639
} | 489 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections;
using System.Collections.Generic;
using Unity.Hierarchy;
namespace UnityEngine.UIElements
{
/// <summary>
/// Default implementation of a <see cref="MultiColumnTreeViewController"/>.
/// </summary>
/// <typeparam name="T">The data type.</typeparam>
public class DefaultMultiColumnTreeViewController<T> : MultiColumnTreeViewController, IDefaultTreeViewController<T>
{
TreeDataController<T> m_TreeDataController;
TreeDataController<T> treeDataController => m_TreeDataController ??= new TreeDataController<T>();
/// <summary>
/// The constructor for DefaultMultiColumnTreeViewController.
/// </summary>
/// <param name="columns">The columns data used to initialize the header.</param>
/// <param name="sortDescriptions">The sort data used to initialize the header.</param>
/// <param name="sortedColumns">The sorted columns for the view.</param>
public DefaultMultiColumnTreeViewController(Columns columns, SortColumnDescriptions sortDescriptions, List<SortColumnDescription> sortedColumns)
: base(columns, sortDescriptions, sortedColumns) {}
/// <inheritdoc />
public override IList itemsSource
{
get => base.itemsSource;
set
{
if (value == null)
{
SetRootItems(null);
}
else if (value is IList<TreeViewItemData<T>> dataList)
{
SetRootItems(dataList);
}
else
{
Debug.LogError($"Type does not match this tree view controller's data type ({typeof(T)}).");
}
}
}
/// <summary>
/// Sets the root items.
/// </summary>
/// <remarks>
/// Root items can include their children directly.
/// </remarks>
/// <param name="items">The TreeView root items.</param>
public void SetRootItems(IList<TreeViewItemData<T>> items)
{
if (items == base.itemsSource)
return;
if (m_Hierarchy.IsCreated)
{
ClearIdToNodeDictionary();
treeDataController.ClearNodeToDataDictionary();
// Recreate memory for the new dataset
hierarchy = new Hierarchy();
}
if (items != null)
{
treeDataController.ConvertTreeViewItemDataToHierarchy(items, (node) => CreateNode(node), (id, node) => UpdateIdToNodeDictionary(id, node));
UpdateHierarchy();
// We want to sync the expanded state(s) if there's a viewDataKey
if (IsViewDataKeyEnabled())
OnViewDataReadyUpdateNodes();
}
// Required to set the CollectionViewController's items source.
SetHierarchyViewModelWithoutNotify(m_HierarchyViewModel);
RaiseItemsSourceChanged();
}
/// <summary>
/// Adds an item to the tree.
/// </summary>
/// <param name="item">Item to add.</param>
/// <param name="parentId">The parent id for the item.</param>
/// <param name="childIndex">The child index in the parent's children list.</param>
/// <param name="rebuildTree">Whether the tree data should be rebuilt right away. Call <see cref="TreeViewController.RebuildTree()"/> when <c>false</c>.</param>
public virtual void AddItem(in TreeViewItemData<T> item, int parentId, int childIndex, bool rebuildTree = true)
{
HierarchyNode node;
if (parentId == BaseTreeView.invalidId)
{
node = CreateNode(HierarchyNode.Null);
}
else
{
var parentNode = GetHierarchyNodeById(parentId);
node = CreateNode(parentNode);
// Update our internal TreeViewItemData otherwise the content will be out of date when the user fetches it.
var treeItemData = treeDataController.GetTreeItemDataForNode(parentNode);
if (treeItemData.data != null)
treeItemData.InsertChild(item, childIndex);
}
treeDataController.AddItem(item, node);
UpdateIdToNodeDictionary(item.id, node);
UpdateHierarchy();
// If the item being added contains children, we want to convert them into HierarchyNode(s). For example,
// users can drive their TreeView solely with the AddItem and TryRemoveItem APIs
if (item.children.GetCount() > 0)
{
var parentNode = GetHierarchyNodeById(item.id);
treeDataController.ConvertTreeViewItemDataToHierarchy(
item.children,
(itemNode) => CreateNode(itemNode == HierarchyNode.Null ? parentNode : itemNode),
(id, newNode) =>
{
UpdateIdToNodeDictionary(id, newNode);
UpdateHierarchy();
});
}
if (baseTreeView.autoExpand)
ExpandAncestorNodes(node);
if (childIndex != -1)
UpdateSortOrder(m_Hierarchy.GetParent(node), node, childIndex);
}
/// <summary>
/// Gets the tree item data for the specified TreeView item ID.
/// </summary>
/// <param name="id">The TreeView item ID.</param>
/// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam>
/// <returns>The tree item data.</returns>
public virtual TreeViewItemData<T> GetTreeViewItemDataForId(int id)
{
return treeDataController.GetTreeItemDataForNode(GetHierarchyNodeById(id));
}
/// <summary>
/// Gets the tree item data for the specified TreeView item index.
/// </summary>
/// <param name="index">The TreeView item index.</param>
/// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam>
/// <returns>The tree item data.</returns>
public virtual TreeViewItemData<T> GetTreeViewItemDataForIndex(int index)
{
var id = GetIdForIndex(index);
return treeDataController.GetTreeItemDataForNode(GetHierarchyNodeById(id));
}
/// <inheritdoc />
public override bool TryRemoveItem(int id, bool rebuildTree = true)
{
var node = GetHierarchyNodeById(id);
if (node != HierarchyNode.Null)
{
// Update our internal TreeViewDataItem reference by removing the child from the parent - if applicable.
var parentId = GetParentId(id);
if (parentId != BaseTreeView.invalidId)
{
var treeItemData = treeDataController.GetTreeItemDataForNode(GetHierarchyNodeById(parentId));
if (treeItemData.data != null)
treeItemData.RemoveChild(id);
}
RemoveAllChildrenItemsFromCollections(node, (hierarchyNode, itemId) =>
{
treeDataController.RemoveItem(hierarchyNode);
UpdateIdToNodeDictionary(itemId, node, false);
});
treeDataController.RemoveItem(node);
UpdateIdToNodeDictionary(id, node, false);
m_Hierarchy.Remove(node);
UpdateHierarchy();
return true;
}
return false;
}
public override object GetItemForId(int id)
{
return treeDataController.GetTreeItemDataForNode(GetHierarchyNodeById(id)).data;
}
/// <summary>
/// Gets data for the specified TreeView item ID.
/// </summary>
/// <param name="id">The TreeView item ID.</param>
/// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam>
/// <returns>The data.</returns>
public T GetDataForId(int id)
{
return treeDataController.GetDataForNode(GetHierarchyNodeById(id));
}
/// <summary>
/// Gets data for the specified TreeView item index.
/// </summary>
/// <param name="index">The TreeView item index.</param>
/// <typeparam name="T">Type of the data inside TreeViewItemData.</typeparam>
/// <returns>The data.</returns>
public T GetDataForIndex(int index)
{
return treeDataController.GetDataForNode(GetHierarchyNodeByIndex(index));
}
/// <inheritdoc />
public override object GetItemForIndex(int index)
{
return treeDataController.GetDataForNode(GetHierarchyNodeByIndex(index));
}
}
}
| UnityCsReference/Modules/UIElements/Core/Collections/Controllers/DefaultMultiColumnTreeViewController.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Controllers/DefaultMultiColumnTreeViewController.cs",
"repo_id": "UnityCsReference",
"token_count": 4063
} | 490 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
class ReusableMultiColumnTreeViewItem : ReusableTreeViewItem
{
public override VisualElement rootElement => bindableElement;
public override void Init(VisualElement item)
{
// Do nothing here, we are using the other Init.
}
public void Init(VisualElement container, Columns columns)
{
var i = 0;
bindableElement = container;
foreach (var column in columns.visibleList)
{
if (columns.IsPrimary(column))
{
var cellContainer = container[i];
var cellItem = cellContainer.GetProperty(MultiColumnController.bindableElementPropertyName) as VisualElement;
InitExpandHierarchy(cellContainer, cellItem);
break;
}
i++;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableMultiColumnTreeViewItem.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableMultiColumnTreeViewItem.cs",
"repo_id": "UnityCsReference",
"token_count": 496
} | 491 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using Unity.Properties;
namespace UnityEngine.UIElements
{
/// <summary>
/// This is a clickable button.
/// </summary>
/// <remarks>
/// A Button has a text label element that can respond to pointer and mouse events.
/// You can add an icon to pair it with the text by assigning a Background (Texture, RenderTexture, Sprite or Vector Image)
/// to the iconImage API or icon-image UXML property. Please note that by providing an icon image, this will
/// automatically update the Button's hierarchy to contain an <see cref="Image"/> and a text label element.
///
/// By default, a single left mouse click activates the Button's <see cref="Clickable"/> property button.
/// To remove this activator, or add more activators, modify the <c>clickable.activators</c> property.
/// For details, see <see cref="ManipulatorActivationFilter"/>.
///
/// To bind a Button's text value to the contents of a variable, set the <c>binding-path</c> property in the
/// UXML file, or the <c>bindingPath</c> property in the C# code, to a string that contains the variable name.
///
/// For more information, refer to [[wiki:UIE-uxml-element-Button|UXML element Button]].
/// </remarks>
public class Button : TextElement
{
internal static readonly BindingId iconImageProperty = nameof(iconImage);
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : TextElement.UxmlSerializedData
{
#pragma warning disable 649
[ImageFieldValueDecorator]
[SerializeField, UxmlAttribute("icon-image")] Object iconImageReference;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags iconImageReference_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new Button();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
if (ShouldWriteAttributeValue(iconImageReference_UxmlAttributeFlags))
{
var e = (Button)obj;
e.iconImageReference = iconImageReference;
}
}
}
/// <summary>
/// Instantiates a <see cref="Button"/> using data from a UXML file.
/// </summary>
/// <remarks>
/// This class is added to every <see cref="VisualElement"/> that is created from UXML.
/// </remarks>
[Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlFactory : UxmlFactory<Button, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="Button"/>.
/// </summary>
/// <remarks>
/// This class defines the properties of a Button element that you can
/// use in a UXML asset.
/// </remarks>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : TextElement.UxmlTraits
{
private readonly UxmlImageAttributeDescription m_IconImage = new() { name = "icon-image" };
/// <summary>
/// Constructor.
/// </summary>
public UxmlTraits()
{
focusable.defaultValue = true;
}
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
base.Init(ve, bag, cc);
var button = (Button)ve;
button.iconImage = m_IconImage.GetValueFromBag(bag, cc);
}
}
/// <summary>
/// USS class name of elements of this type.
/// </summary>
/// <remarks>
/// Unity adds this USS class to every instance of the Button element. Any styling applied to
/// this class affects every button located beside, or below the stylesheet in the visual tree.
/// </remarks>
public new static readonly string ussClassName = "unity-button";
/// <summary>
/// The USS class name for Button elements with an icon.
/// </summary>
/// <remarks>
/// Unity adds this USS class to an instance of the Button element if the instance's
/// <see cref="Button.iconImage"/> property contains a valid Texture. Any styling applied to this class
/// affects every button with an icon located beside, or below the stylesheet in the visual tree.
/// </remarks>
public static readonly string iconUssClassName = ussClassName + "--with-icon";
/// <summary>
/// The USS class name of the image element that will be used to display the icon texture.
/// </summary>
/// <remarks>
/// Unity adds this USS class to an instance of the Image element that will be used to display the
/// <see cref="Button.iconImage"/> property value. Any styling applied to this class will affect
/// image elements inside a Button that contains this class.
/// </remarks>
public static readonly string imageUSSClassName = ussClassName + "__image";
private Clickable m_Clickable;
/// <summary>
/// Clickable MouseManipulator for this Button.
/// </summary>
/// <remarks>
/// <example>
/// The default <see cref="Clickable"/> object provides a list of actions that are called using
/// one or more activation filters.
///
/// To add or remove activation triggers, modify <see cref="Clickable.activators"/>.
/// An activation trigger can be any mouse button, pressed any number of times, with any modifier key.
/// For details, see <see cref="ManipulatorActivationFilter"/>.
/// <code>clickable.activators.Add(new ManipulatorActivationFilter(...))</code>
/// or
/// <code>clickable.activators.Clear()</code>
/// </example>
/// </remarks>
public Clickable clickable
{
get
{
return m_Clickable;
}
set
{
if (m_Clickable != null && m_Clickable.target == this)
{
this.RemoveManipulator(m_Clickable);
}
m_Clickable = value;
if (m_Clickable != null)
{
this.AddManipulator(m_Clickable);
}
}
}
/// <summary>
/// Obsolete. Use <see cref="Button.clicked"/> instead.
/// </summary>
[Obsolete("onClick is obsolete. Use clicked instead (UnityUpgradable) -> clicked", true)]
public event Action onClick
{
add
{
clicked += value;
}
remove
{
clicked -= value;
}
}
/// <summary>
/// Callback triggered when the button is clicked.
/// </summary>
/// <remarks>
/// This is a shortcut for modifying <seealso cref="Clickable.clicked"/>. It is provided as a convenience. When you add or remove actions from clicked, it adds or removes them from <c>Clickable.clicked</c> automatically.
/// </remarks>
/// <example>
/// The following example shows how to use the clicked event to print a message to the console when the button is clicked.
/// <code source="../../../../Modules/UIElements/Tests/UIElementsExamples/Assets/Examples/Button_clicked.cs"/>
/// </example>
public event Action clicked
{
add
{
if (m_Clickable == null)
{
clickable = new Clickable(value);
}
else
{
m_Clickable.clicked += value;
}
}
remove
{
if (m_Clickable != null)
{
m_Clickable.clicked -= value;
}
}
}
// Used privately to help the serializer convert the Unity Object to the appropriate asset type.
Object iconImageReference
{
get => iconImage.GetSelectedImage();
set => iconImage = Background.FromObject(value);
}
// The element designed to hold the Button's text when an icon is preset (sibling of image).
TextElement m_TextElement;
// The element that will hold and render the icon within the button (sibling of text element).
Image m_ImageElement;
// Holds the corresponding icon value of said type (Texture, Sprite, VectorImage).
Background m_IconImage;
/// <summary>
/// The Texture, Sprite, or VectorImage that will represent an icon within a Button element.
/// </summary>
[CreateProperty]
public Background iconImage
{
get => m_IconImage;
set
{
if (value.IsEmpty() && m_ImageElement == null || value == m_IconImage)
return;
if (value.IsEmpty())
{
ResetButtonHierarchy();
m_IconImage = value;
NotifyPropertyChanged(iconImageProperty);
return;
}
if (m_ImageElement == null)
UpdateButtonHierarchy();
// The image control will reset the other values to null
if (value.texture)
m_ImageElement.image = value.texture;
else if (value.sprite)
m_ImageElement.sprite = value.sprite;
else if (value.renderTexture)
m_ImageElement.image = value.renderTexture;
else
m_ImageElement.vectorImage = value.vectorImage;
m_IconImage = value;
NotifyPropertyChanged(iconImageProperty);
}
}
private string m_Text = String.Empty;
public override string text
{
get => m_Text ?? string.Empty;
set
{
m_Text = value;
if (m_TextElement != null)
{
// Make sure we clear the Button's text, otherwise it will show the same string twice
base.text = String.Empty;
if (m_TextElement.text == m_Text)
return;
m_TextElement.text = m_Text;
return;
}
if (base.text == m_Text)
return;
base.text = m_Text;
}
}
/// <summary>
/// Constructs a Button.
/// </summary>
public Button() : this(default, null)
{
}
/// <summary>
/// Constructs a button with an <see cref="Background"/> and an Action. The image definition will be used
/// to represent an icon while the Action is triggered when the button is clicked.
/// </summary>
/// <param name="iconImage">The image value that will be rendered as an icon.</param>
/// <param name="clickEvent">The action triggered when the button is clicked.</param>
public Button(Background iconImage, Action clickEvent = null) : this(clickEvent)
{
this.iconImage = iconImage;
}
/// <summary>
/// Constructs a button with an Action that is triggered when the button is clicked.
/// </summary>
/// <param name="clickEvent">The action triggered when the button is clicked.</param>
/// <remarks>
/// By default, a single left mouse click triggers the Action. To change the activator, modify <see cref="clickable"/>.
/// </remarks>
public Button(Action clickEvent)
{
AddToClassList(ussClassName);
// Click-once behaviour
clickable = new Clickable(clickEvent);
focusable = true;
tabIndex = 0;
RegisterCallback<NavigationSubmitEvent>(OnNavigationSubmit);
}
private void OnNavigationSubmit(NavigationSubmitEvent evt)
{
clickable?.SimulateSingleClick(evt);
evt.StopPropagation();
}
private static readonly string NonEmptyString = " ";
protected internal override Vector2 DoMeasure(float desiredWidth, MeasureMode widthMode, float desiredHeight,
MeasureMode heightMode)
{
var textToMeasure = text;
if (string.IsNullOrEmpty(textToMeasure))
{
textToMeasure = NonEmptyString;
}
return MeasureTextSize(textToMeasure, desiredWidth, widthMode, desiredHeight, heightMode);
}
private void UpdateButtonHierarchy()
{
if (m_ImageElement == null)
{
m_ImageElement = new Image { classList = { imageUSSClassName } };
Add(m_ImageElement);
AddToClassList(iconUssClassName);
}
if (m_TextElement == null)
{
m_TextElement = new TextElement {text = text};
m_Text = text;
base.text = String.Empty;
Add(m_TextElement);
}
}
private void ResetButtonHierarchy()
{
if (m_ImageElement != null)
{
m_ImageElement.RemoveFromHierarchy();
m_ImageElement = null;
RemoveFromClassList(iconUssClassName);
}
if (m_TextElement != null)
{
var restoredText = m_TextElement.text;
m_TextElement.RemoveFromHierarchy();
m_TextElement = null;
text = restoredText;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/Button.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/Button.cs",
"repo_id": "UnityCsReference",
"token_count": 6380
} | 492 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
internal class KeyboardTextEditorEventHandler : TextEditorEventHandler
{
readonly Event m_ImguiEvent = new Event();
// Used by our automated tests.
internal bool m_Changed;
const int k_LineFeed = 10;
const int k_Space = 32;
public KeyboardTextEditorEventHandler(TextElement textElement, TextEditingUtilities editingUtilities)
: base(textElement, editingUtilities)
{
editingUtilities.multiline = textElement.edition.multiline;
}
public override void HandleEventBubbleUp(EventBase evt)
{
base.HandleEventBubbleUp(evt);
switch (evt)
{
case KeyDownEvent kde:
OnKeyDown(kde);
break;
case ValidateCommandEvent vce:
OnValidateCommandEvent(vce);
break;
case ExecuteCommandEvent ece:
OnExecuteCommandEvent(ece);
break;
case FocusEvent fe:
OnFocus(fe);
break;
case BlurEvent be:
OnBlur(be);
break;
case NavigationMoveEvent ne:
OnNavigationEvent(ne);
break;
case NavigationSubmitEvent ne:
OnNavigationEvent(ne);
break;
case NavigationCancelEvent ne:
OnNavigationEvent(ne);
break;
}
}
void OnFocus(FocusEvent _)
{
GUIUtility.imeCompositionMode = IMECompositionMode.On;
textElement.edition.SaveValueAndText();
}
void OnBlur(BlurEvent _)
{
GUIUtility.imeCompositionMode = IMECompositionMode.Auto;
}
void OnKeyDown(KeyDownEvent evt)
{
if (!textElement.hasFocus)
return;
m_Changed = false;
evt.GetEquivalentImguiEvent(m_ImguiEvent);
bool generatePreview = false;
if (editingUtilities.HandleKeyEvent(m_ImguiEvent))
{
if (textElement.text != editingUtilities.text)
m_Changed = true;
evt.StopPropagation();
}
else
{
char c = evt.character;
// Ignore command and control keys, but not AltGr characters
if (evt.actionKey && !(evt.altKey && c != '\0'))
return;
// We rely on KeyCode.Tab for both navigation and inserting tabulation.
// On Linux Platform regular tab event occupies both keycode and character fields
if (c == '\t' && evt.keyCode == KeyCode.None && evt.modifiers == EventModifiers.None)
return;
// Ignore tab in single-line text fields, modifier+tab in multiline text fields
// On Linux Platform modifier+tab case will be represented as keycode=None and character='\t'
if (evt.keyCode == KeyCode.Tab || (evt.keyCode == KeyCode.Tab && evt.character == '\t' && evt.modifiers == EventModifiers.Shift))
{
if(!textElement.edition.multiline || evt.shiftKey)
{
if (evt.ShouldSendNavigationMoveEvent())
{
// Do the navigation manually since NavigationTabEvent doesn't pass through
textElement.focusController.FocusNextInDirection(textElement, evt.shiftKey
? VisualElementFocusChangeDirection.left
: VisualElementFocusChangeDirection.right);
evt.StopPropagation();
}
return;
}
else if (!evt.ShouldSendNavigationMoveEvent())
return;
}
if (!textElement.edition.multiline && (evt.keyCode == KeyCode.KeypadEnter || evt.keyCode == KeyCode.Return))
textElement.edition.UpdateValueFromText?.Invoke();
evt.StopPropagation();
// When the newline character is sent, we have to check if the shift key is down also...
// In the multiline case, this is like a return on a single line
if (textElement.edition.multiline
? c == '\n' && evt.shiftKey
: (c == '\n' || c == '\r' || c == k_LineFeed) && !evt.altKey)
{
textElement.edition.MoveFocusToCompositeRoot?.Invoke();
return;
}
if (evt.keyCode == KeyCode.Escape)
{
textElement.edition.RestoreValueAndText();
textElement.edition.UpdateValueFromText?.Invoke();
textElement.edition.MoveFocusToCompositeRoot?.Invoke();
}
if (evt.keyCode == KeyCode.Tab)
c = '\t';
if (!textElement.edition.AcceptCharacter(c))
return;
if (c >= k_Space || evt.keyCode == KeyCode.Tab || (textElement.edition.multiline && !evt.altKey && (c == '\n' || c == '\r' || c == k_LineFeed)))
{
m_Changed = editingUtilities.Insert(c);
}
// On windows, key presses also send events with keycode but no character. Eat them up here.
else
{
// if we have a composition string, make sure we clear the previous selection.
var oldIsCompositionActive = editingUtilities.isCompositionActive;
generatePreview = true;
if (editingUtilities.UpdateImeState() || oldIsCompositionActive != editingUtilities.isCompositionActive)
m_Changed = true;
}
}
if (m_Changed)
UpdateLabel(generatePreview);
// The selection indices might have changed.
textElement.edition.UpdateScrollOffset?.Invoke(evt.keyCode == KeyCode.Backspace);
}
void UpdateLabel(bool generatePreview)
{
var oldText = editingUtilities.text;
var imeEnabled = editingUtilities.UpdateImeState();
if (imeEnabled && editingUtilities.ShouldUpdateImeWindowPosition())
editingUtilities.SetImeWindowPosition(new Vector2(textElement.worldBound.x, textElement.worldBound.y));
var fullText = generatePreview ? editingUtilities.GeneratePreviewString(textElement.enableRichText) : editingUtilities.text;
//Note that UpdateText will update editingUtilities with the latest text if validations were made.
textElement.edition.UpdateText(fullText);
if (!textElement.edition.isDelayed)
textElement.edition.UpdateValueFromText?.Invoke();
if (imeEnabled)
{
// Reset back to the original string. We need to do this after UpdateText as it sends a change event that will update editingUtilities.text.
editingUtilities.text = oldText;
// We need to move the cursor so that it appears at the end of the composition string when rendered in generateVisualContent.
editingUtilities.EnableCursorPreviewState();
}
// UpdateScrollOffset needs the new geometry of the text to compute the new scrollOffset.
// The latest text geometry is also required for updating the cusor and selection position.
textElement.uitkTextHandle.ComputeSettingsAndUpdate();
}
void OnValidateCommandEvent(ValidateCommandEvent evt)
{
if (!textElement.hasFocus)
return;
switch (evt.commandName)
{
// Handled in TextSelectingManipulator
case EventCommandNames.Copy:
case EventCommandNames.SelectAll:
return;
case EventCommandNames.Cut:
if (!textElement.selection.HasSelection())
return;
break;
case EventCommandNames.Paste:
if (!editingUtilities.CanPaste())
return;
break;
case EventCommandNames.Delete:
break;
case EventCommandNames.UndoRedoPerformed:
// TODO: ????? editor.text = text; --> see EditorGUI's DoTextField
break;
}
evt.StopPropagation();
}
void OnExecuteCommandEvent(ExecuteCommandEvent evt)
{
if (!textElement.hasFocus)
return;
m_Changed = false;
bool mayHaveChanged = false;
string oldText = editingUtilities.text;
switch (evt.commandName)
{
case EventCommandNames.OnLostFocus:
evt.StopPropagation();
return;
case EventCommandNames.Cut:
editingUtilities.Cut();
mayHaveChanged = true;
evt.StopPropagation();
break;
case EventCommandNames.Paste:
editingUtilities.Paste();
mayHaveChanged = true;
evt.StopPropagation();
break;
case EventCommandNames.Delete:
// This "Delete" command stems from a Shift-Delete in the text
// On Windows, Shift-Delete in text does a cut whereas on Mac, it does a delete.
editingUtilities.Cut();
mayHaveChanged = true;
evt.StopPropagation();
break;
}
if (mayHaveChanged)
{
if (oldText != editingUtilities.text)
m_Changed = true;
evt.StopPropagation();
}
if (m_Changed)
UpdateLabel(true);
// The selection indices might have changed.
textElement.edition.UpdateScrollOffset?.Invoke(false);
}
void OnNavigationEvent<TEvent>(NavigationEventBase<TEvent> evt) where TEvent : NavigationEventBase<TEvent>, new()
{
// Prevent navigation events, since we're consuming KeyDownEvents directly
if (evt.deviceType == NavigationDeviceType.Keyboard || evt.deviceType == NavigationDeviceType.Unknown)
{
evt.StopPropagation();
textElement.focusController.IgnoreEvent(evt);
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/InputField/KeyboardTextEditor.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/InputField/KeyboardTextEditor.cs",
"repo_id": "UnityCsReference",
"token_count": 5716
} | 493 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Pool;
using UnityEngine.UIElements.Internal;
namespace UnityEngine.UIElements
{
/// <summary>
/// Defines the sorting mode of a <see cref="MultiColumnListView"/> or <see cref="MultiColumnTreeView"/>.
/// </summary>
public enum ColumnSortingMode
{
/// <summary>
/// Sorting is disabled.
/// </summary>
None,
/// <summary>
/// The default Unity sorting will be used. Define how to compare items in a column with <see cref="Column.comparison"/>.
/// </summary>
Default,
/// <summary>
/// Sorting is left to the user in the <see cref="MultiColumnListView.columnSortingChanged"/> or <see cref="MultiColumnTreeView.columnSortingChanged"/>.
/// </summary>
Custom,
}
/// <summary>
/// The default controller for a multi column view. Takes care of adding the MultiColumnCollectionHeader and
/// reacting to the various callbacks.
/// </summary>
public class MultiColumnController : IDisposable
{
private static readonly PropertyName k_BoundColumnVePropertyName = "__unity-multi-column-bound-column";
internal static readonly PropertyName bindableElementPropertyName = "__unity-multi-column-bindable-element";
internal static readonly string baseUssClassName = "unity-multi-column-view";
static readonly string k_HeaderContainerViewDataKey = "unity-multi-column-header-container";
/// <summary>
/// The USS class name for the header container inside a multi column view.
/// </summary>
public static readonly string headerContainerUssClassName = baseUssClassName + "__header-container";
/// <summary>
/// The USS class name for all row containers inside a multi column view.
/// </summary>
public static readonly string rowContainerUssClassName = baseUssClassName + "__row-container";
/// <summary>
/// The USS class name for all cells inside a multi column view.
/// </summary>
public static readonly string cellUssClassName = baseUssClassName + "__cell";
/// <summary>
/// The USS class name for default labels cells inside a multi column view.
/// </summary>
public static readonly string cellLabelUssClassName = cellUssClassName + "__label";
private static readonly string k_HeaderViewDataKey = "Header";
/// <summary>
/// Raised when sorting changes for a column.
/// </summary>
public event Action columnSortingChanged;
/// <summary>
/// Raised when a column is right-clicked to bring context menu options.
/// </summary>
public event Action<ContextualMenuPopulateEvent, Column> headerContextMenuPopulateEvent;
List<int> m_SortedIndices;
ColumnSortingMode m_SortingMode;
BaseVerticalCollectionView m_View;
VisualElement m_HeaderContainer;
MultiColumnCollectionHeader m_MultiColumnHeader;
internal MultiColumnCollectionHeader header => m_MultiColumnHeader;
internal ColumnSortingMode sortingMode
{
get => m_SortingMode;
set
{
m_SortingMode = value;
header.sortingEnabled = m_SortingMode != ColumnSortingMode.None;
}
}
/// <summary>
/// Constructor. It will create the <see cref="MultiColumnCollectionHeader"/> to use for the view.
/// </summary>
/// <param name="columns">The columns data used to initialize the header.</param>
/// <param name="sortDescriptions">The sort data used to initialize the header.</param>
/// <param name="sortedColumns">The sorted columns for the view.</param>
/// <remarks>The header will be added to the view in the <see cref="PrepareView"/> phase.</remarks>
public MultiColumnController(Columns columns, SortColumnDescriptions sortDescriptions, List<SortColumnDescription> sortedColumns)
{
m_MultiColumnHeader = new MultiColumnCollectionHeader(columns, sortDescriptions, sortedColumns) { viewDataKey = k_HeaderViewDataKey };
m_MultiColumnHeader.columnSortingChanged += OnColumnSortingChanged;
m_MultiColumnHeader.contextMenuPopulateEvent += OnContextMenuPopulateEvent;
m_MultiColumnHeader.columnResized += OnColumnResized;
m_MultiColumnHeader.viewDataRestored += OnViewDataRestored;
m_MultiColumnHeader.columns.columnAdded += OnColumnAdded;
m_MultiColumnHeader.columns.columnRemoved += OnColumnRemoved;
m_MultiColumnHeader.columns.columnReordered += OnColumnReordered;
m_MultiColumnHeader.columns.columnChanged += OnColumnsChanged;
m_MultiColumnHeader.columns.changed += OnColumnChanged;
}
static void BindCellItem<T>(VisualElement ve, int rowIndex, Column column, T item)
{
if (column.bindCell != null)
{
column.bindCell.Invoke(ve, rowIndex);
}
else
{
DefaultBindCellItem(ve, item);
}
}
static void UnbindCellItem(VisualElement ve, int rowIndex, Column column)
{
column.unbindCell?.Invoke(ve, rowIndex);
}
static VisualElement DefaultMakeCellItem()
{
var label = new Label();
label.AddToClassList(cellLabelUssClassName);
return label;
}
static void DefaultBindCellItem<T>(VisualElement ve, T item)
{
if (ve is Label label)
{
label.text = item.ToString();
}
}
/// <summary>
/// Creates a VisualElement to use in the virtualization of the collection view.
/// It will create a cell for every visible column.
/// </summary>
/// <returns>A VisualElement for the row.</returns>
public VisualElement MakeItem()
{
var container = new VisualElement() { name = rowContainerUssClassName };
container.AddToClassList(rowContainerUssClassName);
foreach (var column in m_MultiColumnHeader.columns.visibleList)
{
var cellContainer = new VisualElement();
cellContainer.AddToClassList(cellUssClassName);
var cellItem = column.makeCell?.Invoke() ?? DefaultMakeCellItem();
cellContainer.SetProperty(bindableElementPropertyName, cellItem);
cellContainer.Add(cellItem);
container.Add(cellContainer);
}
return container;
}
/// <summary>
/// Binds a row of multiple cells to an item index.
/// </summary>
/// <param name="element">The element from that row, created by MakeItem().</param>
/// <param name="index">The item index.</param>
/// <param name="item">The item to bind.</param>
public void BindItem<T>(VisualElement element, int index, T item)
{
var i = 0;
foreach (var column in m_MultiColumnHeader.columns.visibleList)
{
if (!m_MultiColumnHeader.columnDataMap.TryGetValue(column, out var columnData))
continue;
var cellContainer = element[i++];
var cellItem = cellContainer.GetProperty(bindableElementPropertyName) as VisualElement;
BindCellItem(cellItem, index, column, item);
cellContainer.style.width = columnData.control.resolvedStyle.width;
cellContainer.SetProperty(k_BoundColumnVePropertyName, column);
}
}
/// <summary>
/// Unbinds the row at the item index.
/// </summary>
/// <param name="element">The element from that row, created by MakeItem().</param>
/// <param name="index">The item index.</param>
public void UnbindItem(VisualElement element, int index)
{
foreach (var cellContainer in element.Children())
{
var column = cellContainer.GetProperty(k_BoundColumnVePropertyName) as Column;
if (column == null)
continue;
var cellItem = cellContainer.GetProperty(bindableElementPropertyName) as VisualElement;
UnbindCellItem(cellItem, index, column);
}
}
/// <summary>
/// Destroys a VisualElement when the view is rebuilt or cleared.
/// </summary>
/// <param name="element">The element being destroyed.</param>
public void DestroyItem(VisualElement element)
{
foreach (var cellContainer in element.Children())
{
var column = cellContainer.GetProperty(k_BoundColumnVePropertyName) as Column;
if (column == null)
continue;
var cellItem = cellContainer.GetProperty(bindableElementPropertyName) as VisualElement;
column.destroyCell?.Invoke(cellItem);
cellContainer.SetProperty(k_BoundColumnVePropertyName, null);
}
}
/// <summary>
/// Initialization step once the view is set.
/// It will insert the multi column header in the hierarchy and register to important callbacks.
/// </summary>
/// <param name="collectionView">The view to register to.</param>
public void PrepareView(BaseVerticalCollectionView collectionView)
{
if (m_View != null)
{
Debug.LogWarning("Trying to initialize multi column view more than once. This shouldn't happen.");
return;
}
m_View = collectionView;
// Insert header to the multi column view.
m_HeaderContainer = new VisualElement { name = headerContainerUssClassName };
m_HeaderContainer.AddToClassList(headerContainerUssClassName);
m_HeaderContainer.viewDataKey = k_HeaderContainerViewDataKey;
collectionView.scrollView.hierarchy.Insert(0, m_HeaderContainer);
m_HeaderContainer.Add(m_MultiColumnHeader);
// Handle horizontal scrolling
m_View.scrollView.horizontalScroller.valueChanged += OnHorizontalScrollerValueChanged;
m_View.scrollView.contentViewport.RegisterCallback<GeometryChangedEvent>(OnViewportGeometryChanged);
m_MultiColumnHeader.columnContainer.RegisterCallback<GeometryChangedEvent>(OnColumnContainerGeometryChanged);
}
/// <summary>
/// Unregisters events and removes the header from the hierarchy.
/// </summary>
public void Dispose()
{
if (m_View != null)
{
m_View.scrollView.horizontalScroller.valueChanged -= OnHorizontalScrollerValueChanged;
m_View.scrollView.contentViewport.UnregisterCallback<GeometryChangedEvent>(OnViewportGeometryChanged);
m_View = null;
}
m_MultiColumnHeader.columnContainer.UnregisterCallback<GeometryChangedEvent>(OnColumnContainerGeometryChanged);
m_MultiColumnHeader.columnSortingChanged -= OnColumnSortingChanged;
m_MultiColumnHeader.contextMenuPopulateEvent -= OnContextMenuPopulateEvent;
m_MultiColumnHeader.columnResized -= OnColumnResized;
m_MultiColumnHeader.viewDataRestored -= OnViewDataRestored;
m_MultiColumnHeader.columns.columnAdded -= OnColumnAdded;
m_MultiColumnHeader.columns.columnRemoved -= OnColumnRemoved;
m_MultiColumnHeader.columns.columnReordered -= OnColumnReordered;
m_MultiColumnHeader.columns.columnChanged -= OnColumnsChanged;
m_MultiColumnHeader.columns.changed -= OnColumnChanged;
m_MultiColumnHeader.RemoveFromHierarchy();
m_MultiColumnHeader.Dispose();
m_MultiColumnHeader = null;
m_HeaderContainer.RemoveFromHierarchy();
m_HeaderContainer = null;
}
void OnHorizontalScrollerValueChanged(float v)
{
m_MultiColumnHeader.ScrollHorizontally(v);
}
void OnViewportGeometryChanged(GeometryChangedEvent evt)
{
var headerPadding = m_MultiColumnHeader.resolvedStyle.paddingLeft + m_MultiColumnHeader.resolvedStyle.paddingRight;
m_MultiColumnHeader.style.maxWidth = evt.newRect.width - headerPadding;
m_MultiColumnHeader.style.maxWidth = evt.newRect.width - headerPadding;
UpdateContentContainer(m_View);
}
void OnColumnContainerGeometryChanged(GeometryChangedEvent evt)
{
UpdateContentContainer(m_View);
}
void UpdateContentContainer(BaseVerticalCollectionView collectionView)
{
var headerTotalWidth = m_MultiColumnHeader.columnContainer.layout.width;
var targetWidth = Mathf.Max(headerTotalWidth, collectionView.scrollView.contentViewport.resolvedStyle.width);
collectionView.scrollView.contentContainer.style.width = targetWidth;
}
void OnColumnSortingChanged()
{
UpdateDragger();
if (sortingMode == ColumnSortingMode.Default)
{
m_View.RefreshItems();
}
columnSortingChanged?.Invoke();
}
internal void UpdateDragger()
{
if (sortingMode == ColumnSortingMode.None)
{
m_View.dragger.enabled = true;
return;
}
m_View.dragger.enabled = header.sortedColumnReadonly.Count == 0;
}
internal void SortIfNeeded()
{
UpdateDragger();
if (sortingMode == ColumnSortingMode.None || sortingMode != ColumnSortingMode.Default || m_View.itemsSource == null)
{
return;
}
var wasSorted = m_SortedIndices?.Count > 0;
if (wasSorted)
{
// We need to unbind before the indices are sorted, so that the sorted index matches the previous one.
m_View.virtualizationController.UnbindAll();
}
m_SortedIndices?.Clear();
if (header.sortedColumnReadonly.Count == 0)
{
return;
}
using var pool = ListPool<int>.Get(out var sortedList);
for (var i = 0; i < m_View.itemsSource.Count; i++)
{
sortedList.Add(i);
}
sortedList.Sort(CombinedComparison);
m_SortedIndices ??= new List<int>(capacity: m_View.itemsSource.Count);
m_SortedIndices.AddRange(sortedList);
}
int CombinedComparison(int a, int b)
{
if (m_View.viewController is BaseTreeViewController treeViewController)
{
var idA = treeViewController.GetIdForIndex(a);
var idB = treeViewController.GetIdForIndex(b);
var parentIdA = treeViewController.GetParentId(idA);
var parentIdB = treeViewController.GetParentId(idB);
// Only sort items within the same parent.
if (parentIdA != parentIdB)
{
var depthA = treeViewController.GetIndentationDepth(idA);
var depthB = treeViewController.GetIndentationDepth(idB);
var originalDepthA = depthA;
var originalDepthB = depthB;
// We walk up until both sides are at the same depth
while (depthA > depthB)
{
depthA--;
idA = parentIdA;
parentIdA = treeViewController.GetParentId(parentIdA);
}
while (depthB > depthA)
{
depthB--;
idB = parentIdB;
parentIdB = treeViewController.GetParentId(parentIdB);
}
// Now both are at the same depth, we then walk up the tree until we hit the same element
while (parentIdA != parentIdB)
{
idA = parentIdA;
idB = parentIdB;
parentIdA = treeViewController.GetParentId(parentIdA);
parentIdB = treeViewController.GetParentId(parentIdB);
}
// We were looking at a node and one of its parent, so compare the original depths.
if (idA == idB)
{
return originalDepthA.CompareTo(originalDepthB);
}
// Compare the indices now that we're at the same depth.
a = treeViewController.GetIndexForId(idA);
b = treeViewController.GetIndexForId(idB);
}
}
var result = 0;
foreach (var sortedColumn in header.sortedColumns)
{
result = sortedColumn.column.comparison?.Invoke(a, b) ?? 0;
if (result != 0)
{
if (sortedColumn.direction == SortDirection.Descending)
{
result = -result;
}
break;
}
}
// When equal, we keep the current order.
return result == 0 ? a.CompareTo(b) : result;
}
internal int GetSortedIndex(int index)
{
if (m_SortedIndices == null)
return index;
if (index < 0 || index >= m_SortedIndices.Count)
return index;
return m_SortedIndices.Count > 0 ? m_SortedIndices[index] : index;
}
void OnContextMenuPopulateEvent(ContextualMenuPopulateEvent evt, Column column) => headerContextMenuPopulateEvent?.Invoke(evt, column);
void OnColumnResized(int index, float width)
{
foreach (var item in m_View.activeItems)
{
item.bindableElement.ElementAt(index).style.width = width;
}
}
void OnColumnAdded(Column column, int index)
{
m_View.Rebuild();
}
void OnColumnRemoved(Column column)
{
m_View.Rebuild();
}
void OnColumnReordered(Column column, int from, int to)
{
if (m_MultiColumnHeader.isApplyingViewState)
return;
m_View.Rebuild();
}
void OnColumnsChanged(Column column, ColumnDataType type)
{
if (m_MultiColumnHeader.isApplyingViewState)
return;
if (type == ColumnDataType.Visibility) m_View.Rebuild();
}
void OnColumnChanged(ColumnsDataType type)
{
if (m_MultiColumnHeader.isApplyingViewState)
return;
if (type == ColumnsDataType.PrimaryColumn) m_View.Rebuild();
}
void OnViewDataRestored()
{
m_View.Rebuild();
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/MultiColumnController.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/MultiColumn/MultiColumnController.cs",
"repo_id": "UnityCsReference",
"token_count": 8752
} | 494 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
/// <summary>
/// A slider containing Integer discrete values. For more information, refer to [[wiki:UIE-uxml-element-sliderInt|UXML element SliderInt]].
/// </summary>
public class SliderInt : BaseSlider<int>
{
[UnityEngine.Internal.ExcludeFromDocs, Serializable]
public new class UxmlSerializedData : BaseSlider<int>.UxmlSerializedData
{
#pragma warning disable 649
[SerializeField] int lowValue;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags lowValue_UxmlAttributeFlags;
[SerializeField] int highValue;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags highValue_UxmlAttributeFlags;
[SerializeField] float pageSize;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags pageSize_UxmlAttributeFlags;
[SerializeField] bool showInputField;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags showInputField_UxmlAttributeFlags;
[SerializeField] SliderDirection direction;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags direction_UxmlAttributeFlags;
[SerializeField] bool inverted;
[SerializeField, UxmlIgnore, HideInInspector] UxmlAttributeFlags inverted_UxmlAttributeFlags;
#pragma warning restore 649
public override object CreateInstance() => new SliderInt();
public override void Deserialize(object obj)
{
base.Deserialize(obj);
var e = (SliderInt)obj;
if (ShouldWriteAttributeValue(lowValue_UxmlAttributeFlags))
e.lowValue = lowValue;
if (ShouldWriteAttributeValue(highValue_UxmlAttributeFlags))
e.highValue = highValue;
if (ShouldWriteAttributeValue(direction_UxmlAttributeFlags))
e.direction = direction;
if (ShouldWriteAttributeValue(pageSize_UxmlAttributeFlags))
e.pageSize = pageSize;
if (ShouldWriteAttributeValue(showInputField_UxmlAttributeFlags))
e.showInputField = showInputField;
if (ShouldWriteAttributeValue(inverted_UxmlAttributeFlags))
e.inverted = inverted;
}
}
/// <summary>
/// Instantiates a <see cref="SliderInt"/> using the data read from a UXML file.
/// </summary>
[Obsolete("UxmlFactory is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlFactory : UxmlFactory<SliderInt, UxmlTraits> {}
/// <summary>
/// Defines <see cref="UxmlTraits"/> for the <see cref="SliderInt"/>.
/// </summary>
[Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)]
public new class UxmlTraits : UxmlTraits<UxmlIntAttributeDescription>
{
UxmlIntAttributeDescription m_LowValue = new UxmlIntAttributeDescription { name = "low-value" };
UxmlIntAttributeDescription m_HighValue = new UxmlIntAttributeDescription { name = "high-value", defaultValue = kDefaultHighValue };
UxmlIntAttributeDescription m_PageSize = new UxmlIntAttributeDescription { name = "page-size", defaultValue = (int)kDefaultPageSize };
UxmlBoolAttributeDescription m_ShowInputField = new UxmlBoolAttributeDescription { name = "show-input-field", defaultValue = kDefaultShowInputField };
UxmlEnumAttributeDescription<SliderDirection> m_Direction = new UxmlEnumAttributeDescription<SliderDirection> { name = "direction", defaultValue = SliderDirection.Horizontal };
UxmlBoolAttributeDescription m_Inverted = new UxmlBoolAttributeDescription { name = "inverted", defaultValue = kDefaultInverted };
/// <summary>
/// Initialize <see cref="SliderInt"/> properties using values from the attribute bag.
/// </summary>
/// <param name="ve">The object to initialize.</param>
/// <param name="bag">The bag of attributes.</param>
/// <param name="cc">The creation context; unused.</param>
public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc)
{
var f = (SliderInt)ve;
f.lowValue = m_LowValue.GetValueFromBag(bag, cc);
f.highValue = m_HighValue.GetValueFromBag(bag, cc);
f.direction = m_Direction.GetValueFromBag(bag, cc);
f.pageSize = m_PageSize.GetValueFromBag(bag, cc);
f.showInputField = m_ShowInputField.GetValueFromBag(bag, cc);
f.inverted = m_Inverted.GetValueFromBag(bag, cc);
base.Init(ve, bag, cc);
}
}
internal const int kDefaultHighValue = 10;
/// <summary>
/// USS class name of elements of this type.
/// </summary>
public new static readonly string ussClassName = "unity-slider-int";
/// <summary>
/// USS class name of labels in elements of this type.
/// </summary>
public new static readonly string labelUssClassName = ussClassName + "__label";
/// <summary>
/// USS class name of input elements in elements of this type.
/// </summary>
public new static readonly string inputUssClassName = ussClassName + "__input";
/// <summary>
/// Constructors for the <see cref="SliderInt"/>.
/// </summary>
public SliderInt()
: this(null, 0, kDefaultHighValue) {}
/// <summary>
/// Constructors for the <see cref="SliderInt"/>.
/// </summary>
/// <param name="start">This is the low value of the slider.</param>
/// <param name="end">This is the high value of the slider.</param>
/// <param name="direction">This is the slider direction, horizontal or vertical.</param>
/// <param name="pageSize">This is the number of values to change when the slider is clicked.</param>
public SliderInt(int start, int end, SliderDirection direction = SliderDirection.Horizontal, float pageSize = kDefaultPageSize)
: this(null, start, end, direction, pageSize) {}
/// <summary>
/// Constructors for the <see cref="SliderInt"/>.
/// </summary>
/// <param name="start">This is the low value of the slider.</param>
/// <param name="end">This is the high value of the slider.</param>
/// <param name="direction">This is the slider direction, horizontal or vertical.</param>
/// <param name="pageSize">This is the number of values to change when the slider is clicked.</param>
public SliderInt(string label, int start = 0, int end = kDefaultHighValue, SliderDirection direction = SliderDirection.Horizontal, float pageSize = kDefaultPageSize)
: base(label, start, end, direction, pageSize)
{
AddToClassList(ussClassName);
labelElement.AddToClassList(labelUssClassName);
visualInput.AddToClassList(inputUssClassName);
}
/// <summary>
/// The value to add or remove to the SliderInt.value when it is clicked.
/// </summary>
/// <remarks>
/// This is casted to int.
/// </remarks>
public override float pageSize
{
get { return base.pageSize; }
set { base.pageSize = Mathf.RoundToInt(value); }
}
/// <inheritdoc />
public override void ApplyInputDeviceDelta(Vector3 delta, DeltaSpeed speed, int startValue)
{
double sensitivity = NumericFieldDraggerUtility.CalculateIntDragSensitivity(startValue, lowValue, highValue);
float acceleration = NumericFieldDraggerUtility.Acceleration(speed == DeltaSpeed.Fast, speed == DeltaSpeed.Slow);
long v = value;
v += (long)Math.Round(NumericFieldDraggerUtility.NiceDelta(delta, acceleration) * sensitivity);
value = (int)v;
}
internal override int SliderLerpUnclamped(int a, int b, float interpolant)
{
return Mathf.RoundToInt(Mathf.LerpUnclamped((float)a, (float)b, interpolant));
}
internal override float SliderNormalizeValue(int currentValue, int lowerValue, int higherValue)
{
return ((float)currentValue - (float)lowerValue) / ((float)higherValue - (float)lowerValue);
}
internal override int SliderRange()
{
return Math.Abs(highValue - lowValue);
}
internal override int ParseStringToValue(string previousValue, string newValue)
{
if (UINumericFieldsUtils.TryConvertStringToInt(newValue, previousValue, out var value))
return value;
return 0;
}
internal override void ComputeValueAndDirectionFromClick(float sliderLength, float dragElementLength, float dragElementPos, float dragElementLastPos)
{
if (Mathf.Approximately(pageSize, 0.0f))
{
base.ComputeValueAndDirectionFromClick(sliderLength, dragElementLength, dragElementPos, dragElementLastPos);
}
else
{
var totalRange = sliderLength - dragElementLength;
if (Mathf.Abs(totalRange) < UIRUtility.k_Epsilon)
return;
var adjustedPageDirection = (int)pageSize;
if ((lowValue > highValue && !inverted) ||
(lowValue < highValue && inverted) ||
(direction == SliderDirection.Vertical && !inverted))
{
adjustedPageDirection = -adjustedPageDirection;
}
var isPositionDecreasing = dragElementLastPos < dragElementPos;
var isPositionIncreasing = dragElementLastPos > (dragElementPos + dragElementLength);
var isDraggingHighToLow = inverted ? isPositionIncreasing : isPositionDecreasing;
var isDraggingLowToHigh = inverted ? isPositionDecreasing : isPositionIncreasing;
if (isDraggingHighToLow && (clampedDragger.dragDirection != ClampedDragger<int>.DragDirection.LowToHigh))
{
clampedDragger.dragDirection = ClampedDragger<int>.DragDirection.HighToLow;
// Compute the next value based on the page size.
value = value - adjustedPageDirection;
}
else if (isDraggingLowToHigh && (clampedDragger.dragDirection != ClampedDragger<int>.DragDirection.HighToLow))
{
clampedDragger.dragDirection = ClampedDragger<int>.DragDirection.LowToHigh;
// Compute the next value based on the page size.
value = value + adjustedPageDirection;
}
}
}
internal override void ComputeValueFromKey(SliderKey sliderKey, bool isShift)
{
switch (sliderKey)
{
case SliderKey.None:
return;
case SliderKey.Lowest:
value = lowValue;
return;
case SliderKey.Highest:
value = highValue;
return;
}
bool isPageSize = sliderKey == SliderKey.LowerPage || sliderKey == SliderKey.HigherPage;
// Change by approximately 1/100 of entire range, or 1/10 if holding down shift
// But round to nearest power of ten to get nice resulting numbers.
var delta = GetClosestPowerOfTen(Mathf.Abs((highValue - lowValue) * 0.01f));
if (delta < 1)
delta = 1;
if (isPageSize)
delta *= pageSize;
else if (isShift)
delta *= 10;
// Increment or decrement by just over half the delta.
// This means that e.g. if delta is 1, incrementing from 1.0 will go to 2.0,
// but incrementing from 0.9 is going to 1.0 rather than 2.0.
// This feels more right since 1.0 is the "next" one.
if (sliderKey == SliderKey.Lower || sliderKey == SliderKey.LowerPage)
delta = -delta;
// Now round to a multiple of our delta value so we get a round end result instead of just a round delta.
value = Mathf.RoundToInt(RoundToMultipleOf(value + (delta * 0.5001f), Mathf.Abs(delta)));
}
}
}
| UnityCsReference/Modules/UIElements/Core/Controls/SliderInt.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Controls/SliderInt.cs",
"repo_id": "UnityCsReference",
"token_count": 5491
} | 495 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Properties;
namespace UnityEngine.UIElements
{
internal class SetValueVisitor<TSrcValue> : PathVisitor
{
public static readonly UnityEngine.Pool.ObjectPool<SetValueVisitor<TSrcValue>> Pool = new (() => new SetValueVisitor<TSrcValue>(), v => v.Reset());
public TSrcValue Value;
public ConverterGroup group { get; set; }
public override void Reset()
{
base.Reset();
Value = default;
group = default;
}
protected override void VisitPath<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value)
{
if (property.IsReadOnly)
{
ReturnCode = VisitReturnCode.AccessViolation;
return;
}
if (null != group && group.TryConvert(ref Value, out TValue local))
{
property.SetValue(ref container, local);
}
else if (ConverterGroups.TryConvert(ref Value, out TValue global))
{
property.SetValue(ref container, global);
}
else
{
ReturnCode = VisitReturnCode.InvalidCast;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Conversions/SetValueVisitor.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Conversions/SetValueVisitor.cs",
"repo_id": "UnityCsReference",
"token_count": 649
} | 496 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
namespace UnityEngine.UIElements
{
internal class ListViewDragger : DragEventsProcessor
{
internal struct DragPosition : IEquatable<DragPosition>
{
public int insertAtIndex;
public int parentId;
public int childIndex;
public ReusableCollectionItem recycledItem;
public DragAndDropPosition dropPosition;
public bool Equals(DragPosition other)
{
return insertAtIndex == other.insertAtIndex
&& parentId == other.parentId
&& childIndex == other.childIndex
&& Equals(recycledItem, other.recycledItem)
&& dropPosition == other.dropPosition;
}
public override bool Equals(object obj)
{
return obj is DragPosition position && Equals(position);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = insertAtIndex;
hashCode = (hashCode * 397) ^ parentId;
hashCode = (hashCode * 397) ^ childIndex;
hashCode = (hashCode * 397) ^ (recycledItem?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (int)dropPosition;
return hashCode;
}
}
}
DragPosition m_LastDragPosition;
VisualElement m_DragHoverBar;
VisualElement m_DragHoverItemMarker;
VisualElement m_DragHoverSiblingMarker;
float m_LeftIndentation = -1f;
float m_SiblingBottom = -1f;
bool m_Enabled = true;
const int k_AutoScrollAreaSize = 5;
const int k_BetweenElementsAreaSize = 5;
const int k_PanSpeed = 20;
const int k_DragHoverBarHeight = 2;
protected BaseVerticalCollectionView targetView => m_Target as BaseVerticalCollectionView;
protected ScrollView targetScrollView => targetView.scrollView;
public ICollectionDragAndDropController dragAndDropController { get; set; }
// Some settings can disable reordering temporarily, like multi column sorting
internal bool enabled
{
get => m_Enabled;
set
{
m_Enabled = value;
// Avoid a full refresh by directly updating the visible handles.
if (targetView is BaseListView)
{
foreach (var item in targetView.activeItems)
{
if (item is not ReusableListViewItem listItem)
continue;
listItem.SetDragHandleEnabled(targetView.dragger.enabled);
}
}
}
}
public ListViewDragger(BaseVerticalCollectionView listView)
: base(listView) {}
protected override bool CanStartDrag(Vector3 pointerPosition)
{
if (dragAndDropController == null)
return false;
if (!targetScrollView.contentContainer.worldBound.Contains(pointerPosition))
return false;
if (!enabled)
return false;
var recycledItem = GetRecycledItem(pointerPosition);
if (recycledItem != null && targetView.HasCanStartDrag())
{
var ids = targetView.selectedIds.Any() ? targetView.selectedIds : new[] { recycledItem.id };
return targetView.RaiseCanStartDrag(recycledItem, ids);
}
if (targetView.selectedIds.Any())
{
return dragAndDropController.CanStartDrag(targetView.selectedIds);
}
return recycledItem != null && dragAndDropController.CanStartDrag(new[] { recycledItem.id });
}
protected internal override StartDragArgs StartDrag(Vector3 pointerPosition)
{
var recycledItem = GetRecycledItem(pointerPosition);
IEnumerable<int> ids;
if (recycledItem != null)
{
if (!targetView.selectedIndices.Contains(recycledItem.index))
{
targetView.SetSelection(recycledItem.index);
}
ids = targetView.selectedIds;
}
else
{
ids = targetView.selectedIds.Any() ? targetView.selectedIds : Enumerable.Empty<int>();
}
var startDragArgs = dragAndDropController.SetupDragAndDrop(ids);
// User defined handling, if any.
startDragArgs = targetView.RaiseSetupDragAndDrop(recycledItem, dragAndDropController.GetSortedSelectedIds(), startDragArgs);
startDragArgs.SetGenericData(DragAndDropData.dragSourceKey, targetView);
return startDragArgs;
}
protected internal override void UpdateDrag(Vector3 pointerPosition)
{
var dragPosition = new DragPosition();
var visualMode = GetVisualMode(pointerPosition, ref dragPosition);
if (visualMode == DragVisualMode.Rejected)
{
ClearDragAndDropUI(false);
}
else
{
HandleDragAndScroll(pointerPosition);
HandleAutoExpansion(pointerPosition);
ApplyDragAndDropUI(dragPosition);
}
dragAndDrop.SetVisualMode(visualMode);
dragAndDrop.UpdateDrag(pointerPosition);
}
DragVisualMode GetVisualMode(Vector3 pointerPosition, ref DragPosition dragPosition)
{
if (dragAndDropController == null)
{
return DragVisualMode.Rejected;
}
var foundPosition = TryGetDragPosition(pointerPosition, ref dragPosition);
var args = MakeDragAndDropArgs(dragPosition);
// User defined handling, if any.
var mode = targetView.RaiseHandleDragAndDrop(pointerPosition, args);
if (mode != DragVisualMode.None)
return mode;
return foundPosition ? dragAndDropController.HandleDragAndDrop(args) : DragVisualMode.Rejected;
}
protected internal override void OnDrop(Vector3 pointerPosition)
{
var dragPosition = new DragPosition();
if (!TryGetDragPosition(pointerPosition, ref dragPosition))
return;
var args = MakeDragAndDropArgs(dragPosition);
// User defined drop handling.
var mode = targetView.RaiseDrop(pointerPosition, args);
if (mode != DragVisualMode.None)
{
if (mode != DragVisualMode.Rejected)
dragAndDrop.AcceptDrag();
else
dragAndDropController.DragCleanup();
return;
}
if (dragAndDropController.HandleDragAndDrop(args) != DragVisualMode.Rejected)
{
dragAndDropController.OnDrop(args);
dragAndDrop.AcceptDrag();
}
else
{
dragAndDropController.DragCleanup();
}
}
// Internal for tests.
internal void HandleDragAndScroll(Vector2 pointerPosition)
{
var scrollUp = pointerPosition.y < targetScrollView.worldBound.yMin + k_AutoScrollAreaSize;
var scrollDown = pointerPosition.y > targetScrollView.worldBound.yMax - k_AutoScrollAreaSize;
if (scrollUp || scrollDown)
{
var offset = targetScrollView.scrollOffset + (scrollUp ? Vector2.down : Vector2.up) * k_PanSpeed;
offset.y = Mathf.Clamp(offset.y, 0f, Mathf.Max(0, targetScrollView.contentContainer.worldBound.height - targetScrollView.contentViewport.worldBound.height));
targetScrollView.scrollOffset = offset;
}
}
void HandleAutoExpansion(Vector2 pointerPosition)
{
var recycledItem = GetRecycledItem(pointerPosition);
if (recycledItem == null)
return;
dragAndDropController.HandleAutoExpand(recycledItem, pointerPosition);
}
void ApplyDragAndDropUI(DragPosition dragPosition)
{
if (m_LastDragPosition.Equals(dragPosition))
return;
if (m_DragHoverBar == null)
{
m_DragHoverBar = new VisualElement();
m_DragHoverBar.AddToClassList(BaseVerticalCollectionView.dragHoverBarUssClassName);
m_DragHoverBar.style.width = targetView.localBound.width;
m_DragHoverBar.style.visibility = Visibility.Hidden;
m_DragHoverBar.pickingMode = PickingMode.Ignore;
void GeometryChangedCallback(GeometryChangedEvent e)
{
m_DragHoverBar.style.width = targetView.localBound.width;
}
targetView.RegisterCallback<GeometryChangedEvent>(GeometryChangedCallback);
targetScrollView.contentViewport.Add(m_DragHoverBar);
}
if (m_DragHoverItemMarker == null && targetView is BaseTreeView)
{
m_DragHoverItemMarker = new VisualElement();
m_DragHoverItemMarker.AddToClassList(BaseVerticalCollectionView.dragHoverMarkerUssClassName);
m_DragHoverItemMarker.style.visibility = Visibility.Hidden;
m_DragHoverItemMarker.pickingMode = PickingMode.Ignore;
m_DragHoverBar.Add(m_DragHoverItemMarker);
m_DragHoverSiblingMarker = new VisualElement();
m_DragHoverSiblingMarker.AddToClassList(BaseVerticalCollectionView.dragHoverMarkerUssClassName);
m_DragHoverSiblingMarker.style.visibility = Visibility.Hidden;
m_DragHoverSiblingMarker.pickingMode = PickingMode.Ignore;
targetScrollView.contentViewport.Add(m_DragHoverSiblingMarker);
}
ClearDragAndDropUI(false);
m_LastDragPosition = dragPosition;
switch (dragPosition.dropPosition)
{
case DragAndDropPosition.OverItem:
dragPosition.recycledItem.rootElement.AddToClassList(BaseVerticalCollectionView.itemDragHoverUssClassName);
break;
case DragAndDropPosition.BetweenItems:
if (dragPosition.insertAtIndex == 0)
{
PlaceHoverBarAt(0);
}
else
{
var beforeItem = targetView.GetRecycledItemFromIndex(dragPosition.insertAtIndex - 1);
var afterItem = targetView.GetRecycledItemFromIndex(dragPosition.insertAtIndex);
PlaceHoverBarAtElement(beforeItem ?? afterItem);
}
break;
case DragAndDropPosition.OutsideItems:
var recycledItem = targetView.GetRecycledItemFromIndex(targetView.itemsSource.Count - 1);
if (recycledItem != null)
PlaceHoverBarAtElement(recycledItem);
else
PlaceHoverBarAt(0);
break;
default:
throw new ArgumentOutOfRangeException(nameof(dragPosition.dropPosition),
dragPosition.dropPosition,
$"Unsupported {nameof(dragPosition.dropPosition)} value");
}
// For some reason, the move cursor is missing when using visualMode, so we force it in editor.
if (dragAndDrop.data.visualMode == DragVisualMode.Move && targetView.elementPanel.contextType == ContextType.Editor)
{
targetView.elementPanel.cursorManager.SetCursor(new Cursor { defaultCursorId = 8 });
}
}
protected virtual bool TryGetDragPosition(Vector2 pointerPosition, ref DragPosition dragPosition)
{
var recycledItem = GetRecycledItem(pointerPosition);
if (recycledItem == null)
{
if (!targetView.worldBound.Contains(pointerPosition))
return false;
dragPosition.dropPosition = DragAndDropPosition.OutsideItems;
if (pointerPosition.y >= targetScrollView.contentContainer.worldBound.yMax)
dragPosition.insertAtIndex = targetView.itemsSource.Count;
else
dragPosition.insertAtIndex = 0;
HandleTreePosition(pointerPosition, ref dragPosition);
return true;
}
// Below an item
if (recycledItem.rootElement.worldBound.yMax - pointerPosition.y < k_BetweenElementsAreaSize)
{
dragPosition.insertAtIndex = recycledItem.index + 1;
dragPosition.dropPosition = DragAndDropPosition.BetweenItems;
}
// Upon an item
else if (pointerPosition.y - recycledItem.rootElement.worldBound.yMin > k_BetweenElementsAreaSize)
{
var scrollOffset = targetScrollView.scrollOffset;
targetScrollView.ScrollTo(recycledItem.rootElement);
if (!Mathf.Approximately(scrollOffset.x, targetScrollView.scrollOffset.x) || !Mathf.Approximately(scrollOffset.y, targetScrollView.scrollOffset.y))
{
return TryGetDragPosition(pointerPosition, ref dragPosition);
}
dragPosition.recycledItem = recycledItem;
dragPosition.insertAtIndex = recycledItem.index;
dragPosition.dropPosition = DragAndDropPosition.OverItem;
}
// Above an item
else
{
dragPosition.insertAtIndex = recycledItem.index;
dragPosition.dropPosition = DragAndDropPosition.BetweenItems;
}
HandleTreePosition(pointerPosition, ref dragPosition);
return true;
}
void HandleTreePosition(Vector2 pointerPosition, ref DragPosition dragPosition)
{
// Reset values.
dragPosition.parentId = -1;
dragPosition.childIndex = -1;
m_LeftIndentation = -1f;
m_SiblingBottom = -1f;
if (targetView is not BaseTreeView treeView)
return;
if (dragPosition.insertAtIndex < 0)
return; // Already handled.
// Insert inside an item, as the last child.
var treeController = treeView.viewController;
if (dragPosition.dropPosition == DragAndDropPosition.OverItem)
{
dragPosition.parentId = treeController.GetIdForIndex(dragPosition.insertAtIndex);
dragPosition.childIndex = -1;
return;
}
// Above first row.
if (dragPosition.insertAtIndex <= 0)
{
dragPosition.childIndex = 0;
return;
}
HandleSiblingInsertionAtAvailableDepthsAndChangeTargetIfNeeded(ref dragPosition, pointerPosition);
}
void HandleSiblingInsertionAtAvailableDepthsAndChangeTargetIfNeeded(ref DragPosition dragPosition, Vector2 pointerPosition)
{
if (targetView is not BaseTreeView treeView)
return;
var treeController = treeView.viewController;
var targetIndex = dragPosition.insertAtIndex;
var initialTargetId = treeController.GetIdForIndex(targetIndex);
// var targetId = initialTargetId;
GetPreviousAndNextItemsIgnoringDraggedItems(dragPosition.insertAtIndex, out var previousItemId, out var nextItemId);
if (previousItemId == BaseTreeView.invalidId)
return; // Above first row so keep targetItem
var hoveringBetweenExpandedParentAndFirstChild = treeController.HasChildren(previousItemId) && treeView.IsExpanded(previousItemId);
var previousItemDepth = treeController.GetIndentationDepth(previousItemId);
var nextItemDepth = treeController.GetIndentationDepth(nextItemId);
var minDepth = nextItemId != BaseTreeView.invalidId ? nextItemDepth : 0;
var maxDepth = treeController.GetIndentationDepth(previousItemId) + (hoveringBetweenExpandedParentAndFirstChild ? 1 : 0);
// Change target item.
var targetId = previousItemId;
// Get the indent width
var toggleWidth = 15f;
var indentWidth = 15f;
if (previousItemDepth > 0)
{
var rootElement = treeView.GetRootElementForId(previousItemId);
var indentElement = rootElement.Q(BaseTreeView.itemIndentUssClassName);
var toggle = rootElement.Q(BaseTreeView.itemToggleUssClassName);
toggleWidth = toggle.layout.width;
indentWidth = indentElement.layout.width / previousItemDepth;
}
else
{
var initialItemDepth = treeView.viewController.GetIndentationDepth(initialTargetId);
if (initialItemDepth > 0)
{
var rootElement = treeView.GetRootElementForId(initialTargetId);
var indentElement = rootElement.Q(BaseTreeView.itemIndentUssClassName);
var toggle = rootElement.Q(BaseTreeView.itemToggleUssClassName);
toggleWidth = toggle.layout.width;
indentWidth = indentElement.layout.width / initialItemDepth;
}
}
if (maxDepth <= minDepth)
{
m_LeftIndentation = toggleWidth + indentWidth * minDepth;
if (hoveringBetweenExpandedParentAndFirstChild)
{
dragPosition.parentId = previousItemId;
dragPosition.childIndex = 0;
}
else
{
dragPosition.parentId = treeController.GetParentId(previousItemId);
dragPosition.childIndex = treeController.GetChildIndexForId(nextItemId);
}
return; // The nextItem is a descendant of previous item so keep targetItem
}
var localMousePosition = treeView.scrollView.contentContainer.WorldToLocal(pointerPosition);
var cursorDepth = Mathf.FloorToInt((localMousePosition.x - toggleWidth) / indentWidth);
if (cursorDepth >= maxDepth)
{
m_LeftIndentation = toggleWidth + indentWidth * maxDepth;
if (hoveringBetweenExpandedParentAndFirstChild)
{
dragPosition.parentId = previousItemId;
dragPosition.childIndex = 0;
}
else
{
dragPosition.parentId = treeController.GetParentId(previousItemId);
dragPosition.childIndex = treeController.GetChildIndexForId(previousItemId) + 1;
}
return; // No need to change targetItem if same or higher depth
}
// Search through parents for a new target that matches the cursor
var targetDepth = treeController.GetIndentationDepth(targetId);
while (targetDepth > minDepth)
{
if (targetDepth == cursorDepth)
break;
targetId = treeController.GetParentId(targetId);
targetDepth--;
}
var didChangeTargetToAncestor = targetId != initialTargetId;
if (didChangeTargetToAncestor)
{
var siblingRoot = treeView.GetRootElementForId(targetId);
if (siblingRoot != null)
{
var contentViewport = targetScrollView.contentViewport;
var elementBounds = contentViewport.WorldToLocal(siblingRoot.worldBound);
if (contentViewport.localBound.yMin < elementBounds.yMax && elementBounds.yMax < contentViewport.localBound.yMax)
{
m_SiblingBottom = elementBounds.yMax;
}
}
}
// Change to new target item
dragPosition.parentId = treeController.GetParentId(targetId);
dragPosition.childIndex = treeController.GetChildIndexForId(targetId) + 1;
m_LeftIndentation = toggleWidth + indentWidth * targetDepth;
}
void GetPreviousAndNextItemsIgnoringDraggedItems(int insertAtIndex, out int previousItemId, out int nextItemId)
{
previousItemId = nextItemId = -1;
var previousItemIndex = insertAtIndex - 1;
var nextItemIndex = insertAtIndex;
while (previousItemIndex >= 0)
{
var id = targetView.viewController.GetIdForIndex(previousItemIndex);
if (!dragAndDropController.GetSortedSelectedIds().Contains(id))
{
previousItemId = id;
break;
}
previousItemIndex--;
}
while (nextItemIndex < targetView.itemsSource.Count)
{
var id = targetView.viewController.GetIdForIndex(nextItemIndex);
if (!dragAndDropController.GetSortedSelectedIds().Contains(id))
{
nextItemId = id;
break;
}
nextItemIndex++;
}
}
protected DragAndDropArgs MakeDragAndDropArgs(DragPosition dragPosition)
{
object target = null;
var recycledItem = dragPosition.recycledItem;
if (recycledItem != null)
target = targetView.viewController.GetItemForIndex(recycledItem.index);
return new DragAndDropArgs
{
target = target,
insertAtIndex = dragPosition.insertAtIndex,
parentId = dragPosition.parentId,
childIndex = dragPosition.childIndex,
dragAndDropPosition = dragPosition.dropPosition,
dragAndDropData = DragAndDropUtility.GetDragAndDrop(m_Target.panel).data,
};
}
float GetHoverBarTopPosition(ReusableCollectionItem item)
{
var contentViewport = targetScrollView.contentViewport;
var elementBounds = contentViewport.WorldToLocal(item.rootElement.worldBound);
var top = Mathf.Min(elementBounds.yMax, contentViewport.localBound.yMax - k_DragHoverBarHeight);
return top;
}
void PlaceHoverBarAtElement(ReusableCollectionItem item)
{
PlaceHoverBarAt(GetHoverBarTopPosition(item), m_LeftIndentation, m_SiblingBottom);
}
void PlaceHoverBarAt(float top, float indentationPadding = -1f, float siblingBottom = -1f)
{
m_DragHoverBar.style.top = top;
m_DragHoverBar.style.visibility = Visibility.Visible;
if (m_DragHoverItemMarker != null)
{
m_DragHoverItemMarker.style.visibility = Visibility.Visible;
}
if (indentationPadding >= 0)
{
m_DragHoverBar.style.marginLeft = indentationPadding;
m_DragHoverBar.style.width = targetView.localBound.width - indentationPadding;
if (siblingBottom > 0 && m_DragHoverSiblingMarker != null)
{
m_DragHoverSiblingMarker.style.top = siblingBottom;
m_DragHoverSiblingMarker.style.visibility = Visibility.Visible;
m_DragHoverSiblingMarker.style.marginLeft = indentationPadding;
}
}
else
{
m_DragHoverBar.style.marginLeft = 0;
m_DragHoverBar.style.width = targetView.localBound.width;
}
}
protected override void ClearDragAndDropUI(bool dragCancelled)
{
if (dragCancelled)
{
dragAndDropController.DragCleanup();
}
targetView.elementPanel.cursorManager.ResetCursor();
m_LastDragPosition = new DragPosition();
foreach (var item in targetView.activeItems)
{
item.rootElement.RemoveFromClassList(BaseVerticalCollectionView.itemDragHoverUssClassName);
}
if (m_DragHoverBar != null)
m_DragHoverBar.style.visibility = Visibility.Hidden;
if (m_DragHoverItemMarker != null)
m_DragHoverItemMarker.style.visibility = Visibility.Hidden;
if (m_DragHoverSiblingMarker != null)
m_DragHoverSiblingMarker.style.visibility = Visibility.Hidden;
}
protected ReusableCollectionItem GetRecycledItem(Vector3 pointerPosition)
{
foreach (var recycledItem in targetView.activeItems)
{
if (recycledItem.rootElement.worldBound.Contains(pointerPosition))
return recycledItem;
}
return null;
}
}
internal static class ListViewDraggerExtension
{
public static ReusableCollectionItem GetRecycledItemFromId(this BaseVerticalCollectionView listView, int id)
{
foreach (var recycledItem in listView.activeItems)
{
if (recycledItem.id.Equals(id))
return recycledItem;
}
return null;
}
public static ReusableCollectionItem GetRecycledItemFromIndex(this BaseVerticalCollectionView listView, int index)
{
foreach (var recycledItem in listView.activeItems)
{
if (recycledItem.index.Equals(index))
return recycledItem;
}
return null;
}
}
}
| UnityCsReference/Modules/UIElements/Core/DragAndDrop/ListViewDragger.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/DragAndDrop/ListViewDragger.cs",
"repo_id": "UnityCsReference",
"token_count": 12766
} | 497 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using JetBrains.Annotations;
using UnityEngine.Pool;
namespace UnityEngine.UIElements
{
/// <summary>
/// Use this enum to specify during which phases the event handler is executed.
/// </summary>
public enum TrickleDown
{
/// <summary>
/// The event handler should be executed during the AtTarget and BubbleUp phases.
/// </summary>
NoTrickleDown = 0,
/// <summary>
/// The event handler should be executed during the AtTarget and TrickleDown phases.
/// </summary>
TrickleDown = 1
}
[Flags]
internal enum InvokePolicy
{
Default = 0,
IncludeDisabled = 1,
Once = 2
}
internal class EventCallbackListPool
{
readonly Stack<EventCallbackList> m_Stack = new Stack<EventCallbackList>();
public EventCallbackList Get(EventCallbackList initializer)
{
EventCallbackList element;
if (m_Stack.Count == 0)
{
if (initializer != null)
element = new EventCallbackList(initializer);
else
element = new EventCallbackList();
}
else
{
element = m_Stack.Pop();
if (initializer != null)
element.AddRange(initializer);
}
return element;
}
public void Release(EventCallbackList element)
{
element.Clear();
m_Stack.Push(element);
}
}
internal class EventCallbackList
{
public static readonly EventCallbackList EmptyList = new EventCallbackList();
private static readonly EventCallbackFunctorBase[] EmptyArray = new EventCallbackFunctorBase[0];
private EventCallbackFunctorBase[] m_Array;
private int m_Count;
public EventCallbackList()
{
m_Array = EmptyArray;
}
public EventCallbackList(EventCallbackList source)
{
m_Count = source.m_Count;
m_Array = new EventCallbackFunctorBase[m_Count];
Array.Copy(source.m_Array, m_Array, m_Count);
}
public bool Contains(long eventTypeId, [NotNull] Delegate callback)
{
return Find(eventTypeId, callback) != null;
}
public EventCallbackFunctorBase Find(long eventTypeId, [NotNull] Delegate callback)
{
for (int i = 0; i < m_Count; i++)
{
if (m_Array[i].IsEquivalentTo(eventTypeId, callback))
{
return m_Array[i];
}
}
return null;
}
public bool Remove(long eventTypeId, [NotNull] Delegate callback, out EventCallbackFunctorBase removedFunctor)
{
for (int i = 0; i < m_Count; i++)
{
if (m_Array[i].IsEquivalentTo(eventTypeId, callback))
{
removedFunctor = m_Array[i];
m_Count--;
Array.Copy(m_Array, i+1, m_Array, i, m_Count-i);
m_Array[m_Count] = default;
return true;
}
}
removedFunctor = null;
return false;
}
public void Add(EventCallbackFunctorBase item)
{
if (m_Count >= m_Array.Length)
Array.Resize(ref m_Array, Mathf.NextPowerOfTwo(m_Count + 4)); // size goes 0, 4, 8, 16, etc.
m_Array[m_Count++] = item;
}
public void AddRange(EventCallbackList list)
{
if (m_Count + list.m_Count > m_Array.Length)
Array.Resize(ref m_Array, Mathf.NextPowerOfTwo(m_Count + list.m_Count));
Array.Copy(list.m_Array, 0, m_Array, m_Count, list.m_Count);
m_Count += list.m_Count;
}
public int Count => m_Count;
public Span<EventCallbackFunctorBase> Span => new Span<EventCallbackFunctorBase>(m_Array, 0, m_Count);
public EventCallbackFunctorBase this[int i]
{
get { return m_Array[i]; }
set { m_Array[i] = value; }
}
public void Clear()
{
Array.Clear(m_Array, 0, m_Count);
m_Count = 0;
}
}
internal class EventCallbackRegistry
{
private static readonly EventCallbackListPool s_ListPool = new EventCallbackListPool();
private static EventCallbackList GetCallbackList(EventCallbackList initializer = null)
{
return s_ListPool.Get(initializer);
}
private static void ReleaseCallbackList(EventCallbackList toRelease)
{
s_ListPool.Release(toRelease);
}
internal struct DynamicCallbackList
{
private TrickleDown m_UseTrickleDown;
[NotNull] private EventCallbackList m_Callbacks;
[CanBeNull] private EventCallbackList m_TemporaryCallbacks;
[CanBeNull] private List<EventCallbackFunctorBase> m_UnregisteredCallbacksDuringInvoke;
private int m_IsInvoking;
public int Count => m_Callbacks.Count;
public static DynamicCallbackList Create(TrickleDown useTrickleDown)
{
return new DynamicCallbackList
{
m_UseTrickleDown = useTrickleDown,
m_Callbacks = EventCallbackList.EmptyList,
m_TemporaryCallbacks = null,
m_UnregisteredCallbacksDuringInvoke = null,
m_IsInvoking = 0
};
}
[NotNull] public EventCallbackList GetCallbackListForWriting()
{
return m_IsInvoking == 0
? (m_Callbacks != EventCallbackList.EmptyList ? m_Callbacks : m_Callbacks = GetCallbackList())
: (m_TemporaryCallbacks ??= GetCallbackList(m_Callbacks));
}
[NotNull] public readonly EventCallbackList GetCallbackListForReading()
{
return m_TemporaryCallbacks ?? m_Callbacks;
}
public bool UnregisterCallback(long eventTypeId, [NotNull] Delegate callback)
{
EventCallbackList callbackList = GetCallbackListForWriting();
if (!callbackList.Remove(eventTypeId, callback, out var functor))
return false;
if (m_IsInvoking > 0)
(m_UnregisteredCallbacksDuringInvoke ??= ListPool<EventCallbackFunctorBase>.Get()).Add(functor);
else
functor.Dispose();
return true;
}
public void Invoke(EventBase evt, BaseVisualElementPanel panel, VisualElement target)
{
BeginInvoke();
try
{
// Some callbacks require an enabled target. For uniformity, we don't update this between calls.
var enabled = !evt.skipDisabledElements || target.enabledInHierarchy;
var eventTypeId = evt.eventTypeId;
foreach (var callback in m_Callbacks.Span)
{
if (callback.eventTypeId == eventTypeId && target.elementPanel == panel &&
(enabled || (callback.invokePolicy & InvokePolicy.IncludeDisabled) != 0))
{
// Unregister once callbacks before invoke so they can be re-registered if needed
if ((callback.invokePolicy & InvokePolicy.Once) != 0)
callback.UnregisterCallback(target, m_UseTrickleDown);
callback.Invoke(evt);
if (evt.isImmediatePropagationStopped)
break;
}
}
}
finally
{
EndInvoke();
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void BeginInvoke()
{
m_IsInvoking++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EndInvoke()
{
m_IsInvoking--;
if (m_IsInvoking == 0)
{
// If callbacks were modified during callback invocation, update them now.
if (m_TemporaryCallbacks != null)
{
if (m_Callbacks != EventCallbackList.EmptyList) ReleaseCallbackList(m_Callbacks);
m_Callbacks = GetCallbackList(m_TemporaryCallbacks);
ReleaseCallbackList(m_TemporaryCallbacks);
m_TemporaryCallbacks = null;
// If callbacks were removed during invocation, their functors can now be safely disposed
if (m_UnregisteredCallbacksDuringInvoke != null)
{
foreach (var functor in m_UnregisteredCallbacksDuringInvoke)
functor.Dispose();
ListPool<EventCallbackFunctorBase>.Release(m_UnregisteredCallbacksDuringInvoke);
m_UnregisteredCallbacksDuringInvoke = null;
}
}
}
}
}
internal DynamicCallbackList m_TrickleDownCallbacks = DynamicCallbackList.Create(TrickleDown.TrickleDown);
internal DynamicCallbackList m_BubbleUpCallbacks = DynamicCallbackList.Create(TrickleDown.NoTrickleDown);
// It's important to always call this with `ref`, otherwise we'll mutate a copy of the struct.
private ref DynamicCallbackList GetDynamicCallbackList(TrickleDown useTrickleDown)
{
return ref useTrickleDown == TrickleDown.TrickleDown ? ref m_TrickleDownCallbacks : ref m_BubbleUpCallbacks;
}
public void RegisterCallback<TEventType>([NotNull] EventCallback<TEventType> callback,
TrickleDown useTrickleDown = TrickleDown.NoTrickleDown, InvokePolicy invokePolicy = default)
where TEventType : EventBase<TEventType>, new()
{
long eventTypeId = EventBase<TEventType>.TypeId();
ref var dynamicCallbackList = ref GetDynamicCallbackList(useTrickleDown);
EventCallbackList callbackList = dynamicCallbackList.GetCallbackListForReading();
if (callbackList.Find(eventTypeId, callback) is EventCallbackFunctor<TEventType> functor)
{
functor.invokePolicy = invokePolicy;
return;
}
callbackList = dynamicCallbackList.GetCallbackListForWriting();
callbackList.Add(EventCallbackFunctor<TEventType>.GetPooled(eventTypeId, callback, invokePolicy));
}
public void RegisterCallback<TEventType, TCallbackArgs>(
[NotNull] EventCallback<TEventType, TCallbackArgs> callback, TCallbackArgs userArgs,
TrickleDown useTrickleDown = TrickleDown.NoTrickleDown, InvokePolicy invokePolicy = default)
where TEventType : EventBase<TEventType>, new()
{
long eventTypeId = EventBase<TEventType>.TypeId();
ref var dynamicCallbackList = ref GetDynamicCallbackList(useTrickleDown);
EventCallbackList callbackList = dynamicCallbackList.GetCallbackListForReading();
if (callbackList.Find(eventTypeId, callback) is EventCallbackFunctor<TEventType, TCallbackArgs> functor)
{
functor.invokePolicy = invokePolicy;
functor.userArgs = userArgs;
return;
}
callbackList = dynamicCallbackList.GetCallbackListForWriting();
callbackList.Add(
EventCallbackFunctor<TEventType, TCallbackArgs>.GetPooled(eventTypeId, callback, userArgs,
invokePolicy));
}
// Return value is used for unit tests only
public bool UnregisterCallback<TEventType>([NotNull] EventCallback<TEventType> callback,
TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new()
{
return GetDynamicCallbackList(useTrickleDown).UnregisterCallback(EventBase<TEventType>.TypeId(), callback);
}
public bool UnregisterCallback<TEventType, TCallbackArgs>(
[NotNull] EventCallback<TEventType, TCallbackArgs> callback,
TrickleDown useTrickleDown = TrickleDown.NoTrickleDown) where TEventType : EventBase<TEventType>, new()
{
return GetDynamicCallbackList(useTrickleDown).UnregisterCallback(EventBase<TEventType>.TypeId(), callback);
}
// For unit tests only
internal void InvokeCallbacks(EventBase evt, PropagationPhase propagationPhase)
{
var target = (VisualElement) evt.currentTarget;
var panel = target.elementPanel;
switch (propagationPhase)
{
case PropagationPhase.TrickleDown:
GetDynamicCallbackList(TrickleDown.TrickleDown).Invoke(evt, panel, target);
break;
case PropagationPhase.BubbleUp:
GetDynamicCallbackList(TrickleDown.NoTrickleDown).Invoke(evt, panel, target);
break;
default:
throw new ArgumentOutOfRangeException(nameof(propagationPhase),
"Propagation phases other than TrickleDown and BubbleUp are not supported");
}
}
public bool HasTrickleDownHandlers()
{
return m_TrickleDownCallbacks.Count > 0;
}
public bool HasBubbleHandlers()
{
return m_BubbleUpCallbacks.Count > 0;
}
}
}
| UnityCsReference/Modules/UIElements/Core/Events/EventCallbackRegistry.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Events/EventCallbackRegistry.cs",
"repo_id": "UnityCsReference",
"token_count": 6819
} | 498 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
static class PointerDeviceState
{
[Flags]
internal enum LocationFlag
{
None = 0,
// The location of the pointer was outside of the panel **when the location was set**. The window may have grown since then.
// We need to know this to avoid elements to become hovered when the window grows, due to an out of date pointer location.
OutsidePanel = 1,
}
private struct PointerLocation
{
// Pointer position in panel space. If Panel is null, position in screen space.
internal Vector2 Position { get; private set; }
// The Panel that handles events for this pointer.
internal IPanel Panel { get; private set; }
internal LocationFlag Flags { get; private set; }
internal void SetLocation(Vector2 position, IPanel panel)
{
Position = position;
Panel = panel;
Flags = LocationFlag.None;
if (panel == null || !panel.visualTree.layout.Contains(position))
{
Flags |= LocationFlag.OutsidePanel;
}
}
}
private static PointerLocation[] s_EditorPointerLocations = new PointerLocation[PointerId.maxPointers];
private static PointerLocation[] s_PlayerPointerLocations = new PointerLocation[PointerId.maxPointers];
private static int[] s_PressedButtons = new int[PointerId.maxPointers];
// When a pointer button is pressed on top of a runtime panel, that panel is flagged as having "soft capture" of that pointer,
// that is, unless an element has an actual pointer capture, pointer move events should stay inside this panel until
// all pointer buttons are released again. This is used by runtime panels to mimic GUIView.cpp window capture behavior.
private static readonly IPanel[] s_PlayerPanelWithSoftPointerCapture = new IPanel[PointerId.maxPointers];
// For test usage
internal static void Reset()
{
for (var i = 0; i < PointerId.maxPointers; i++)
{
s_EditorPointerLocations[i].SetLocation(Vector2.zero, null);
s_PlayerPointerLocations[i].SetLocation(Vector2.zero, null);
s_PressedButtons[i] = 0;
s_PlayerPanelWithSoftPointerCapture[i] = null;
}
}
internal static void RemovePanelData(IPanel panel)
{
for (var i = 0; i < PointerId.maxPointers; i++)
{
if (s_EditorPointerLocations[i].Panel == panel)
s_EditorPointerLocations[i].SetLocation(Vector2.zero, null);
if (s_PlayerPointerLocations[i].Panel == panel)
s_PlayerPointerLocations[i].SetLocation(Vector2.zero, null);
if (s_PlayerPanelWithSoftPointerCapture[i] == panel)
s_PlayerPanelWithSoftPointerCapture[i] = null;
}
}
public static void SavePointerPosition(int pointerId, Vector2 position, IPanel panel, ContextType contextType)
{
switch (contextType)
{
case ContextType.Editor:
default:
s_EditorPointerLocations[pointerId].SetLocation(position, panel);
break;
case ContextType.Player:
s_PlayerPointerLocations[pointerId].SetLocation(position, panel);
break;
}
}
public static void PressButton(int pointerId, int buttonId)
{
Debug.Assert(buttonId >= 0, "PressButton expects buttonId >= 0");
Debug.Assert(buttonId < 32, "PressButton expects buttonId < 32");
s_PressedButtons[pointerId] |= (1 << buttonId);
}
public static void ReleaseButton(int pointerId, int buttonId)
{
Debug.Assert(buttonId >= 0, "ReleaseButton expects buttonId >= 0");
Debug.Assert(buttonId < 32, "ReleaseButton expects buttonId < 32");
s_PressedButtons[pointerId] &= ~(1 << buttonId);
}
public static void ReleaseAllButtons(int pointerId)
{
s_PressedButtons[pointerId] = 0;
}
public static Vector2 GetPointerPosition(int pointerId, ContextType contextType)
{
switch (contextType)
{
case ContextType.Editor:
default:
return s_EditorPointerLocations[pointerId].Position;
case ContextType.Player:
return s_PlayerPointerLocations[pointerId].Position;
}
}
public static IPanel GetPanel(int pointerId, ContextType contextType)
{
switch (contextType)
{
case ContextType.Editor:
default:
return s_EditorPointerLocations[pointerId].Panel;
case ContextType.Player:
return s_PlayerPointerLocations[pointerId].Panel;
}
}
static bool HasFlagFast(LocationFlag flagSet, LocationFlag flag)
{
return (flagSet & flag) == flag;
}
public static bool HasLocationFlag(int pointerId, ContextType contextType, LocationFlag flag)
{
switch (contextType)
{
case ContextType.Editor:
default:
return HasFlagFast(s_EditorPointerLocations[pointerId].Flags, flag);
case ContextType.Player:
return HasFlagFast(s_PlayerPointerLocations[pointerId].Flags, flag);
}
}
public static int GetPressedButtons(int pointerId)
{
return s_PressedButtons[pointerId];
}
internal static bool HasAdditionalPressedButtons(int pointerId, int exceptButtonId)
{
return (s_PressedButtons[pointerId] & ~(1 << exceptButtonId)) != 0;
}
internal static void SetPlayerPanelWithSoftPointerCapture(int pointerId, IPanel panel)
{
s_PlayerPanelWithSoftPointerCapture[pointerId] = panel;
}
internal static IPanel GetPlayerPanelWithSoftPointerCapture(int pointerId)
{
return s_PlayerPanelWithSoftPointerCapture[pointerId];
}
}
}
| UnityCsReference/Modules/UIElements/Core/Events/PointerDeviceState.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Events/PointerDeviceState.cs",
"repo_id": "UnityCsReference",
"token_count": 2995
} | 499 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Text;
namespace UnityEngine.UIElements
{
internal static class UIDocumentHierarchyUtil
{
internal static UIDocumentHierarchicalIndexComparer indexComparer = new UIDocumentHierarchicalIndexComparer();
internal static int FindHierarchicalSortedIndex(SortedDictionary<UIDocumentHierarchicalIndex, UIDocument> children,
UIDocument child)
{
int index = 0;
foreach (var sibling in children.Values)
{
if (sibling == child)
{
return index;
}
if (sibling.rootVisualElement != null && sibling.rootVisualElement.parent != null)
{
index++;
}
}
return index;
}
internal static void SetHierarchicalIndex(Transform childTransform, Transform directParentTransform, Transform mainParentTransform, out UIDocumentHierarchicalIndex hierarchicalIndex)
{
if (mainParentTransform == null || childTransform == null)
{
hierarchicalIndex.pathToParent = null;
return;
}
if (directParentTransform == mainParentTransform)
{
hierarchicalIndex.pathToParent = new int[] { childTransform.GetSiblingIndex() };
}
else
{
List<int> pathToParent = new List<int>();
while (mainParentTransform != childTransform && childTransform != null)
{
pathToParent.Add(childTransform.GetSiblingIndex());
childTransform = childTransform.parent;
}
pathToParent.Reverse();
hierarchicalIndex.pathToParent = pathToParent.ToArray();
}
}
internal static void SetGlobalIndex(Transform objectTransform, Transform directParentTransform, out UIDocumentHierarchicalIndex globalIndex)
{
if (objectTransform == null)
{
globalIndex.pathToParent = null;
return;
}
if (directParentTransform == null)
{
globalIndex.pathToParent = new int[] { objectTransform.GetSiblingIndex() };
}
else
{
List<int> pathToParent = new List<int>() { objectTransform.GetSiblingIndex() };
while (directParentTransform != null)
{
pathToParent.Add(directParentTransform.GetSiblingIndex());
directParentTransform = directParentTransform.parent;
}
pathToParent.Reverse();
globalIndex.pathToParent = pathToParent.ToArray();
}
}
}
internal class UIDocumentHierarchicalIndexComparer : IComparer<UIDocumentHierarchicalIndex>
{
public int Compare(UIDocumentHierarchicalIndex x, UIDocumentHierarchicalIndex y)
{
return x.CompareTo(y);
}
}
internal struct UIDocumentHierarchicalIndex : IComparable<UIDocumentHierarchicalIndex>
{
internal int[] pathToParent;
public int CompareTo(UIDocumentHierarchicalIndex other)
{
// Safety checks
if (pathToParent == null)
{
if (other.pathToParent == null)
{
return 0;
}
return 1;
}
if (other.pathToParent == null) // we know pathToParent != null
{
return -1;
}
int myLength = pathToParent.Length;
int otherLength = other.pathToParent.Length;
for (int i = 0; i < myLength && i < otherLength; ++i)
{
if (pathToParent[i] < other.pathToParent[i])
{
return -1;
}
if (pathToParent[i] > other.pathToParent[i])
{
return 1;
}
}
if (myLength > otherLength)
{
return 1;
}
else if (myLength < otherLength)
{
return -1;
}
return 0;
}
public override string ToString()
{
StringBuilder toString = new StringBuilder("pathToParent = [");
if (pathToParent != null)
{
int count = pathToParent.Length;
for (int i = 0; i < count; ++i)
{
toString.Append(pathToParent[i]);
if (i < count - 1)
{
toString.Append(", ");
}
}
}
toString.Append("]");
return toString.ToString();
}
}
}
| UnityCsReference/Modules/UIElements/Core/GameObjects/UIDocumentHierarchyUtil.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/GameObjects/UIDocumentHierarchyUtil.cs",
"repo_id": "UnityCsReference",
"token_count": 2665
} | 500 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Runtime.InteropServices;
namespace UnityEngine.UIElements.Layout;
/// <summary>
/// A <see cref="LayoutHandle"/> represents a reference to unmanaged memory.
///
/// * The index specifies the data index in the <see cref="LayoutDataStore"/>.
/// * The version is used for tracking lifecycle and re-using indices.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
readonly struct LayoutHandle
{
public static LayoutHandle Undefined => new LayoutHandle();
public readonly int Index;
public readonly int Version;
internal LayoutHandle(int index, int version)
{
Index = index;
Version = version;
}
public bool IsUndefined => this.Equals(Undefined);
public bool Equals(LayoutHandle other)
=> Index == other.Index && Version == other.Version;
public override bool Equals(object obj)
=> obj is LayoutHandle other && Equals(other);
public override int GetHashCode()
{
unchecked
{
return (Index * 397) ^ Version;
}
}
}
| UnityCsReference/Modules/UIElements/Core/Layout/LayoutHandle.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Layout/LayoutHandle.cs",
"repo_id": "UnityCsReference",
"token_count": 400
} | 501 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.UIElements.Layout;
struct LayoutDefaults
{
public static readonly FixedBuffer9<LayoutValue> EdgeValuesUnit = new FixedBuffer9<LayoutValue>
{
[0] = LayoutValue.Undefined(),
[1] = LayoutValue.Undefined(),
[2] = LayoutValue.Undefined(),
[3] = LayoutValue.Undefined(),
[4] = LayoutValue.Undefined(),
[5] = LayoutValue.Undefined(),
[6] = LayoutValue.Undefined(),
[7] = LayoutValue.Undefined(),
[8] = LayoutValue.Undefined(),
};
public static readonly float[] DimensionValues = {float.NaN, float.NaN};
public static readonly FixedBuffer2<LayoutValue> DimensionValuesUnit = new FixedBuffer2<LayoutValue>
{
[0] = LayoutValue.Undefined(),
[1] = LayoutValue.Undefined()
};
public static readonly FixedBuffer2<LayoutValue> DimensionValuesAutoUnit = new FixedBuffer2<LayoutValue>
{
[0] = LayoutValue.Auto(),
[1] = LayoutValue.Auto()
};
}
| UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutDefaults.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutDefaults.cs",
"repo_id": "UnityCsReference",
"token_count": 435
} | 502 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Runtime.InteropServices;
namespace UnityEngine.UIElements.Layout;
[StructLayout(LayoutKind.Sequential)]
struct LayoutValue
{
float value;
LayoutUnit unit;
public LayoutUnit Unit => unit;
public float Value => value;
public static LayoutValue Point(float value)
{
return new LayoutValue
{
value = value,
unit = float.IsNaN(value) ? LayoutUnit.Undefined : LayoutUnit.Point
};
}
public bool Equals(LayoutValue other)
{
return Unit == other.Unit && (Value.Equals(other.Value) || Unit == LayoutUnit.Undefined);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is LayoutValue yogaValue && Equals(yogaValue);
}
public override int GetHashCode()
{
unchecked
{
return (Value.GetHashCode() * 397) ^ (int) Unit;
}
}
public static LayoutValue Undefined()
{
return new LayoutValue
{
value = float.NaN,
unit = LayoutUnit.Undefined
};
}
public static LayoutValue Auto()
{
return new LayoutValue
{
value = float.NaN,
unit = LayoutUnit.Auto
};
}
public static LayoutValue Percent(float value)
{
return new LayoutValue
{
value = value,
unit = float.IsNaN(value) ? LayoutUnit.Undefined : LayoutUnit.Percent
};
}
public static implicit operator LayoutValue(float value)
{
return Point(value);
}
}
static class LayoutValueExtensions
{
public static LayoutValue Percent(this float value)
{
return LayoutValue.Percent(value);
}
public static LayoutValue Pt(this float value)
{
return LayoutValue.Point(value);
}
public static LayoutValue Percent(this int value)
{
return LayoutValue.Percent(value);
}
public static LayoutValue Pt(this int value)
{
return LayoutValue.Point(value);
}
}
| UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutValue.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Layout/Model/LayoutValue.cs",
"repo_id": "UnityCsReference",
"token_count": 918
} | 503 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using Unity.Profiling;
namespace UnityEngine.UIElements
{
// This is the required interface to UIElementsUtility for Runtime game components.
[NativeHeader("Modules/UIElements/Core/Native/UIElementsRuntimeUtilityNative.h")]
[VisibleToOtherModules("Unity.UIElements")]
internal static class UIElementsRuntimeUtilityNative
{
internal static Action UpdatePanelsCallback;
internal static Action<bool> RepaintPanelsCallback;
internal static Action RenderOffscreenPanelsCallback;
[RequiredByNativeCode]
public static void UpdatePanels()
{
UpdatePanelsCallback?.Invoke();
}
[RequiredByNativeCode]
public static void RepaintPanels(bool onlyOffscreen)
{
RepaintPanelsCallback?.Invoke(onlyOffscreen);
}
[RequiredByNativeCode]
public static void RenderOffscreenPanels()
{
RenderOffscreenPanelsCallback?.Invoke();
}
public extern static void RegisterPlayerloopCallback();
public extern static void UnregisterPlayerloopCallback();
public extern static void VisualElementCreation();
}
}
| UnityCsReference/Modules/UIElements/Core/Native/UIElementsUtility.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Native/UIElementsUtility.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 517
} | 504 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.UIElements.UIR;
namespace UnityEngine.UIElements
{
class DynamicAtlasPage : IDisposable
{
public TextureId textureId { get; private set; }
public RenderTexture atlas { get; private set; }
public RenderTextureFormat format { get; }
public FilterMode filterMode { get; }
public Vector2Int minSize { get; }
public Vector2Int maxSize { get; }
public Vector2Int currentSize => m_CurrentSize;
internal Allocator2D allocator => m_Allocator; // For debugging purposes
readonly int m_1Padding = 1;
readonly int m_2Padding = 2;
Allocator2D m_Allocator;
TextureBlitter m_Blitter;
Vector2Int m_CurrentSize;
static int s_TextureCounter;
public DynamicAtlasPage(RenderTextureFormat format, FilterMode filterMode, Vector2Int minSize, Vector2Int maxSize)
{
textureId = TextureRegistry.instance.AllocAndAcquireDynamic();
this.format = format;
this.filterMode = filterMode;
this.minSize = minSize;
this.maxSize = maxSize;
m_Allocator = new Allocator2D(minSize, maxSize, m_2Padding);
m_Blitter = new TextureBlitter(64);
}
#region Dispose Pattern
protected bool disposed { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
if (atlas != null)
{
UIRUtility.Destroy(atlas);
atlas = null;
}
if (m_Allocator != null)
{
// m_Allocator.Dispose(); TODO once we pool content
m_Allocator = null;
}
if (m_Blitter != null)
{
m_Blitter.Dispose();
m_Blitter = null;
}
if (textureId != TextureId.invalid)
{
TextureRegistry.instance.Release(textureId);
textureId = TextureId.invalid;
}
}
else
UnityEngine.UIElements.DisposeHelper.NotifyMissingDispose(this);
disposed = true;
}
#endregion // Dispose Pattern
public bool TryAdd(Texture2D image, out Allocator2D.Alloc2D alloc, out RectInt rect)
{
if (disposed)
{
DisposeHelper.NotifyDisposedUsed(this);
alloc = new Allocator2D.Alloc2D();
rect = new RectInt();
return false;
}
if (!m_Allocator.TryAllocate(image.width + m_2Padding, image.height + m_2Padding, out alloc))
{
rect = new RectInt();
return false;
}
m_CurrentSize.x = Mathf.Max(m_CurrentSize.x, UIRUtility.GetNextPow2(alloc.rect.xMax));
m_CurrentSize.y = Mathf.Max(m_CurrentSize.y, UIRUtility.GetNextPow2(alloc.rect.yMax));
rect = new RectInt(alloc.rect.xMin + m_1Padding, alloc.rect.yMin + m_1Padding, image.width, image.height);
Update(image, rect);
return true;
}
public void Update(Texture2D image, RectInt rect)
{
if (disposed)
{
DisposeHelper.NotifyDisposedUsed(this);
return;
}
Debug.Assert(image != null && rect.width > 0 && rect.height > 0);
m_Blitter.QueueBlit(image, new RectInt(0, 0, image.width, image.height), new Vector2Int(rect.x, rect.y), true, Color.white);
}
public void Remove(Allocator2D.Alloc2D alloc)
{
if (disposed)
{
DisposeHelper.NotifyDisposedUsed(this);
return;
}
Debug.Assert(alloc.rect.width > 0 && alloc.rect.height > 0);
m_Allocator.Free(alloc);
}
public void Commit()
{
if (disposed)
{
DisposeHelper.NotifyDisposedUsed(this);
return;
}
UpdateAtlasTexture();
m_Blitter.Commit(atlas);
}
void UpdateAtlasTexture()
{
if (atlas == null)
{
atlas = CreateAtlasTexture();
return;
}
if (atlas.width != m_CurrentSize.x || atlas.height != m_CurrentSize.y)
{
RenderTexture newAtlas = CreateAtlasTexture();
if (newAtlas == null)
Debug.LogErrorFormat("Failed to allocate a render texture for the dynamic atlas. Current Size = {0}x{1}. Requested Size = {2}x{3}.",
atlas.width, atlas.height, m_CurrentSize.x, m_CurrentSize.y);
else
m_Blitter.BlitOneNow(newAtlas, atlas,
new RectInt(0, 0, atlas.width, atlas.height),
new Vector2Int(0, 0), false, Color.white);
UIRUtility.Destroy(atlas);
atlas = newAtlas;
}
}
RenderTexture CreateAtlasTexture()
{
if (m_CurrentSize.x == 0 || m_CurrentSize.y == 0)
return null;
// The RenderTextureReadWrite setting is purposely omitted in order to get the "Default" behavior.
return new RenderTexture(m_CurrentSize.x, m_CurrentSize.y, 0, format)
{
hideFlags = HideFlags.HideAndDontSave,
name = "UIR Dynamic Atlas Page " + s_TextureCounter++,
filterMode = filterMode
};
}
}
}
| UnityCsReference/Modules/UIElements/Core/Renderer/UIRDynamicAtlasPage.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRDynamicAtlasPage.cs",
"repo_id": "UnityCsReference",
"token_count": 3188
} | 505 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using Unity.Collections;
namespace UnityEngine.UIElements.UIR
{
class NativeList<T> : IDisposable where T : struct
{
NativeArray<T> m_NativeArray;
int m_Count;
public NativeList(int initialCapacity)
{
Debug.Assert(initialCapacity > 0);
m_NativeArray = new NativeArray<T>(initialCapacity, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
}
void Expand(int newLength)
{
var newArray = new NativeArray<T>(newLength, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
var dst = newArray.Slice(0, m_Count);
dst.CopyFrom(m_NativeArray);
m_NativeArray.Dispose();
m_NativeArray = newArray;
}
public void Add(ref T data)
{
if (m_Count == m_NativeArray.Length)
Expand(m_NativeArray.Length << 1);
m_NativeArray[m_Count++] = data;
}
public void Add(NativeSlice<T> src)
{
int required = m_Count + src.Length;
if (m_NativeArray.Length < required)
Expand(required << 1);
var dst = m_NativeArray.Slice(m_Count, src.Length);
dst.CopyFrom(src);
m_Count += src.Length;
}
public void Clear()
{
m_Count = 0;
}
public NativeSlice<T> GetSlice(int start, int length)
{
return m_NativeArray.Slice(start, length);
}
public int Count => m_Count;
#region Dispose Pattern
protected bool disposed { get; private set; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
m_NativeArray.Dispose();
}
else DisposeHelper.NotifyMissingDispose(this);
disposed = true;
}
#endregion // Dispose Pattern
}
}
| UnityCsReference/Modules/UIElements/Core/Renderer/UIRNativeList.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRNativeList.cs",
"repo_id": "UnityCsReference",
"token_count": 1111
} | 506 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using Unity.Collections;
namespace UnityEngine.UIElements.UIR
{
internal enum OwnedState : byte
{
Inherited = 0,
Owned = 1,
}
internal struct BMPAlloc
{
public static readonly BMPAlloc Invalid = new BMPAlloc() { page = -1 };
public bool Equals(BMPAlloc other) { return page == other.page && pageLine == other.pageLine && bitIndex == other.bitIndex; }
public bool IsValid() { return page >= 0; }
public override string ToString() { return string.Format("{0},{1},{2}", page, pageLine, bitIndex); }
public int page;
public ushort pageLine;
public byte bitIndex;
public OwnedState ownedState;
}
// The BitmapAllocator32 always scans for allocations from the first page and upwards.
// Thus if a returned allocation is at a certain location, it is guaranteed that all preceding
// locations are occupied. This property is relied on in UIRVEShaderInfoAllocator below to report
// OOM when the allocation returned exceeds the allowed constant buffer size but fits in a BMPAlloc page.
// This allocator is not multi-threading safe.
internal struct BitmapAllocator32
{
struct Page
{
public UInt16 x, y; // Location of this page in the atlas. These coordinates are the top-left corner of the page.
public int freeSlots;
}
// Bits represented in lines of 32-bit ints
public const int kPageWidth = 32; // Must match bit count of the type of m_AllocMap
int m_PageHeight;
List<Page> m_Pages;
List<UInt32> m_AllocMap; // Each page takes kPageHeight sequential entries/lines in this array, 0 is allocated, 1 is available
int m_EntryWidth, m_EntryHeight;
public void Construct(int pageHeight, int entryWidth = 1, int entryHeight = 1)
{
m_PageHeight = pageHeight;
m_Pages = new List<Page>(1);
m_AllocMap = new List<UInt32>(m_PageHeight * m_Pages.Capacity);
m_EntryWidth = entryWidth;
m_EntryHeight = entryHeight;
}
public void ForceFirstAlloc(ushort firstPageX, ushort firstPageY)
{
m_AllocMap.Add(0xFFFFFFFE); // Reserve first slot
for (int i = 1; i < m_PageHeight; i++)
m_AllocMap.Add(0xFFFFFFFF);
m_Pages.Add(new Page() { x = firstPageX, y = firstPageY, freeSlots = kPageWidth * m_PageHeight - 1 });
}
public BMPAlloc Allocate(BaseShaderInfoStorage storage)
{
int pageCount = m_Pages.Count;
for (int pageIndex = 0; pageIndex < pageCount; pageIndex++)
{
var pageInfo = m_Pages[pageIndex];
if (pageInfo.freeSlots == 0)
continue;
int line = pageIndex * m_PageHeight;
int endLine = line + m_PageHeight;
for (; line < endLine; line++)
{
var allocBits = m_AllocMap[line];
if (allocBits == 0)
continue;
byte allocIndex = CountTrailingZeroes(allocBits);
m_AllocMap[line] = allocBits & (~(1U << allocIndex));
pageInfo.freeSlots--;
m_Pages[pageIndex] = pageInfo;
return new BMPAlloc() { page = pageIndex, pageLine = (ushort)(line - pageIndex * m_PageHeight), bitIndex = allocIndex, ownedState = OwnedState.Owned };
} // For each line
} // For each page
RectInt uvRect;
if ((storage == null) || !storage.AllocateRect(kPageWidth * m_EntryWidth, m_PageHeight * m_EntryHeight, out uvRect))
return BMPAlloc.Invalid;
m_AllocMap.Capacity += m_PageHeight;
m_AllocMap.Add(0xFFFFFFFE); // Reserve first slot
for (int i = 1; i < m_PageHeight; i++)
m_AllocMap.Add(0xFFFFFFFF);
m_Pages.Add(new Page() { x = (UInt16)uvRect.xMin, y = (UInt16)uvRect.yMin, freeSlots = kPageWidth * m_PageHeight - 1 });
return new BMPAlloc() { page = m_Pages.Count - 1, ownedState = OwnedState.Owned };
}
public void Free(BMPAlloc alloc)
{
Debug.Assert(alloc.ownedState == OwnedState.Owned);
int line = alloc.page * m_PageHeight + alloc.pageLine;
m_AllocMap[line] = m_AllocMap[line] | (1U << alloc.bitIndex);
var page = m_Pages[alloc.page];
page.freeSlots++;
m_Pages[alloc.page] = page;
}
public int entryWidth { get { return m_EntryWidth; } }
public int entryHeight { get { return m_EntryHeight; } }
internal void GetAllocPageAtlasLocation(int page, out UInt16 x, out UInt16 y) { var p = m_Pages[page]; x = p.x; y = p.y; }
static byte CountTrailingZeroes(UInt32 val)
{
// This entire function is implemented on hardware in one instruction... sigh
byte trailingZeroes = 0;
if ((val & 0xFFFF) == 0)
{
val >>= 16;
trailingZeroes = 16;
}
if ((val & 0xFF) == 0)
{
val >>= 8;
trailingZeroes += 8;
}
if ((val & 0xF) == 0)
{
val >>= 4;
trailingZeroes += 4;
}
if ((val & 3) == 0)
{
val >>= 2;
trailingZeroes += 2;
}
if ((val & 1) == 0)
trailingZeroes += 1;
return trailingZeroes;
}
}
internal struct UIRVEShaderInfoAllocator
{
BaseShaderInfoStorage m_Storage;
BitmapAllocator32 m_TransformAllocator, m_ClipRectAllocator, m_OpacityAllocator, m_ColorAllocator, m_TextSettingsAllocator; // All allocators take pages from the same storage
bool m_StorageReallyCreated;
static int pageWidth { get { return BitmapAllocator32.kPageWidth; } }
static int pageHeight { get { return 8; } } // 32*8 = 256, can be stored in a byte
// The page coordinates correspond to the atlas's internal algorithm's results.
// If that algorithm changes, the new results must be put here to match
internal static readonly Vector2Int identityTransformTexel = new Vector2Int(0, 0);
internal static readonly Vector2Int infiniteClipRectTexel = new Vector2Int(0, 32);
internal static readonly Vector2Int fullOpacityTexel = new Vector2Int(32, 32);
internal static readonly Vector2Int clearColorTexel = new Vector2Int(0, 40);
internal static readonly Vector2Int defaultTextCoreSettingsTexel = new Vector2Int(32, 0);
internal static readonly Matrix4x4 identityTransformValue = Matrix4x4.identity;
internal static readonly Vector4 identityTransformRow0Value = identityTransformValue.GetRow(0);
internal static readonly Vector4 identityTransformRow1Value = identityTransformValue.GetRow(1);
internal static readonly Vector4 identityTransformRow2Value = identityTransformValue.GetRow(2);
internal static readonly Vector4 infiniteClipRectValue = new Vector4(0, 0, 0, 0);
internal static readonly Vector4 fullOpacityValue = new Vector4(1, 1, 1, 1);
internal static readonly Vector4 clearColorValue = new Vector4(0, 0, 0, 0);
internal static readonly TextCoreSettings defaultTextCoreSettingsValue = new TextCoreSettings() {
faceColor = Color.white,
outlineColor = Color.clear,
outlineWidth = 0.0f,
underlayColor = Color.clear,
underlayOffset = Vector2.zero,
underlaySoftness = 0.0f
};
// Default allocations. All their members are 0 including "owned"
#pragma warning disable 649
public static readonly BMPAlloc identityTransform, infiniteClipRect, fullOpacity, clearColor, defaultTextCoreSettings;
#pragma warning restore 649
static Vector2Int AllocToTexelCoord(ref BitmapAllocator32 allocator, BMPAlloc alloc)
{
UInt16 x, y;
allocator.GetAllocPageAtlasLocation(alloc.page, out x, out y);
return new Vector2Int(
alloc.bitIndex * allocator.entryWidth + x,
alloc.pageLine * allocator.entryHeight + y);
}
static bool AtlasRectMatchesPage(ref BitmapAllocator32 allocator, BMPAlloc defAlloc, RectInt atlasRect)
{
UInt16 x, y;
allocator.GetAllocPageAtlasLocation(defAlloc.page, out x, out y);
return (x == atlasRect.xMin) && (y == atlasRect.yMin) &&
(allocator.entryWidth * pageWidth == atlasRect.width) &&
(allocator.entryHeight * pageHeight == atlasRect.height);
}
public Texture atlas
{
get
{
if (m_StorageReallyCreated)
return m_Storage.texture;
return UIRenderDevice.defaultShaderInfoTexFloat;
}
}
public bool internalAtlasCreated { get { return m_StorageReallyCreated; } } // For diagnostics really
public void Construct()
{
// The default allocs refer to four startup pages to be allocated as below from the atlas
// once the atlas is used for the first time. The page coordinates correspond to the atlas's
// internal algorithm's results. If that algorithm changes, the new results must be put here to match
m_OpacityAllocator = m_ColorAllocator = m_ClipRectAllocator = m_TransformAllocator = m_TextSettingsAllocator = new BitmapAllocator32();
m_TransformAllocator.Construct(pageHeight, 1, 3);
m_TransformAllocator.ForceFirstAlloc((ushort)identityTransformTexel.x, (ushort)identityTransformTexel.y);
m_ClipRectAllocator.Construct(pageHeight);
m_ClipRectAllocator.ForceFirstAlloc((ushort)infiniteClipRectTexel.x, (ushort)infiniteClipRectTexel.y);
m_OpacityAllocator.Construct(pageHeight);
m_OpacityAllocator.ForceFirstAlloc((ushort)fullOpacityTexel.x, (ushort)fullOpacityTexel.y);
m_ColorAllocator.Construct(pageHeight);
m_ColorAllocator.ForceFirstAlloc((ushort)clearColorTexel.x, (ushort)clearColorTexel.y);
m_TextSettingsAllocator.Construct(pageHeight, 1, 4);
m_TextSettingsAllocator.ForceFirstAlloc((ushort)defaultTextCoreSettingsTexel.x, (ushort)defaultTextCoreSettingsTexel.y);
}
void ReallyCreateStorage()
{
// Because we want predictable placement of first pages, 64 will fit all default allocs
m_Storage = new ShaderInfoStorageRGBAFloat(64);
// The order of allocation from the atlas below is important. See the comment at the beginning of Construct().
RectInt rcTransform, rcClipRect, rcOpacity, rcColor, rcTextCoreSettings;
m_Storage.AllocateRect(pageWidth * m_TransformAllocator.entryWidth, pageHeight * m_TransformAllocator.entryHeight, out rcTransform);
m_Storage.AllocateRect(pageWidth * m_ClipRectAllocator.entryWidth, pageHeight * m_ClipRectAllocator.entryHeight, out rcClipRect);
m_Storage.AllocateRect(pageWidth * m_OpacityAllocator.entryWidth, pageHeight * m_OpacityAllocator.entryHeight, out rcOpacity);
m_Storage.AllocateRect(pageWidth * m_ColorAllocator.entryWidth, pageHeight * m_ColorAllocator.entryHeight, out rcColor);
m_Storage.AllocateRect(pageWidth * m_TextSettingsAllocator.entryWidth, pageHeight * m_TextSettingsAllocator.entryHeight, out rcTextCoreSettings);
if (!AtlasRectMatchesPage(ref m_TransformAllocator, identityTransform, rcTransform))
throw new Exception("Atlas identity transform allocation failed unexpectedly");
if (!AtlasRectMatchesPage(ref m_ClipRectAllocator, infiniteClipRect, rcClipRect))
throw new Exception("Atlas infinite clip rect allocation failed unexpectedly");
if (!AtlasRectMatchesPage(ref m_OpacityAllocator, fullOpacity, rcOpacity))
throw new Exception("Atlas full opacity allocation failed unexpectedly");
if (!AtlasRectMatchesPage(ref m_ColorAllocator, clearColor, rcColor))
throw new Exception("Atlas clear color allocation failed unexpectedly");
if (!AtlasRectMatchesPage(ref m_TextSettingsAllocator, defaultTextCoreSettings, rcTextCoreSettings))
throw new Exception("Atlas text setting allocation failed unexpectedly");
SetTransformValue(identityTransform, identityTransformValue);
SetClipRectValue(infiniteClipRect, infiniteClipRectValue);
SetOpacityValue(fullOpacity, fullOpacityValue.w);
SetColorValue(clearColor, clearColorValue, false); // color is saturated, no need to check the colorspace
SetTextCoreSettingValue(defaultTextCoreSettings, defaultTextCoreSettingsValue, false); // colors are saturated, no need to check the colorspace
m_StorageReallyCreated = true;
}
public void Dispose()
{
if (m_Storage != null)
m_Storage.Dispose();
m_Storage = null;
m_StorageReallyCreated = false;
}
public void IssuePendingStorageChanges()
{
m_Storage?.UpdateTexture();
}
public BMPAlloc AllocTransform()
{
if (!m_StorageReallyCreated)
ReallyCreateStorage();
return m_TransformAllocator.Allocate(m_Storage);
}
public BMPAlloc AllocClipRect()
{
if (!m_StorageReallyCreated)
ReallyCreateStorage();
return m_ClipRectAllocator.Allocate(m_Storage);
}
public BMPAlloc AllocOpacity()
{
if (!m_StorageReallyCreated)
ReallyCreateStorage();
return m_OpacityAllocator.Allocate(m_Storage);
}
public BMPAlloc AllocColor()
{
if (!m_StorageReallyCreated)
ReallyCreateStorage();
return m_ColorAllocator.Allocate(m_Storage);
}
public BMPAlloc AllocTextCoreSettings(TextCoreSettings settings)
{
if (!m_StorageReallyCreated)
ReallyCreateStorage();
return m_TextSettingsAllocator.Allocate(m_Storage);
}
public void SetTransformValue(BMPAlloc alloc, Matrix4x4 xform)
{
Debug.Assert(alloc.IsValid());
var allocXY = AllocToTexelCoord(ref m_TransformAllocator, alloc);
m_Storage.SetTexel(allocXY.x, allocXY.y + 0, xform.GetRow(0));
m_Storage.SetTexel(allocXY.x, allocXY.y + 1, xform.GetRow(1));
m_Storage.SetTexel(allocXY.x, allocXY.y + 2, xform.GetRow(2));
}
public void SetClipRectValue(BMPAlloc alloc, Vector4 clipRect)
{
Debug.Assert(alloc.IsValid());
var allocXY = AllocToTexelCoord(ref m_ClipRectAllocator, alloc);
m_Storage.SetTexel(allocXY.x, allocXY.y, clipRect);
}
public void SetOpacityValue(BMPAlloc alloc, float opacity)
{
Debug.Assert(alloc.IsValid());
var allocXY = AllocToTexelCoord(ref m_OpacityAllocator, alloc);
m_Storage.SetTexel(allocXY.x, allocXY.y, new Color(1, 1, 1, opacity));
}
public void SetColorValue(BMPAlloc alloc, Color color, bool isEditorContext)
{
Debug.Assert(alloc.IsValid());
var allocXY = AllocToTexelCoord(ref m_ColorAllocator, alloc);
if(QualitySettings.activeColorSpace == ColorSpace.Linear && !isEditorContext)
m_Storage.SetTexel(allocXY.x, allocXY.y, color.linear);
else
m_Storage.SetTexel(allocXY.x, allocXY.y, color);
}
public void SetTextCoreSettingValue(BMPAlloc alloc, TextCoreSettings settings, bool isEditorContext)
{
Debug.Assert(alloc.IsValid());
var allocXY = AllocToTexelCoord(ref m_TextSettingsAllocator, alloc);
var settingValues = new Color(-settings.underlayOffset.x, settings.underlayOffset.y, settings.underlaySoftness, settings.outlineWidth);
if (QualitySettings.activeColorSpace == ColorSpace.Linear && !isEditorContext)
{
m_Storage.SetTexel(allocXY.x, allocXY.y + 0, settings.faceColor.linear);
m_Storage.SetTexel(allocXY.x, allocXY.y + 1, settings.outlineColor.linear);
m_Storage.SetTexel(allocXY.x, allocXY.y + 2, settings.underlayColor.linear);
}
else
{
m_Storage.SetTexel(allocXY.x, allocXY.y + 0, settings.faceColor);
m_Storage.SetTexel(allocXY.x, allocXY.y + 1, settings.outlineColor);
m_Storage.SetTexel(allocXY.x, allocXY.y + 2, settings.underlayColor);
}
m_Storage.SetTexel(allocXY.x, allocXY.y + 3, settingValues);
}
public void FreeTransform(BMPAlloc alloc)
{
Debug.Assert(alloc.IsValid());
m_TransformAllocator.Free(alloc);
}
public void FreeClipRect(BMPAlloc alloc)
{
Debug.Assert(alloc.IsValid());
m_ClipRectAllocator.Free(alloc);
}
public void FreeOpacity(BMPAlloc alloc)
{
Debug.Assert(alloc.IsValid());
m_OpacityAllocator.Free(alloc);
}
public void FreeColor(BMPAlloc alloc)
{
Debug.Assert(alloc.IsValid());
m_ColorAllocator.Free(alloc);
}
public void FreeTextCoreSettings(BMPAlloc alloc)
{
Debug.Assert(alloc.IsValid());
m_TextSettingsAllocator.Free(alloc);
}
public Color32 TransformAllocToVertexData(BMPAlloc alloc)
{
Debug.Assert(pageWidth == 32 && pageHeight == 8); // Match the bit-shift values below for fast integer division
UInt16 x = 0, y = 0;
m_TransformAllocator.GetAllocPageAtlasLocation(alloc.page, out x, out y);
return new Color32((byte)(x >> 5), (byte)(y >> 3), (byte)(alloc.pageLine * pageWidth + alloc.bitIndex), 0);
}
public Color32 ClipRectAllocToVertexData(BMPAlloc alloc)
{
Debug.Assert(pageWidth == 32 && pageHeight == 8); // Match the bit-shift values below for fast integer division
UInt16 x = 0, y = 0;
m_ClipRectAllocator.GetAllocPageAtlasLocation(alloc.page, out x, out y);
return new Color32((byte)(x >> 5), (byte)(y >> 3), (byte)(alloc.pageLine * pageWidth + alloc.bitIndex), 0);
}
public Color32 OpacityAllocToVertexData(BMPAlloc alloc)
{
Debug.Assert(pageWidth == 32 && pageHeight == 8); // Match the bit-shift values below for fast integer division
UInt16 x, y;
m_OpacityAllocator.GetAllocPageAtlasLocation(alloc.page, out x, out y);
return new Color32((byte)(x >> 5), (byte)(y >> 3), (byte)(alloc.pageLine * pageWidth + alloc.bitIndex), 0);
}
public Color32 ColorAllocToVertexData(BMPAlloc alloc)
{
Debug.Assert(pageWidth == 32 && pageHeight == 8); // Match the bit-shift values below for fast integer division
UInt16 x, y;
m_ColorAllocator.GetAllocPageAtlasLocation(alloc.page, out x, out y);
return new Color32((byte)(x >> 5), (byte)(y >> 3), (byte)(alloc.pageLine * pageWidth + alloc.bitIndex), 0);
}
public Color32 TextCoreSettingsToVertexData(BMPAlloc alloc)
{
Debug.Assert(pageWidth == 32 && pageHeight == 8); // Match the bit-shift values below for fast integer division
UInt16 x, y;
m_TextSettingsAllocator.GetAllocPageAtlasLocation(alloc.page, out x, out y);
return new Color32((byte)(x >> 5), (byte)(y >> 3), (byte)(alloc.pageLine * pageWidth + alloc.bitIndex), 0);
}
}
}
| UnityCsReference/Modules/UIElements/Core/Renderer/UIRVEShaderInfoAllocator.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Renderer/UIRVEShaderInfoAllocator.cs",
"repo_id": "UnityCsReference",
"token_count": 8976
} | 507 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Properties;
namespace UnityEngine.UIElements
{
public partial struct EasingFunction
{
internal class PropertyBag : ContainerPropertyBag<EasingFunction>
{
class ModeProperty : Property<EasingFunction, EasingMode>
{
public override string Name { get; } = nameof(mode);
public override bool IsReadOnly { get; } = false;
public override EasingMode GetValue(ref EasingFunction container) => container.mode;
public override void SetValue(ref EasingFunction container, EasingMode value) => container.mode = value;
}
public PropertyBag()
{
AddProperty(new ModeProperty());
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/EasingFunction.PropertyBag.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/EasingFunction.PropertyBag.cs",
"repo_id": "UnityCsReference",
"token_count": 379
} | 508 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
/******************************************************************************/
//
// DO NOT MODIFY
// This file has been generated by the UIElementsGenerator tool
// See VisualElementStylePropertiesCsGenerator class for details
//
/******************************************************************************/
namespace UnityEngine.UIElements
{
public partial class VisualElement
{
[UnityEngine.Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static partial class StyleProperties
{
internal static readonly BindingId alignContentProperty = "style." + nameof(IStyle.alignContent);
internal static readonly BindingId alignItemsProperty = "style." + nameof(IStyle.alignItems);
internal static readonly BindingId alignSelfProperty = "style." + nameof(IStyle.alignSelf);
internal static readonly BindingId backgroundColorProperty = "style." + nameof(IStyle.backgroundColor);
internal static readonly BindingId backgroundImageProperty = "style." + nameof(IStyle.backgroundImage);
internal static readonly BindingId backgroundPositionXProperty = "style." + nameof(IStyle.backgroundPositionX);
internal static readonly BindingId backgroundPositionYProperty = "style." + nameof(IStyle.backgroundPositionY);
internal static readonly BindingId backgroundRepeatProperty = "style." + nameof(IStyle.backgroundRepeat);
internal static readonly BindingId backgroundSizeProperty = "style." + nameof(IStyle.backgroundSize);
internal static readonly BindingId borderBottomColorProperty = "style." + nameof(IStyle.borderBottomColor);
internal static readonly BindingId borderBottomLeftRadiusProperty = "style." + nameof(IStyle.borderBottomLeftRadius);
internal static readonly BindingId borderBottomRightRadiusProperty = "style." + nameof(IStyle.borderBottomRightRadius);
internal static readonly BindingId borderBottomWidthProperty = "style." + nameof(IStyle.borderBottomWidth);
internal static readonly BindingId borderLeftColorProperty = "style." + nameof(IStyle.borderLeftColor);
internal static readonly BindingId borderLeftWidthProperty = "style." + nameof(IStyle.borderLeftWidth);
internal static readonly BindingId borderRightColorProperty = "style." + nameof(IStyle.borderRightColor);
internal static readonly BindingId borderRightWidthProperty = "style." + nameof(IStyle.borderRightWidth);
internal static readonly BindingId borderTopColorProperty = "style." + nameof(IStyle.borderTopColor);
internal static readonly BindingId borderTopLeftRadiusProperty = "style." + nameof(IStyle.borderTopLeftRadius);
internal static readonly BindingId borderTopRightRadiusProperty = "style." + nameof(IStyle.borderTopRightRadius);
internal static readonly BindingId borderTopWidthProperty = "style." + nameof(IStyle.borderTopWidth);
internal static readonly BindingId bottomProperty = "style." + nameof(IStyle.bottom);
internal static readonly BindingId colorProperty = "style." + nameof(IStyle.color);
internal static readonly BindingId cursorProperty = "style." + nameof(IStyle.cursor);
internal static readonly BindingId displayProperty = "style." + nameof(IStyle.display);
internal static readonly BindingId flexBasisProperty = "style." + nameof(IStyle.flexBasis);
internal static readonly BindingId flexDirectionProperty = "style." + nameof(IStyle.flexDirection);
internal static readonly BindingId flexGrowProperty = "style." + nameof(IStyle.flexGrow);
internal static readonly BindingId flexShrinkProperty = "style." + nameof(IStyle.flexShrink);
internal static readonly BindingId flexWrapProperty = "style." + nameof(IStyle.flexWrap);
internal static readonly BindingId fontSizeProperty = "style." + nameof(IStyle.fontSize);
internal static readonly BindingId heightProperty = "style." + nameof(IStyle.height);
internal static readonly BindingId justifyContentProperty = "style." + nameof(IStyle.justifyContent);
internal static readonly BindingId leftProperty = "style." + nameof(IStyle.left);
internal static readonly BindingId letterSpacingProperty = "style." + nameof(IStyle.letterSpacing);
internal static readonly BindingId marginBottomProperty = "style." + nameof(IStyle.marginBottom);
internal static readonly BindingId marginLeftProperty = "style." + nameof(IStyle.marginLeft);
internal static readonly BindingId marginRightProperty = "style." + nameof(IStyle.marginRight);
internal static readonly BindingId marginTopProperty = "style." + nameof(IStyle.marginTop);
internal static readonly BindingId maxHeightProperty = "style." + nameof(IStyle.maxHeight);
internal static readonly BindingId maxWidthProperty = "style." + nameof(IStyle.maxWidth);
internal static readonly BindingId minHeightProperty = "style." + nameof(IStyle.minHeight);
internal static readonly BindingId minWidthProperty = "style." + nameof(IStyle.minWidth);
internal static readonly BindingId opacityProperty = "style." + nameof(IStyle.opacity);
internal static readonly BindingId overflowProperty = "style." + nameof(IStyle.overflow);
internal static readonly BindingId paddingBottomProperty = "style." + nameof(IStyle.paddingBottom);
internal static readonly BindingId paddingLeftProperty = "style." + nameof(IStyle.paddingLeft);
internal static readonly BindingId paddingRightProperty = "style." + nameof(IStyle.paddingRight);
internal static readonly BindingId paddingTopProperty = "style." + nameof(IStyle.paddingTop);
internal static readonly BindingId positionProperty = "style." + nameof(IStyle.position);
internal static readonly BindingId rightProperty = "style." + nameof(IStyle.right);
internal static readonly BindingId rotateProperty = "style." + nameof(IStyle.rotate);
internal static readonly BindingId scaleProperty = "style." + nameof(IStyle.scale);
internal static readonly BindingId textOverflowProperty = "style." + nameof(IStyle.textOverflow);
internal static readonly BindingId textShadowProperty = "style." + nameof(IStyle.textShadow);
internal static readonly BindingId topProperty = "style." + nameof(IStyle.top);
internal static readonly BindingId transformOriginProperty = "style." + nameof(IStyle.transformOrigin);
[UnityEngine.Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static readonly BindingId transitionDelayProperty = "style." + nameof(IStyle.transitionDelay);
[UnityEngine.Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static readonly BindingId transitionDurationProperty = "style." + nameof(IStyle.transitionDuration);
[UnityEngine.Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static readonly BindingId transitionPropertyProperty = "style." + nameof(IStyle.transitionProperty);
[UnityEngine.Bindings.VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static readonly BindingId transitionTimingFunctionProperty = "style." + nameof(IStyle.transitionTimingFunction);
internal static readonly BindingId translateProperty = "style." + nameof(IStyle.translate);
internal static readonly BindingId unityBackgroundImageTintColorProperty = "style." + nameof(IStyle.unityBackgroundImageTintColor);
internal static readonly BindingId unityFontProperty = "style." + nameof(IStyle.unityFont);
internal static readonly BindingId unityFontDefinitionProperty = "style." + nameof(IStyle.unityFontDefinition);
internal static readonly BindingId unityFontStyleAndWeightProperty = "style." + nameof(IStyle.unityFontStyleAndWeight);
internal static readonly BindingId unityOverflowClipBoxProperty = "style." + nameof(IStyle.unityOverflowClipBox);
internal static readonly BindingId unityParagraphSpacingProperty = "style." + nameof(IStyle.unityParagraphSpacing);
internal static readonly BindingId unitySliceBottomProperty = "style." + nameof(IStyle.unitySliceBottom);
internal static readonly BindingId unitySliceLeftProperty = "style." + nameof(IStyle.unitySliceLeft);
internal static readonly BindingId unitySliceRightProperty = "style." + nameof(IStyle.unitySliceRight);
internal static readonly BindingId unitySliceScaleProperty = "style." + nameof(IStyle.unitySliceScale);
internal static readonly BindingId unitySliceTopProperty = "style." + nameof(IStyle.unitySliceTop);
internal static readonly BindingId unityTextAlignProperty = "style." + nameof(IStyle.unityTextAlign);
internal static readonly BindingId unityTextGeneratorProperty = "style." + nameof(IStyle.unityTextGenerator);
internal static readonly BindingId unityTextOutlineColorProperty = "style." + nameof(IStyle.unityTextOutlineColor);
internal static readonly BindingId unityTextOutlineWidthProperty = "style." + nameof(IStyle.unityTextOutlineWidth);
internal static readonly BindingId unityTextOverflowPositionProperty = "style." + nameof(IStyle.unityTextOverflowPosition);
internal static readonly BindingId visibilityProperty = "style." + nameof(IStyle.visibility);
internal static readonly BindingId whiteSpaceProperty = "style." + nameof(IStyle.whiteSpace);
internal static readonly BindingId widthProperty = "style." + nameof(IStyle.width);
internal static readonly BindingId wordSpacingProperty = "style." + nameof(IStyle.wordSpacing);
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/Generated/StyleProperties.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/Generated/StyleProperties.cs",
"repo_id": "UnityCsReference",
"token_count": 3465
} | 509 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
/// <summary>
/// Style value that can be either a <see cref="Background"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public struct StyleBackground : IStyleValue<Background>, IEquatable<StyleBackground>
{
/// <summary>
/// The <see cref="Background"/> value.
/// </summary>
public Background value
{
get { return m_Keyword == StyleKeyword.Undefined ? m_Value : new Background(); }
set
{
m_Value = value;
m_Keyword = StyleKeyword.Undefined;
}
}
/// <summary>
/// The style keyword.
/// </summary>
public StyleKeyword keyword
{
get { return m_Keyword; }
set { m_Keyword = value; }
}
/// <summary>
/// Creates from either a <see cref="Background"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleBackground(Background v)
: this(v, StyleKeyword.Undefined)
{}
/// <summary>
/// Creates from either a <see cref="Background"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleBackground(Texture2D v)
: this(v, StyleKeyword.Undefined)
{}
/// <summary>
/// Creates from either a <see cref="Background"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleBackground(Sprite v)
: this(v, StyleKeyword.Undefined)
{}
/// <summary>
/// Creates from either a <see cref="Background"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleBackground(VectorImage v)
: this(v, StyleKeyword.Undefined)
{}
/// <summary>
/// Creates from either a <see cref="Background"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleBackground(StyleKeyword keyword)
: this(new Background(), keyword)
{}
internal StyleBackground(Texture2D v, StyleKeyword keyword)
: this(Background.FromTexture2D(v), keyword)
{}
internal StyleBackground(Sprite v, StyleKeyword keyword)
: this(Background.FromSprite(v), keyword)
{}
internal StyleBackground(VectorImage v, StyleKeyword keyword)
: this(Background.FromVectorImage(v), keyword)
{}
internal StyleBackground(Background v, StyleKeyword keyword)
{
m_Keyword = keyword;
m_Value = v;
}
private Background m_Value;
private StyleKeyword m_Keyword;
/// <undoc/>
public static bool operator==(StyleBackground lhs, StyleBackground rhs)
{
return lhs.m_Keyword == rhs.m_Keyword && lhs.m_Value == rhs.m_Value;
}
/// <undoc/>
public static bool operator!=(StyleBackground lhs, StyleBackground rhs)
{
return !(lhs == rhs);
}
/// <undoc/>
public static implicit operator StyleBackground(StyleKeyword keyword)
{
return new StyleBackground(keyword);
}
/// <undoc/>
public static implicit operator StyleBackground(Background v)
{
return new StyleBackground(v);
}
/// <undoc/>
public static implicit operator StyleBackground(Texture2D v)
{
return new StyleBackground(v);
}
/// <undoc/>
public bool Equals(StyleBackground other)
{
return other == this;
}
/// <undoc/>
public override bool Equals(object obj)
{
return obj is StyleBackground other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return (m_Value.GetHashCode() * 397) ^ (int)m_Keyword;
}
}
public override string ToString()
{
return this.DebugString();
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/StyleBackground.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/StyleBackground.cs",
"repo_id": "UnityCsReference",
"token_count": 1931
} | 510 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.UIElements
{
/// <summary>
/// Represents a style value that can be either a <see cref="Rotate"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public struct StyleRotate : IStyleValue<Rotate>, IEquatable<StyleRotate>
{
/// <summary>
/// The <see cref="Rotate"/> value.
/// </summary>
public Rotate value
{
get
{
// SD: Changed to provide an interpretation of Initial and Null for the debugger, that takes the StyleRotate and need to display some value in the fields.
// This is probably subject to change in the future.
return m_Keyword switch
{
StyleKeyword.Undefined => m_Value,
StyleKeyword.Null => Rotate.None(),
StyleKeyword.None => Rotate.None(),
StyleKeyword.Initial => Rotate.Initial(),
_ => throw new NotImplementedException(),
};
}
set
{
m_Value = value;
m_Keyword = StyleKeyword.Undefined;
}
}
/// <summary>
/// The style keyword.
/// </summary>
public StyleKeyword keyword
{
get { return m_Keyword; }
set { m_Keyword = value; }
}
/// <summary>
/// Creates a StyleRotate from either a <see cref="Rotate"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleRotate(Rotate v)
: this(v, StyleKeyword.Undefined)
{}
/// <summary>
/// Creates a StyleRotate from either a <see cref="Rotate"/> or a <see cref="StyleKeyword"/>.
/// </summary>
public StyleRotate(StyleKeyword keyword)
: this(default(Rotate), keyword)
{}
internal StyleRotate(Rotate v, StyleKeyword keyword)
{
m_Keyword = keyword;
m_Value = v;
}
private Rotate m_Value;
private StyleKeyword m_Keyword;
/// <undoc/>
public static bool operator==(StyleRotate lhs, StyleRotate rhs)
{
return lhs.m_Keyword == rhs.m_Keyword && lhs.m_Value == rhs.m_Value;
}
/// <undoc/>
public static bool operator!=(StyleRotate lhs, StyleRotate rhs)
{
return !(lhs == rhs);
}
/// <undoc/>
public static implicit operator StyleRotate(StyleKeyword keyword)
{
return new StyleRotate(keyword);
}
/// <undoc/>
public static implicit operator StyleRotate(Rotate v)
{
return new StyleRotate(v);
}
/// <undoc/>
public bool Equals(StyleRotate other)
{
return other == this;
}
/// <undoc/>
public override bool Equals(object obj)
{
return obj is StyleRotate other && Equals(other);
}
public override int GetHashCode()
{
unchecked
{
return (m_Value.GetHashCode() * 397) ^ (int)m_Keyword;
}
}
public override string ToString()
{
return this.DebugString();
}
}
}
| UnityCsReference/Modules/UIElements/Core/Style/StyleRotate.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/Style/StyleRotate.cs",
"repo_id": "UnityCsReference",
"token_count": 1702
} | 511 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using Unity.Properties;
using UnityEngine.UIElements.StyleSheets;
namespace UnityEngine.UIElements
{
public partial struct StylePropertyName
{
internal class PropertyBag : ContainerPropertyBag<StylePropertyName>
{
class IdProperty : Property<StylePropertyName, StylePropertyId>
{
public override string Name { get; } = nameof(id);
public override bool IsReadOnly { get; } = true;
public override StylePropertyId GetValue(ref StylePropertyName container) => container.id;
public override void SetValue(ref StylePropertyName container, StylePropertyId value) {}
}
class NameProperty : Property<StylePropertyName, string>
{
public override string Name { get; } = nameof(name);
public override bool IsReadOnly { get; } = true;
public override string GetValue(ref StylePropertyName container) => container.name;
public override void SetValue(ref StylePropertyName container, string value) {}
}
public PropertyBag()
{
AddProperty(new IdProperty());
AddProperty(new NameProperty());
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/StylePropertyName.PropertyBag.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/StylePropertyName.PropertyBag.cs",
"repo_id": "UnityCsReference",
"token_count": 583
} | 512 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace UnityEngine.UIElements.StyleSheets
{
internal static partial class ShorthandApplicator
{
private static List<TimeValue> s_TransitionDelayList = new List<TimeValue>();
private static List<TimeValue> s_TransitionDurationList = new List<TimeValue>();
private static List<StylePropertyName> s_TransitionPropertyList = new List<StylePropertyName>();
private static List<EasingFunction> s_TransitionTimingFunctionList = new List<EasingFunction>();
private static bool CompileFlexShorthand(StylePropertyReader reader, out float grow, out float shrink, out Length basis)
{
grow = 0f;
shrink = 1f;
basis = Length.Auto();
bool valid = false;
var valueCount = reader.valueCount;
if (valueCount == 1 && reader.IsValueType(0, StyleValueType.Keyword))
{
// Handle none | auto
if (reader.IsKeyword(0, StyleValueKeyword.None))
{
valid = true;
grow = 0f;
shrink = 0f;
basis = Length.Auto();
}
else if (reader.IsKeyword(0, StyleValueKeyword.Auto))
{
valid = true;
grow = 1f;
shrink = 1f;
basis = Length.Auto();
}
}
else if (valueCount <= 3)
{
// Handle [ <'flex-grow'> <'flex-shrink'>? || <'flex-basis'> ]
valid = true;
grow = 0f;
shrink = 1f;
basis = Length.Percent(0);
bool growFound = false;
bool basisFound = false;
for (int i = 0; i < valueCount && valid; i++)
{
var valueType = reader.GetValueType(i);
if (valueType == StyleValueType.Dimension || valueType == StyleValueType.Keyword)
{
// Basis
if (basisFound)
{
valid = false;
break;
}
basisFound = true;
if (valueType == StyleValueType.Keyword)
{
if (reader.IsKeyword(i, StyleValueKeyword.Auto))
basis = Length.Auto();
}
else if (valueType == StyleValueType.Dimension)
{
basis = reader.ReadLength(i);
}
if (growFound && i != valueCount - 1)
{
// If grow is already processed basis must be the last value
valid = false;
}
}
else if (valueType == StyleValueType.Float)
{
var value = reader.ReadFloat(i);
if (!growFound)
{
growFound = true;
grow = value;
}
else
{
shrink = value;
}
}
else
{
valid = false;
}
}
}
return valid;
}
private static void CompileBorderRadius(StylePropertyReader reader, out Length top, out Length right, out Length bottom, out Length left)
{
CompileBoxArea(reader, out top, out right, out bottom, out left);
// Border radius doesn't support any keyword, reset to 0 in this case.
if (top.IsAuto() || top.IsNone())
top = 0f;
if (right.IsAuto() || right.IsNone())
right = 0f;
if (bottom.IsAuto() || bottom.IsNone())
bottom = 0f;
if (left.IsAuto() || left.IsNone())
left = 0f;
}
private static void CompileBackgroundPosition(StylePropertyReader reader, out BackgroundPosition backgroundPositionX, out BackgroundPosition backgroundPositionY)
{
var valCount = reader.valueCount;
var val1 = reader.GetValue(0);
var val2 = valCount > 1 ? reader.GetValue(1) : default;
var val3 = valCount > 2 ? reader.GetValue(2) : default;
var val4 = valCount > 3 ? reader.GetValue(3) : default;
backgroundPositionX = new BackgroundPosition();
backgroundPositionY = new BackgroundPosition();
if (valCount == 1)
{
var keyword = (BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 0);
if (keyword == BackgroundPositionKeyword.Left)
{
backgroundPositionX = new BackgroundPosition(BackgroundPositionKeyword.Left);
backgroundPositionY = BackgroundPosition.Initial();
}
else if (keyword == BackgroundPositionKeyword.Right)
{
backgroundPositionX = new BackgroundPosition(BackgroundPositionKeyword.Right);
backgroundPositionY = BackgroundPosition.Initial();
}
else if (keyword == BackgroundPositionKeyword.Top)
{
backgroundPositionX = BackgroundPosition.Initial();
backgroundPositionY = new BackgroundPosition(BackgroundPositionKeyword.Top);
}
else if (keyword == BackgroundPositionKeyword.Bottom)
{
backgroundPositionX = BackgroundPosition.Initial();
backgroundPositionY = new BackgroundPosition(BackgroundPositionKeyword.Bottom);
}
else if (keyword == BackgroundPositionKeyword.Center)
{
backgroundPositionX = new BackgroundPosition(BackgroundPositionKeyword.Center);
backgroundPositionY = new BackgroundPosition(BackgroundPositionKeyword.Center);
}
}
else if (valCount == 2)
{
if (((val1.handle.valueType == StyleValueType.Dimension) || (val1.handle.valueType == StyleValueType.Float)) &&
((val1.handle.valueType == StyleValueType.Dimension) || (val1.handle.valueType == StyleValueType.Float)))
{
backgroundPositionX = new BackgroundPosition(BackgroundPositionKeyword.Left, val1.sheet.ReadDimension(val1.handle).ToLength());
backgroundPositionY = new BackgroundPosition(BackgroundPositionKeyword.Top, val2.sheet.ReadDimension(val2.handle).ToLength());
}
else if ((val1.handle.valueType == StyleValueType.Enum) && (val2.handle.valueType == StyleValueType.Enum))
{
BackgroundPositionKeyword keyword1 = (BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 0);
BackgroundPositionKeyword keyword2 = (BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 1);
static void SwapKeyword(ref BackgroundPositionKeyword a, ref BackgroundPositionKeyword b)
{
BackgroundPositionKeyword temp = a;
a = b;
b = temp;
}
if (keyword2 == BackgroundPositionKeyword.Left) SwapKeyword(ref keyword1, ref keyword2);
if (keyword2 == BackgroundPositionKeyword.Right) SwapKeyword(ref keyword1, ref keyword2);
if (keyword1 == BackgroundPositionKeyword.Top) SwapKeyword(ref keyword1, ref keyword2);
if (keyword1 == BackgroundPositionKeyword.Bottom) SwapKeyword(ref keyword1, ref keyword2);
backgroundPositionX = new BackgroundPosition(keyword1);
backgroundPositionY = new BackgroundPosition(keyword2);
}
}
else if (valCount == 3)
{
if ((val1.handle.valueType == StyleValueType.Enum) &&
(val2.handle.valueType == StyleValueType.Enum) &&
(val3.handle.valueType == StyleValueType.Dimension))
{
backgroundPositionX = new BackgroundPosition((BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 0));
backgroundPositionY = new BackgroundPosition((BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 1), reader.ReadLength(2));
}
else if ((val1.handle.valueType == StyleValueType.Enum) &&
(val2.handle.valueType == StyleValueType.Dimension) &&
(val3.handle.valueType == StyleValueType.Enum))
{
backgroundPositionX = new BackgroundPosition((BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 0), reader.ReadLength(1));
backgroundPositionY = new BackgroundPosition((BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 2));
}
}
else if (valCount == 4)
{
if ((val1.handle.valueType == StyleValueType.Enum) &&
(val2.handle.valueType == StyleValueType.Dimension) &&
(val3.handle.valueType == StyleValueType.Enum) &&
(val4.handle.valueType == StyleValueType.Dimension))
{
backgroundPositionX = new BackgroundPosition((BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 0), reader.ReadLength(1));
backgroundPositionY = new BackgroundPosition((BackgroundPositionKeyword)reader.ReadEnum(StyleEnumType.BackgroundPositionKeyword, 2), reader.ReadLength(3));
}
}
}
public static void CompileUnityBackgroundScaleMode(StylePropertyReader reader,
out BackgroundPosition backgroundPositionX,
out BackgroundPosition backgroundPositionY,
out BackgroundRepeat backgroundRepeat,
out BackgroundSize backgroundSize)
{
var scaleMode = (ScaleMode)reader.ReadEnum(StyleEnumType.ScaleMode, 0);
backgroundPositionX = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(scaleMode);
backgroundPositionY = BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(scaleMode);
backgroundRepeat = BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat(scaleMode);
backgroundSize = BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(scaleMode);
}
private static void CompileBoxArea(StylePropertyReader reader, out Length top, out Length right, out Length bottom, out Length left)
{
top = 0f;
right = 0f;
bottom = 0f;
left = 0f;
var valueCount = reader.valueCount;
switch (valueCount)
{
// apply to all four sides
case 0:
break;
case 1:
{
top = right = bottom = left = reader.ReadLength(0);
break;
}
// vertical | horizontal
case 2:
{
top = bottom = reader.ReadLength(0);
left = right = reader.ReadLength(1);
break;
}
// top | horizontal | bottom
case 3:
{
top = reader.ReadLength(0);
left = right = reader.ReadLength(1);
bottom = reader.ReadLength(2);
break;
}
// top | right | bottom | left
default:
{
top = reader.ReadLength(0);
right = reader.ReadLength(1);
bottom = reader.ReadLength(2);
left = reader.ReadLength(3);
break;
}
}
}
private static void CompileBoxArea(StylePropertyReader reader, out float top, out float right, out float bottom, out float left)
{
Length t;
Length r;
Length b;
Length l;
CompileBoxArea(reader, out t, out r, out b, out l);
top = t.value;
right = r.value;
bottom = b.value;
left = l.value;
}
private static void CompileBoxArea(StylePropertyReader reader, out Color top, out Color right, out Color bottom, out Color left)
{
top = Color.clear;
right = Color.clear;
bottom = Color.clear;
left = Color.clear;
var valueCount = reader.valueCount;
switch (valueCount)
{
// apply to all four sides
case 0:
break;
case 1:
{
top = right = bottom = left = reader.ReadColor(0);
break;
}
// vertical | horizontal
case 2:
{
top = bottom = reader.ReadColor(0);
left = right = reader.ReadColor(1);
break;
}
// top | horizontal | bottom
case 3:
{
top = reader.ReadColor(0);
left = right = reader.ReadColor(1);
bottom = reader.ReadColor(2);
break;
}
// top | right | bottom | left
default:
{
top = reader.ReadColor(0);
right = reader.ReadColor(1);
bottom = reader.ReadColor(2);
left = reader.ReadColor(3);
break;
}
}
}
private static void CompileTextOutline(StylePropertyReader reader, out Color outlineColor, out float outlineWidth)
{
outlineColor = Color.clear;
outlineWidth = 0.0f;
var valueCount = reader.valueCount;
for (int i = 0; i < valueCount; i++)
{
var valueType = reader.GetValueType(i);
if (valueType == StyleValueType.Dimension)
outlineWidth = reader.ReadFloat(i);
else if (valueType == StyleValueType.Enum || valueType == StyleValueType.Color)
outlineColor = reader.ReadColor(i);
}
}
// https://drafts.csswg.org/css-transitions/#transition-shorthand-property
// [ none | <single-transition-property> ] || <time> || <easing-function> || <time>
private static void CompileTransition(StylePropertyReader reader, out List<TimeValue> outDelay, out List<TimeValue> outDuration,
out List<StylePropertyName> outProperty, out List<EasingFunction> outTimingFunction)
{
s_TransitionDelayList.Clear();
s_TransitionDurationList.Clear();
s_TransitionPropertyList.Clear();
s_TransitionTimingFunctionList.Clear();
bool isValid = true;
bool noneFound = false;
var valueCount = reader.valueCount;
int transitionCount = 0;
int i = 0;
do
{
// If none is present and there are more transitions the shorthand is considered invalid
if (noneFound)
{
isValid = false;
break;
}
var transitionProperty = InitialStyle.transitionProperty[0];
var transitionDuration = InitialStyle.transitionDuration[0];
var transitionDelay = InitialStyle.transitionDelay[0];
var transitionTimingFunction = InitialStyle.transitionTimingFunction[0];
bool durationFound = false;
bool delayFound = false;
bool propertyFound = false;
bool timingFunctionFound = false;
bool commaFound = false;
for (; i < valueCount && !commaFound; ++i)
{
var valueType = reader.GetValueType(i);
switch (valueType)
{
case StyleValueType.Keyword:
if (reader.IsKeyword(i, StyleValueKeyword.None) && transitionCount == 0)
{
noneFound = true;
propertyFound = true;
transitionProperty = new StylePropertyName("none");
}
else
{
isValid = false;
}
break;
case StyleValueType.Dimension:
var time = reader.ReadTimeValue(i);
if (!durationFound)
{
// transition-duration
durationFound = true;
transitionDuration = time;
}
else if (!delayFound)
{
// transition-delay
delayFound = true;
transitionDelay = time;
}
else
{
isValid = false;
}
break;
case StyleValueType.Enum:
var str = reader.ReadAsString(i);
if (!timingFunctionFound && StylePropertyUtil.TryGetEnumIntValue(StyleEnumType.EasingMode, str, out var intValue))
{
// transition-timing-function
timingFunctionFound = true;
transitionTimingFunction = (EasingMode)intValue;
}
else if (!propertyFound)
{
// transition-property
propertyFound = true;
transitionProperty = new StylePropertyName(str);
}
else
{
isValid = false;
}
break;
case StyleValueType.CommaSeparator:
commaFound = true;
++transitionCount;
break;
default:
isValid = false;
break;
}
}
s_TransitionDelayList.Add(transitionDelay);
s_TransitionDurationList.Add(transitionDuration);
s_TransitionPropertyList.Add(transitionProperty);
s_TransitionTimingFunctionList.Add(transitionTimingFunction);
}
while (i < valueCount && isValid);
if (isValid)
{
outProperty = s_TransitionPropertyList;
outDelay = s_TransitionDelayList;
outDuration = s_TransitionDurationList;
outTimingFunction = s_TransitionTimingFunctionList;
}
else
{
outProperty = InitialStyle.transitionProperty;
outDelay = InitialStyle.transitionDelay;
outDuration = InitialStyle.transitionDuration;
outTimingFunction = InitialStyle.transitionTimingFunction;
}
}
}
}
| UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleSheetApplicator.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/StyleSheetApplicator.cs",
"repo_id": "UnityCsReference",
"token_count": 11480
} | 513 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Bindings;
namespace UnityEngine.UIElements.StyleSheets
{
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal static partial class StylePropertyCache
{
public static bool TryGetSyntax(string name, out string syntax)
{
return s_PropertySyntaxCache.TryGetValue(name, out syntax);
}
public static bool TryGetNonTerminalValue(string name, out string syntax)
{
return s_NonTerminalValues.TryGetValue(name, out syntax);
}
public static string FindClosestPropertyName(string name)
{
float cost = float.MaxValue;
string closestName = null;
foreach (var propName in s_PropertySyntaxCache.Keys)
{
float factor = 1;
// Add some weight to the check if the name is part of the property name
if (propName.Contains(name))
factor = 0.1f;
float d = StringUtils.LevenshteinDistance(name, propName) * factor;
if (d < cost)
{
cost = d;
closestName = propName;
}
}
return closestName;
}
}
}
| UnityCsReference/Modules/UIElements/Core/StyleSheets/Validation/StylePropertyCache.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/StyleSheets/Validation/StylePropertyCache.cs",
"repo_id": "UnityCsReference",
"token_count": 665
} | 514 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.UIElements
{
internal abstract class UIElementsBridge
{
public abstract void SetWantsMouseJumping(int value);
}
internal class RuntimeUIElementsBridge : UIElementsBridge
{
public override void SetWantsMouseJumping(int value)
{
}
}
}
| UnityCsReference/Modules/UIElements/Core/UIElementsBridge.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/UIElementsBridge.cs",
"repo_id": "UnityCsReference",
"token_count": 165
} | 515 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
namespace UnityEngine.UIElements
{
/// <summary>
/// Describes an XML <c>Object</c> attribute referencing an asset of a chosen type in the project. In UXML, this is
/// referenced as a string URI.
/// </summary>
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal class UxmlImageAttributeDescription : UxmlAttributeDescription, IUxmlAssetAttributeDescription
{
// Stores the value of the asset type being interacted with or saved. Defaults to an empty Texture if none is provided
private Type m_AssetType;
/// <summary>
/// Constructor.
/// </summary>
public UxmlImageAttributeDescription()
{
type = "string"; // In uxml, this is referenced as a string.
typeNamespace = xmlSchemaNamespace;
defaultValue = default;
}
/// <summary>
/// The default value to be used for that specific attribute.
/// </summary>
public Background defaultValue { get; set; }
/// <summary>
/// The string representation of the default value of the UXML attribute.
/// </summary>
public override string defaultValueAsString => defaultValue.IsEmpty() ? "null" : defaultValue.ToString();
/// <summary>
/// Retrieves the value of this attribute from the attribute bag. Returns it if it is found, otherwise return null.
/// </summary>
/// <param name="bag">The bag of attributes.</param>
/// <param name="cc">The context in which the values are retrieved.</param>
/// <returns>The value of the attribute.</returns>
public Background GetValueFromBag(IUxmlAttributes bag, CreationContext cc)
{
if (TryGetValueFromBagAsString(bag, cc, out var path, out var sourceAsset) && sourceAsset != null)
{
if (path == null)
return default;
if (m_AssetType == null)
m_AssetType = sourceAsset.GetAssetType(path);
return Background.FromObject(sourceAsset.GetAsset(path, m_AssetType));
}
return default;
}
// Override to keep a reference of the asset type being selected
Type IUxmlAssetAttributeDescription.assetType
{
get => m_AssetType ?? typeof(Texture);
}
}
}
| UnityCsReference/Modules/UIElements/Core/UXML/UxmlImageAttributeDescription.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/UXML/UxmlImageAttributeDescription.cs",
"repo_id": "UnityCsReference",
"token_count": 984
} | 516 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using Unity.Properties;
using UnityEngine.Assertions;
using UnityEngine.Bindings;
using UnityEngine.Pool;
[assembly:GeneratePropertyBagsForTypesQualifiedWith(typeof(UnityEngine.UIElements.IDataSourceViewHashProvider))]
[assembly:GeneratePropertyBagsForTypesQualifiedWith(typeof(UnityEngine.UIElements.INotifyBindablePropertyChanged))]
namespace UnityEngine.UIElements
{
/// <summary>
/// Defines a binding property that serves as an identifier for the binding system.
/// </summary>
public readonly struct BindingId : IEquatable<BindingId>
{
/// <summary>
/// Returns an invalid binding property.
/// </summary>
public static readonly BindingId Invalid = default;
private readonly PropertyPath m_PropertyPath;
private readonly string m_Path;
/// <summary>
/// Instantiate a new binding property.
/// </summary>
/// <param name="path">The path of the property.</param>
public BindingId(string path)
{
m_PropertyPath = new PropertyPath(path);
m_Path = path;
}
/// <summary>
/// Instantiate a new binding property.
/// </summary>
/// <param name="path">The path of the property.</param>
public BindingId(in PropertyPath path)
{
m_PropertyPath = path;
m_Path = path.ToString();
}
/// <summary>
/// Converts a <see cref="BindingId"/> to a <see cref="PropertyPath"/>.
/// </summary>
/// <param name="vep">The property.</param>
/// <returns>A path for the property.</returns>
public static implicit operator PropertyPath(in BindingId vep)
{
return vep.m_PropertyPath;
}
/// <summary>
/// Converts a <see cref="BindingId"/> to a <see cref="string"/>.
/// </summary>
/// <param name="vep">The property.</param>
/// <returns>A path for the property.</returns>
public static implicit operator string(in BindingId vep)
{
return vep.m_Path;
}
/// <summary>
/// Converts a <see cref="string"/> to a <see cref="BindingId"/>.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <returns>The property.</returns>
public static implicit operator BindingId(string name)
{
return new BindingId(name);
}
/// <summary>
/// Converts a <see cref="PropertyPath"/> to a <see cref="BindingId"/>.
/// </summary>
/// <param name="path">The path to the property.</param>
/// <returns>The property.</returns>
public static implicit operator BindingId(in PropertyPath path)
{
return new BindingId(path);
}
/// <summary>
/// Returns the binding property as a string.
/// </summary>
/// <returns>The property path.</returns>
public override string ToString()
{
return m_Path;
}
/// <summary>
/// Indicates whether two binding properties are equal.
/// </summary>
/// <param name="other">The object to compare with the current instance.</param>
/// <returns><see langword="true"/> if obj and this instance are the same type and represent the same value; otherwise, <see langword="false"/>.</returns>
public bool Equals(BindingId other)
{
return m_PropertyPath == other.m_PropertyPath;
}
/// <inheritdoc/>
public override bool Equals(object obj)
{
return obj is BindingId other && Equals(other);
}
/// <inheritdoc/>
public override int GetHashCode()
{
return m_PropertyPath.GetHashCode();
}
/// <undoc/>
public static bool operator ==(in BindingId lhs, in BindingId rhs)
{
return lhs.m_PropertyPath == rhs.m_PropertyPath;
}
/// <undoc/>
public static bool operator !=(in BindingId lhs, in BindingId rhs)
{
return !(lhs == rhs);
}
}
/// <summary>
/// Sends an event when a value of a property changes.
/// </summary>
/// <remarks>
/// This event does not bubble up or trickle down.
/// </remarks>
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
class PropertyChangedEvent : EventBase<PropertyChangedEvent>, IChangeEvent
{
static PropertyChangedEvent()
{
SetCreateFunction(() => new PropertyChangedEvent());
}
/// <summary>
/// Assigns the property of a control that has changed.
/// </summary>
public BindingId property { get; set; }
/// <summary>
/// Creates a new instance of <see cref="PropertyChangedEvent"/>.
/// </summary>
public PropertyChangedEvent()
{
bubbles = false;
tricklesDown = false;
}
/// <summary>
/// Gets an event from the event pool and initializes it with the given property. Use this function instead of
/// creating new events. Events obtained using this method need to be released back to the pool. You can use
/// `Dispose()` to release them.
/// </summary>
/// <param name="property">The property that has changed.</param>
/// <returns>A <see cref="PropertyChangedEvent"/>.</returns>
public static PropertyChangedEvent GetPooled(in BindingId property)
{
var e = GetPooled();
e.property = property;
return e;
}
}
/// <summary>
/// Base class for objects that are part of the UIElements visual tree.
/// </summary>
/// <remarks>
/// VisualElement contains several features that are common to all controls in UIElements, such as layout, styling and event handling.
/// Several other classes derive from it to implement custom rendering and define behaviour for controls.
/// </remarks>
public partial class VisualElement
{
private object m_DataSource;
private PropertyPath m_DataSourcePath;
/// <summary>
/// Assigns a data source to this VisualElement which overrides any inherited data source. This data source is
/// inherited by all children.
/// </summary>
[CreateProperty]
public object dataSource
{
get => m_DataSource;
set
{
if (m_DataSource == value)
return;
var previous = m_DataSource;
m_DataSource = value;
TrackSource(previous, m_DataSource);
IncrementVersion(VersionChangeType.DataSource);
NotifyPropertyChanged(dataSourceProperty);
}
}
/// <summary>
/// Path from the data source to the value.
/// </summary>
[CreateProperty]
public PropertyPath dataSourcePath
{
get => m_DataSourcePath;
set
{
if (m_DataSourcePath == value)
return;
m_DataSourcePath = value;
IncrementVersion(VersionChangeType.DataSource);
NotifyPropertyChanged(dataSourcePathProperty);
}
}
internal string dataSourcePathString
{
get => dataSourcePath.ToString();
set => dataSourcePath = new PropertyPath(value);
}
// Used for uxml serialization authoring only.
List<Binding> m_Bindings;
List<Binding> bindings
{
get => m_Bindings ??= new List<Binding>();
set => m_Bindings = value;
}
/// <summary>
/// The possible type of data source assignable to this VisualElement.
/// <remarks>
/// This information is only used by the UI Builder as a hint to provide some completion to the data source path field when the effective data source cannot be specified at design time.
/// </remarks>
/// </summary>
internal Type dataSourceType { get; set; }
internal string dataSourceTypeString
{
get => UxmlUtility.TypeToString(dataSourceType);
set => dataSourceType = UxmlUtility.ParseType(value);
}
/// <summary>
/// Assigns a binding between a target and a source.
/// </summary>
/// <remarks>
/// Passing a value of <see langword="null"/> for <see cref="binding"/> removes the binding.
/// </remarks>
/// <param name="bindingId">The binding ID.</param>
/// <param name="binding">The binding object.</param>
public void SetBinding(BindingId bindingId, Binding binding)
{
RegisterBinding(bindingId, binding);
}
/// <summary>
/// Gets the binding instance for the provided targeted property.
/// </summary>
/// <param name="bindingId">The binding ID.</param>
/// <returns>The binding instance, if it exists.</returns>
public Binding GetBinding(BindingId bindingId)
{
return TryGetBinding(bindingId, out var binding) ? binding : null;
}
/// <summary>
/// Gets the binding instance for the provided targeted property.
/// </summary>
/// <param name="bindingId">The binding ID.</param>
/// <param name="binding">When this method returns, contains the binding associated with the target property, if it exists; otherwise contains <see langword="null"/></param>
/// <returns><see langword="true"/> if the binding exists; <see langword="false"/> otherwise.</returns>
public bool TryGetBinding(BindingId bindingId, out Binding binding)
{
if (DataBindingUtility.TryGetBinding(this, bindingId, out var bindingInfo))
{
binding = bindingInfo.binding;
return true;
}
binding = null;
return false;
}
/// <summary>
/// Gets information on all the bindings of the current element.
/// </summary>
/// <returns>The bindings information.</returns>
/// <remarks>The order in which the binding information is returned is undefined.</remarks>
public IEnumerable<BindingInfo> GetBindingInfos()
{
using var pool = ListPool<BindingInfo>.Get(out var bindingInfos);
DataBindingUtility.GetBindingsForElement(this, bindingInfos);
foreach (var bindingInfo in bindingInfos)
{
yield return bindingInfo;
}
}
/// <summary>
/// Allows to know if a target property has a binding associated to it.
/// </summary>
/// <param name="bindingId">The binding ID.</param>
/// <returns><see langword="true"/> if the property has a binding; <see langword="false"/> otherwise.</returns>
public bool HasBinding(BindingId bindingId)
{
return TryGetBinding(bindingId, out _);
}
/// <summary>
/// Removes a binding from the element.
/// </summary>
/// <remarks>
/// This is equivalent to calling <see cref="SetBinding"/> with a <see langword="null"/> value./>
/// </remarks>
/// <param name="bindingId">The id of the binding to unbind on this element.</param>
public void ClearBinding(BindingId bindingId)
{
SetBinding(bindingId, null);
bindings?.RemoveAll(b => b.property == bindingId);
}
/// <summary>
/// Removes all bindings from the element.
/// </summary>
public void ClearBindings()
{
DataBindingManager.CreateClearAllBindingsRequest(this);
bindings?.Clear();
if (panel != null)
ProcessBindingRequests();
}
/// <summary>
/// Queries the <see cref="dataSource"/> and <see cref="dataSourcePath"/> inherited from the hierarchy.
/// </summary>
/// <returns>A context object with the hierarchical data source and data source path.</returns>
public DataSourceContext GetHierarchicalDataSourceContext()
{
var current = this;
var path = default(PropertyPath);
while (null != current)
{
if (!current.dataSourcePath.IsEmpty)
path = PropertyPath.Combine(current.dataSourcePath, path);
if (null != current.dataSource)
{
var source = current.dataSource;
return new DataSourceContext(source, path);
}
current = current.hierarchy.parent;
}
return new DataSourceContext(null, path);
}
/// <summary>
/// Queries the <see cref="dataSource"/> and <see cref="dataSourcePath"/> of a binding object.
/// </summary>
/// <param name="bindingId">The binding ID to query.</param>
/// <returns>A context object with the data source and data source path of a binding object.</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public DataSourceContext GetDataSourceContext(BindingId bindingId)
{
if (TryGetDataSourceContext(bindingId, out var context))
return context;
throw new ArgumentOutOfRangeException(nameof(bindingId), $"[UI Toolkit] could not get binding with id '{bindingId}' on the element.");
}
/// <summary>
/// Queries the <see cref="dataSource"/> and <see cref="dataSourcePath"/> of a binding object.
/// </summary>
/// <param name="bindingId">The binding ID to query.</param>
/// <param name="context">The resulting context object.</param>
/// <returns>Returns <see langword="true"/> if a binding with the provided id was registered on the element; <see langword="false"/> otherwise.</returns>
public bool TryGetDataSourceContext(BindingId bindingId, out DataSourceContext context)
{
var binding = GetBinding(bindingId);
switch (binding)
{
case null:
{
context = default;
return false;
}
case IDataSourceProvider {dataSource: { }} provider:
{
context = new DataSourceContext(provider.dataSource, provider.dataSourcePath);
break;
}
case IDataSourceProvider {dataSourcePath.IsEmpty: false} provider:
{
var hierarchicalContext = GetHierarchicalDataSourceContext();
context = new DataSourceContext(
hierarchicalContext.dataSource,
PropertyPath.Combine(hierarchicalContext.dataSourcePath, provider.dataSourcePath)
);
break;
}
default:
{
context = GetHierarchicalDataSourceContext();
break;
}
}
return true;
}
/// <summary>
/// Returns the last <see cref="BindingResult"/> of a binding object from the data source to the UI.
/// </summary>
/// <param name="bindingId">The ID of the binding object.</param>
/// <param name="result">The result of the last binding operation to the UI.</param>
/// <returns><see langword="true"/> if the binding object has been updated; <see langword="false"/> otherwise.</returns>
public bool TryGetLastBindingToUIResult(in BindingId bindingId, out BindingResult result)
{
if (elementPanel == null)
{
result = default;
return false;
}
var bindingManager = elementPanel.dataBindingManager;
if (bindingManager.TryGetBindingData(this, in bindingId, out var bindingData) &&
bindingManager.TryGetLastUIBindingResult(bindingData, out result))
{
return true;
}
result = default;
return false;
}
/// <summary>
/// Returns the last <see cref="BindingResult"/> of a binding object from the UI to the data source.
/// </summary>
/// <param name="bindingId">The ID of the binding object.</param>
/// <param name="result">The result of the last binding operation to the data source.</param>
/// <returns><see langword="true"/> if the binding object has been updated; <see langword="false"/> otherwise.</returns>
public bool TryGetLastBindingToSourceResult(in BindingId bindingId, out BindingResult result)
{
if (elementPanel == null)
{
result = default;
return false;
}
var bindingManager = elementPanel.dataBindingManager;
if (bindingManager.TryGetBindingData(this, in bindingId, out var bindingData) &&
bindingManager.TryGetLastSourceBindingResult(bindingData, out result))
{
return true;
}
result = default;
return false;
}
void RegisterBinding(BindingId bindingId, Binding binding)
{
AddBindingRequest(bindingId, binding);
if (panel != null)
ProcessBindingRequests();
}
internal void AddBindingRequest(BindingId bindingId, Binding binding)
{
DataBindingManager.CreateBindingRequest(this, bindingId, binding);
}
void ProcessBindingRequests()
{
Assert.IsFalse(null == elementPanel, null);
if (DataBindingManager.AnyPendingBindingRequests(this))
IncrementVersion(VersionChangeType.BindingRegistration);
}
void CreateBindingRequests()
{
var p = elementPanel;
Assert.IsFalse(null == p, null);
p.dataBindingManager.TransferBindingRequests(this);
}
void TrackSource(object previous, object current)
{
elementPanel?.dataBindingManager.TrackDataSource(previous, current);
}
}
}
| UnityCsReference/Modules/UIElements/Core/VisualElementDataBinding.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/VisualElementDataBinding.cs",
"repo_id": "UnityCsReference",
"token_count": 8011
} | 517 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using Unity.Profiling;
using UnityEngine.Bindings;
namespace UnityEngine.UIElements
{
// Editor update phases, the order of the enum define the updater order
internal enum VisualTreeEditorUpdatePhase
{
AssetChange,
Count
}
internal interface IVisualTreeEditorUpdater : IDisposable
{
IVisualTreeUpdater GetUpdater(VisualTreeEditorUpdatePhase phase);
void SetUpdater(IVisualTreeUpdater updater, VisualTreeEditorUpdatePhase phase);
void Update();
void UpdateVisualTreePhase(VisualTreeEditorUpdatePhase phase);
void OnVersionChanged(VisualElement ve, VersionChangeType versionChangeType);
}
// Update phases, the order of the enum define the updater order
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal enum VisualTreeUpdatePhase
{
ViewData,
Bindings,
DataBinding,
Animation,
Styles,
Layout,
TransformClip,
Repaint,
Count
}
internal sealed class VisualTreeUpdater : IDisposable
{
class UpdaterArray
{
private IVisualTreeUpdater[] m_VisualTreeUpdaters;
public UpdaterArray()
{
m_VisualTreeUpdaters = new IVisualTreeUpdater[(int)VisualTreeUpdatePhase.Count];
}
public IVisualTreeUpdater this[VisualTreeUpdatePhase phase]
{
set { m_VisualTreeUpdaters[(int)phase] = value; }
get { return m_VisualTreeUpdaters[(int)phase]; }
}
public IVisualTreeUpdater this[int index]
{
set { m_VisualTreeUpdaters[index] = value; }
get { return m_VisualTreeUpdaters[index]; }
}
}
private BaseVisualElementPanel m_Panel;
private UpdaterArray m_UpdaterArray;
public IVisualTreeEditorUpdater visualTreeEditorUpdater { get; set; }
public VisualTreeUpdater(BaseVisualElementPanel panel)
{
m_Panel = panel;
m_UpdaterArray = new UpdaterArray();
SetDefaultUpdaters();
}
public void Dispose()
{
visualTreeEditorUpdater.Dispose();
for (int i = 0; i < (int)VisualTreeUpdatePhase.Count; i++)
{
var updater = m_UpdaterArray[i];
updater.Dispose();
}
}
//Note: used in tests
public void UpdateVisualTree()
{
visualTreeEditorUpdater.Update();
for (int i = 0; i < (int)VisualTreeUpdatePhase.Count; i++)
{
var updater = m_UpdaterArray[i];
using (updater.profilerMarker.Auto())
{
updater.Update();
}
}
}
public void UpdateVisualTreePhase(VisualTreeUpdatePhase phase)
{
var updater = m_UpdaterArray[phase];
using (updater.profilerMarker.Auto())
{
updater.Update();
}
}
public void OnVersionChanged(VisualElement ve, VersionChangeType versionChangeType)
{
visualTreeEditorUpdater.OnVersionChanged(ve, versionChangeType);
for (int i = 0; i < (int)VisualTreeUpdatePhase.Count; i++)
{
var updater = m_UpdaterArray[i];
updater.OnVersionChanged(ve, versionChangeType);
}
}
public void DirtyStyleSheets()
{
var styleUpdater = m_UpdaterArray[VisualTreeUpdatePhase.Styles] as VisualTreeStyleUpdater;
styleUpdater.DirtyStyleSheets();
}
public void SetUpdater(IVisualTreeUpdater updater, VisualTreeUpdatePhase phase)
{
m_UpdaterArray[phase]?.Dispose();
updater.panel = m_Panel;
m_UpdaterArray[phase] = updater;
}
public void SetUpdater<T>(VisualTreeUpdatePhase phase) where T : IVisualTreeUpdater, new()
{
m_UpdaterArray[phase]?.Dispose();
var updater = new T() {panel = m_Panel};
m_UpdaterArray[phase] = updater;
}
public IVisualTreeUpdater GetUpdater(VisualTreeUpdatePhase phase)
{
return m_UpdaterArray[phase];
}
private void SetDefaultUpdaters()
{
SetUpdater<VisualTreeViewDataUpdater>(VisualTreeUpdatePhase.ViewData);
SetUpdater<VisualTreeBindingsUpdater>(VisualTreeUpdatePhase.Bindings);
SetUpdater<VisualTreeDataBindingsUpdater>(VisualTreeUpdatePhase.DataBinding);
SetUpdater<VisualElementAnimationSystem>(VisualTreeUpdatePhase.Animation);
SetUpdater<VisualTreeStyleUpdater>(VisualTreeUpdatePhase.Styles);
SetUpdater<UIRLayoutUpdater>(VisualTreeUpdatePhase.Layout);
SetUpdater<VisualTreeHierarchyFlagsUpdater>(VisualTreeUpdatePhase.TransformClip);
SetUpdater<UIRRepaintUpdater>(VisualTreeUpdatePhase.Repaint);
}
}
[VisibleToOtherModules("UnityEditor.UIBuilderModule")]
internal interface IVisualTreeUpdater : IDisposable
{
BaseVisualElementPanel panel { get; set; }
ProfilerMarker profilerMarker { get; }
void Update();
void OnVersionChanged(VisualElement ve, VersionChangeType versionChangeType);
}
internal abstract class BaseVisualTreeUpdater : IVisualTreeUpdater
{
public event Action<BaseVisualElementPanel> panelChanged;
private BaseVisualElementPanel m_Panel;
public BaseVisualElementPanel panel
{
get { return m_Panel; }
set
{
m_Panel = value;
if (panelChanged != null) panelChanged(value);
}
}
public VisualElement visualTree { get { return panel.visualTree; } }
public abstract ProfilerMarker profilerMarker { get; }
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{}
public abstract void Update();
public abstract void OnVersionChanged(VisualElement ve, VersionChangeType versionChangeType);
}
}
| UnityCsReference/Modules/UIElements/Core/VisualTreeUpdater.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/Core/VisualTreeUpdater.cs",
"repo_id": "UnityCsReference",
"token_count": 2970
} | 518 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Runtime.InteropServices;
namespace UnityEngine.UIElements;
unsafe struct VisualNodePropertyData
{
public void* Ptr;
}
[StructLayout(LayoutKind.Sequential)]
unsafe struct VisualNodeProperty<T> where T : unmanaged
{
readonly VisualNodePropertyData* m_Data;
internal VisualNodeProperty(VisualNodePropertyData* data)
=> m_Data = data;
public ref T this[VisualNodeHandle handle]
{
get
{
Debug.Assert(handle.Id > 0);
return ref ((T*)m_Data->Ptr)[handle.Id - 1];
}
}
}
| UnityCsReference/Modules/UIElements/ScriptBindings/VisualNodeProperty.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElements/ScriptBindings/VisualNodeProperty.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 269
} | 519 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements.Bindings;
// specific enum version that binds on the index property of the BaseField<Enum>
class SerializedManagedEnumBinding : SerializedObjectBindingToBaseField<Enum, BaseField<Enum>>
{
//we need to keep a copy of the last value since some fields will allocate when getting the value
private int lastEnumValue;
private Type managedType;
public static void CreateBind(BaseField<Enum> field, SerializedObjectBindingContext context,
SerializedProperty property)
{
Type managedType;
ScriptAttributeUtility.GetFieldInfoFromProperty(property, out managedType);
if (managedType == null)
{
Debug.LogWarning(
$"{field.GetType().FullName} is not compatible with property \"{property.propertyPath}\". " +
"Make sure you're binding to a managed enum type");
return;
}
var newBinding = new SerializedManagedEnumBinding();
newBinding.isReleased = false;
field.SetBinding(BindingExtensions.s_SerializedBindingId, newBinding);
newBinding.SetBinding(field, context, property, managedType);
}
private void SetBinding(BaseField<Enum> c, SerializedObjectBindingContext context,
SerializedProperty property, Type manageType)
{
this.managedType = manageType;
property.unsafeMode = true;
SetContext(context, property);
int enumValueAsInt = property.intValue;
Enum value = GetEnumFromSerializedFromInt(manageType, ref enumValueAsInt);
if (c is EnumField)
(c as EnumField).Init(value);
else if (c is EnumFlagsField)
(c as EnumFlagsField).Init(value);
else
{
throw new InvalidOperationException(c.GetType() + " cannot be bound to a enum");
}
lastEnumValue = enumValueAsInt;
var previousValue = c.value;
c.value = value;
BindingsStyleHelpers.RegisterRightClickMenu(c, property);
// Make sure to write this property only after setting a first value into the field
// This avoid any null checks in regular update methods
this.field = c;
if (!EqualityComparer<Enum>.Default.Equals(previousValue, c.value))
{
if (c is VisualElement handler)
{
using (ChangeEvent<Enum> evt = ChangeEvent<Enum>.GetPooled(previousValue, previousValue))
{
evt.elementTarget = handler;
handler.SendEvent(evt);
}
}
}
}
static Enum GetEnumFromSerializedFromInt(Type managedType, ref int enumValueAsInt)
{
var enumData = EnumDataUtility.GetCachedEnumData(managedType);
if (enumData.flags)
return EnumDataUtility.IntToEnumFlags(managedType, enumValueAsInt);
int valueIndex = Array.IndexOf(enumData.flagValues, enumValueAsInt);
if (valueIndex != -1)
return enumData.values[valueIndex];
// For binding, return the minimal default value if enumValueAsInt is smaller than the smallest enum value,
// especially if no default enum is defined
if (enumData.flagValues.Length != 0)
{
var minIntValue = enumData.flagValues[0];
var minIntValueIndex = 0;
for (int i = 1; i < enumData.flagValues.Length; i++)
{
if (enumData.flagValues[i] < minIntValue)
{
minIntValueIndex = i;
minIntValue = enumData.flagValues[i];
}
}
if (enumValueAsInt <= minIntValue || (enumValueAsInt == 0 && minIntValue < 0))
{
enumValueAsInt = minIntValue;
return enumData.values[minIntValueIndex];
}
}
Debug.LogWarning("Error: invalid enum value " + enumValueAsInt + " for type " + managedType);
return null;
}
protected override void SyncPropertyToField(BaseField<Enum> c, SerializedProperty p)
{
if (p == null)
{
throw new ArgumentNullException(nameof(p));
}
if (c == null)
{
throw new ArgumentNullException(nameof(c));
}
int enumValueAsInt = p.intValue;
field.value = GetEnumFromSerializedFromInt(managedType, ref enumValueAsInt);
lastEnumValue = enumValueAsInt;
}
protected override void UpdateLastFieldValue()
{
if (field == null || managedType == null)
{
lastEnumValue = 0;
return;
}
var enumData = EnumDataUtility.GetCachedEnumData(managedType);
Enum fieldValue = field?.value;
if (enumData.flags)
lastEnumValue = EnumDataUtility.EnumFlagsToInt(enumData, fieldValue);
else
{
int valueIndex = Array.IndexOf(enumData.values, fieldValue);
if (valueIndex != -1)
lastEnumValue = enumData.flagValues[valueIndex];
else
{
lastEnumValue = 0;
if (field != null)
Debug.LogWarning("Error: invalid enum value " + fieldValue + " for type " + managedType);
}
}
}
protected override bool SyncFieldValueToProperty()
{
if (lastEnumValue == boundProperty.intValue)
return false;
// When the value is a negative we need to convert it or it will be clamped.
var underlyingType = managedType.GetEnumUnderlyingType();
if (lastEnumValue < 0 && (underlyingType == typeof(uint) || underlyingType == typeof(ushort) || underlyingType == typeof(byte)))
{
boundProperty.longValue = (uint)lastEnumValue;
}
else
{
boundProperty.intValue = lastEnumValue;
}
boundProperty.m_SerializedObject.ApplyModifiedProperties();
return true;
}
public override void OnRelease()
{
if (isReleased)
return;
// Make sure to nullify the field to unbind before reverting the enum value
var saveField = field;
BindingsStyleHelpers.UnregisterRightClickMenu(saveField);
field = null;
saveField.value = null;
ResetContext();
field = null;
managedType = null;
isReleased = true;
ResetCachedValues();
}
}
| UnityCsReference/Modules/UIElementsEditor/Bindings/SerializedManagedEnumBinding.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsEditor/Bindings/SerializedManagedEnumBinding.cs",
"repo_id": "UnityCsReference",
"token_count": 2909
} | 520 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using UnityEngine;
using UnityEngine.UIElements;
using UnityEngine.UIElements.Experimental;
namespace UnityEditor.UIElements.Debugger
{
class EventTypeChoice : IComparable<EventTypeChoice>
{
public string Name;
public string Group;
public long TypeId;
public int CompareTo(EventTypeChoice other)
{
if (Group == Name)
{
var comparison = Group.CompareTo(other.Group);
return comparison == 0 ? -1 : comparison;
}
if (other.Group == other.Name)
{
var comparison = Group.CompareTo(other.Group);
return comparison == 0 ? 1 : comparison;
}
return Group.CompareTo(other.Group) * 2 + Name.CompareTo(other.Name);
}
}
internal class EventTypeSearchField : ToolbarSearchField
{
[Serializable]
public new class UxmlSerializedData : ToolbarSearchField.UxmlSerializedData
{
public override object CreateInstance() => new EventTypeSearchField();
}
const int k_MaxTooltipLines = 40;
const string EllipsisText = "...";
VisualElement m_MenuContainer;
VisualElement m_OuterContainer;
ListView m_ListView;
Dictionary<long, bool> m_State;
Dictionary<string, List<long>> m_GroupedEvents;
List<EventTypeChoice> m_Choices;
List<EventTypeChoice> m_FilteredChoices;
Dictionary<long, int> m_EventCountLog;
bool m_IsFocused;
public int GetSelectedCount() => m_Choices.Count(c => c.TypeId > 0 && m_State[c.TypeId]);
public new static readonly string ussClassName = "event-debugger-filter";
public static readonly string ussContainerClassName = ussClassName + "__container";
public static readonly string ussListViewClassName = ussClassName + "__list-view";
public static readonly string ussItemContainerClassName = ussClassName + "__item-container";
public static readonly string ussItemLabelClassName = ussClassName + "__item-label";
public static readonly string ussGroupLabelClassName = ussClassName + "__group-label";
public static readonly string ussItemCountClassName = ussClassName + "__item-count";
public static readonly string ussItemToggleClassName = ussClassName + "__item-toggle";
public IReadOnlyDictionary<long, bool> State => m_State;
public void SetState(Dictionary<long, bool> state)
{
m_State = state;
UpdateTextHint();
}
bool IsGenericTypeOf(Type t, Type genericDefinition)
{
Type[] parameters = null;
return IsGenericTypeOf(t, genericDefinition, out parameters);
}
bool IsGenericTypeOf(Type t, Type genericDefinition, out Type[] genericParameters)
{
genericParameters = new Type[] {};
if (!genericDefinition.IsGenericType)
{
return false;
}
var isMatch = t.IsGenericType && t.GetGenericTypeDefinition() == genericDefinition.GetGenericTypeDefinition();
if (!isMatch && t.BaseType != null)
{
isMatch = IsGenericTypeOf(t.BaseType, genericDefinition, out genericParameters);
}
if (!isMatch && genericDefinition.IsInterface && t.GetInterfaces().Any())
{
foreach (var i in t.GetInterfaces())
{
if (IsGenericTypeOf(i, genericDefinition, out genericParameters))
{
isMatch = true;
break;
}
}
}
if (isMatch && !genericParameters.Any())
{
genericParameters = t.GetGenericArguments();
}
return isMatch;
}
public EventTypeSearchField()
{
m_Choices = new List<EventTypeChoice>();
m_State = new Dictionary<long, bool>();
m_GroupedEvents = new Dictionary<string, List<long>>();
AppDomain currentDomain = AppDomain.CurrentDomain;
HashSet<string> userAssemblies = new HashSet<string>(ScriptingRuntime.GetAllUserAssemblies());
foreach (Assembly assembly in currentDomain.GetAssemblies())
{
if (userAssemblies.Contains(assembly.GetName().Name + ".dll"))
continue;
try
{
foreach (var type in assembly.GetTypes().Where(t => typeof(EventBase).IsAssignableFrom(t) && !t.ContainsGenericParameters))
{
// Only select Pointer events on startup
AddType(type, IsGenericTypeOf(type, typeof(PointerEventBase<>)));
}
// Special case for ChangeEvent<>.
var implementingTypes = GetAllTypesImplementingOpenGenericType(typeof(INotifyValueChanged<>), assembly).ToList();
foreach (var valueChangedType in implementingTypes)
{
var baseType = valueChangedType.BaseType;
if (baseType == null || baseType.GetGenericArguments().Length <= 0)
continue;
var argumentType = baseType.GetGenericArguments()[0];
if (!argumentType.IsGenericParameter)
{
AddType(typeof(ChangeEvent<>).MakeGenericType(argumentType), false);
}
}
}
catch (TypeLoadException e)
{
Debug.LogWarningFormat("Error while loading types from assembly {0}: {1}", assembly.FullName, e);
}
catch (ReflectionTypeLoadException e)
{
for (var i = 0; i < e.LoaderExceptions.Length; i++)
{
if (e.LoaderExceptions[i] != null)
{
Debug.LogError(e.Types[i] + ": " + e.LoaderExceptions[i].Message);
}
}
}
}
m_State.Add(0, false);
// Add groups, with negative ids.
var keyIndex = -1;
foreach (var key in m_GroupedEvents.Keys.OrderBy(k => k))
{
m_Choices.Add(new EventTypeChoice() { Name = key, Group = key, TypeId = keyIndex });
m_State.Add(keyIndex--, key.Contains("IPointerEvent"));
}
m_Choices.Sort();
m_Choices.Insert(0, new EventTypeChoice() { Name = "IAll", Group = "IAll", TypeId = 0 });
m_FilteredChoices = m_Choices.ToList();
m_MenuContainer = new VisualElement();
m_MenuContainer.AddToClassList(ussClassName);
m_OuterContainer = new VisualElement();
m_OuterContainer.AddToClassList(ussContainerClassName);
m_MenuContainer.Add(m_OuterContainer);
m_ListView = new ListView();
m_ListView.AddToClassList(ussListViewClassName);
m_ListView.pickingMode = PickingMode.Position;
m_ListView.showBoundCollectionSize = false;
m_ListView.fixedItemHeight = 20;
m_ListView.selectionType = SelectionType.None;
m_ListView.showAlternatingRowBackgrounds = AlternatingRowBackground.All;
m_ListView.makeItem = () =>
{
var container = new VisualElement();
container.AddToClassList(ussItemContainerClassName);
var toggle = new Toggle();
toggle.labelElement.AddToClassList(ussItemLabelClassName);
toggle.visualInput.AddToClassList(ussItemToggleClassName);
toggle.RegisterValueChangedCallback(OnToggleValueChanged);
container.Add(toggle);
var label = new Label();
label.AddToClassList(ussItemCountClassName);
label.pickingMode = PickingMode.Ignore;
container.Add(label);
return container;
};
m_ListView.bindItem = (element, i) =>
{
var toggle = element[0] as Toggle;
var countLabel = element[1] as Label;
var choice = m_FilteredChoices[i];
toggle.SetValueWithoutNotify(m_State[choice.TypeId]);
var isGroup = choice.Name == choice.Group;
toggle.label = isGroup ? $"{choice.Group.Substring(1).Replace("Event", "")} Events" : choice.Name;
toggle.labelElement.RemoveFromClassList(isGroup ? ussItemLabelClassName : ussGroupLabelClassName);
toggle.labelElement.AddToClassList(isGroup ? ussGroupLabelClassName : ussItemLabelClassName);
toggle.userData = i;
if (m_EventCountLog != null && m_EventCountLog.ContainsKey(choice.TypeId))
{
countLabel.style.display = DisplayStyle.Flex;
countLabel.text = m_EventCountLog[choice.TypeId].ToString();
}
else
{
countLabel.text = "";
countLabel.style.display = DisplayStyle.None;
}
};
m_ListView.itemsSource = m_FilteredChoices;
m_OuterContainer.Add(m_ListView);
UpdateTextHint();
m_MenuContainer.RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
m_MenuContainer.RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
textInputField.RegisterValueChangedCallback(OnValueChanged);
RegisterCallback<FocusInEvent>(OnFocusIn);
RegisterCallback<FocusEvent>(OnFocus);
RegisterCallback<FocusOutEvent>(OnFocusOut);
}
public void SetEventLog(Dictionary<long, int> log)
{
m_EventCountLog = log;
}
static IEnumerable<Type> GetAllTypesImplementingOpenGenericType(Type openGenericType, Assembly assembly)
{
return from x in assembly.GetTypes()
from z in x.GetInterfaces()
let y = x.BaseType
where (y != null && y.IsGenericType && openGenericType.IsAssignableFrom(y.GetGenericTypeDefinition())) ||
(z.IsGenericType && openGenericType.IsAssignableFrom(z.GetGenericTypeDefinition()))
select x;
}
void AddType(Type type, bool value)
{
var methodInfo = type.GetMethod("TypeId", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
if (methodInfo == null)
return;
var typeId = (long)methodInfo.Invoke(null, null);
if (m_State.ContainsKey(typeId))
return;
m_State.Add(typeId, value);
var nextType = type;
bool InterfacePredicate(Type t) => t.IsPublic && t.Namespace != nameof(System);
Type interfaceType;
do
{
var previousType = nextType;
nextType = previousType.BaseType;
interfaceType = previousType.GetInterfaces().Where(InterfacePredicate).Except(nextType.GetInterfaces().Where(InterfacePredicate)).FirstOrDefault();
}
while (interfaceType == null && nextType != typeof(EventBase));
var readableTypeName = EventDebugger.GetTypeDisplayName(type);
if (interfaceType != null)
{
if (!m_GroupedEvents.ContainsKey(interfaceType.Name))
{
m_GroupedEvents.Add(interfaceType.Name, new List<long>());
}
m_GroupedEvents[interfaceType.Name].Add(typeId);
m_Choices.Add(new EventTypeChoice { Name = readableTypeName, TypeId = typeId, Group = interfaceType.Name });
}
else
{
if (!m_GroupedEvents.ContainsKey("IUncategorized"))
m_GroupedEvents.Add("IUncategorized", new List<long>());
m_GroupedEvents["IUncategorized"].Add(typeId);
m_Choices.Add(new EventTypeChoice { Name = readableTypeName, TypeId = typeId, Group = "IUncategorized" });
}
}
void OnToggleValueChanged(ChangeEvent<bool> e)
{
var element = e.elementTarget;
var index = (int)element.userData;
var choice = m_FilteredChoices[index];
m_State[choice.TypeId] = e.newValue;
if (choice.TypeId < 0)
{
foreach (var eventTypeId in m_GroupedEvents[choice.Group])
{
m_State[eventTypeId] = e.newValue;
}
}
else if (choice.TypeId == 0)
{
foreach (var c in m_Choices)
{
m_State[c.TypeId] = e.newValue;
}
}
// All toggling
if (m_State.Where(s => s.Key > 0).All(s => s.Value))
{
m_State[0] = true;
}
else if (m_State.Where(s => s.Key > 0).Any(s => !s.Value))
{
m_State[0] = false;
}
// Group toggling
if (choice.TypeId != 0)
{
if (m_GroupedEvents[choice.Group].All(id => m_State[id]))
{
var group = m_Choices.First(c => c.TypeId < 0 && c.Group == choice.Group);
m_State[group.TypeId] = true;
}
else if (m_GroupedEvents[choice.Group].Any(id => !m_State[id]))
{
var group = m_Choices.First(c => c.TypeId < 0 && c.Group == choice.Group);
m_State[group.TypeId] = false;
}
}
FilterEvents(value);
using (var evt = ChangeEvent<string>.GetPooled(null, null))
{
evt.elementTarget = this;
SendEvent(evt);
}
}
void OnAttachToPanel(AttachToPanelEvent evt)
{
if (evt.destinationPanel == null)
return;
m_ListView.RegisterCallback<GeometryChangedEvent>(EnsureVisibilityInParent);
}
void OnDetachFromPanel(DetachFromPanelEvent evt)
{
if (evt.originPanel == null)
return;
m_ListView.UnregisterCallback<GeometryChangedEvent>(EnsureVisibilityInParent);
m_MenuContainer.UnregisterCallback<AttachToPanelEvent>(OnAttachToPanel);
m_MenuContainer.UnregisterCallback<DetachFromPanelEvent>(OnDetachFromPanel);
}
void OnFocusIn(FocusInEvent evt)
{
DropDown();
}
void OnFocus(FocusEvent evt)
{
if (!m_IsFocused)
{
m_FilteredChoices = m_Choices.ToList();
m_ListView.itemsSource = m_FilteredChoices;
RefreshLayout();
SetValueWithoutNotify("");
}
m_IsFocused = true;
}
void OnFocusOut(FocusOutEvent evt)
{
var focusedElement = evt.relatedTarget as VisualElement;
if (focusedElement?.FindCommonAncestor(m_ListView) != m_ListView && focusedElement?.FindCommonAncestor(this) != this)
{
Hide();
UpdateTextHint();
m_IsFocused = false;
}
else
{
m_MenuContainer.schedule.Execute(Focus);
}
}
void UpdateTextHint()
{
UpdateTooltip();
var choiceCount = GetSelectedCount();
base.SetValueWithoutNotify($"{choiceCount} selected event type{(choiceCount > 1 ? "s" : "")}");
}
void OnValueChanged(ChangeEvent<string> changeEvent)
{
FilterEvents(changeEvent.newValue.Trim());
}
// Use quicksearch instead?
const string k_IsKeyword = "is:";
static readonly string[] k_OnKeywords = { "on", "enabled", "true" };
static readonly string[] k_OffKeywords = { "off", "disabled", "false" };
void FilterEvents(string filter)
{
m_FilteredChoices.Clear();
var filterLower = filter.ToLower();
bool? isOn = null;
var checkIsParameter = filter.StartsWith(k_IsKeyword);
if (checkIsParameter)
{
var parameter = filter.Substring(k_IsKeyword.Length);
if (k_OnKeywords.Contains(parameter))
isOn = true;
else if (k_OffKeywords.Contains(parameter))
isOn = false;
}
foreach (var choice in m_Choices)
{
if (isOn != null && m_State[choice.TypeId] == isOn.Value)
{
m_FilteredChoices.Add(choice);
}
else if (string.IsNullOrEmpty(filter) || choice.Name.ToLower().Contains(filterLower) || choice.Group.ToLower().Contains(filterLower))
{
m_FilteredChoices.Add(choice);
}
}
m_ListView.itemsSource = m_FilteredChoices;
RefreshLayout();
}
void DropDown()
{
var root = panel.GetRootVisualElement();
root.Add(m_MenuContainer);
m_MenuContainer.style.left = root.layout.x;
m_MenuContainer.style.top = root.layout.y;
m_MenuContainer.style.width = root.layout.width;
m_MenuContainer.style.height = root.layout.height;
m_OuterContainer.style.left = worldBound.x - root.layout.x;
m_OuterContainer.style.top = worldBound.y - root.layout.y;
ClearTooltip();
}
void Hide()
{
m_MenuContainer.RemoveFromHierarchy();
}
void EnsureVisibilityInParent(GeometryChangedEvent evt)
{
RefreshLayout();
}
void RefreshLayout()
{
var root = panel.GetRootVisualElement();
if (root != null && !float.IsNaN(m_OuterContainer.layout.width) && !float.IsNaN(m_OuterContainer.layout.height))
{
m_OuterContainer.style.height = Mathf.Min(
m_MenuContainer.layout.height - m_MenuContainer.layout.y - m_OuterContainer.layout.y,
m_ListView.fixedItemHeight * m_ListView.itemsSource.Count +
m_ListView.resolvedStyle.borderTopWidth + m_ListView.resolvedStyle.borderBottomWidth +
m_OuterContainer.resolvedStyle.borderBottomWidth + m_OuterContainer.resolvedStyle.borderTopWidth);
if (resolvedStyle.width > m_OuterContainer.resolvedStyle.width)
{
m_OuterContainer.style.width = resolvedStyle.width;
}
}
}
void UpdateTooltip()
{
var tooltipStr = new StringBuilder();
var lineCount = 0;
foreach (var selectedChoice in m_Choices.Where(c => c.TypeId > 0 && m_State[c.TypeId]))
{
if (lineCount++ >= k_MaxTooltipLines)
{
tooltipStr.AppendLine(EllipsisText);
break;
}
tooltipStr.AppendLine(selectedChoice.Name);
}
textInputField.tooltip = tooltipStr.ToString();
}
void ClearTooltip()
{
textInputField.tooltip = "Type in event name to filter the list. You can also use the keyword is:{on/off}.";
}
}
}
| UnityCsReference/Modules/UIElementsEditor/Debugger/Events/EventTypeSearchField.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsEditor/Debugger/Events/EventTypeSearchField.cs",
"repo_id": "UnityCsReference",
"token_count": 10155
} | 521 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
using UnityEngine;
using System;
using UnityEngine.UIElements.UIR;
namespace UnityEditor.UIElements.Debugger
{
class TextureAtlasViewer
{
public enum AtlasType
{
Nearest = 1,
Bilinear = 2,
};
[Flags]
public enum DisplayOptions
{
SubTextures = 1 << 0,
AllocationRows = 1 << 1,
AllocationAreas = 1 << 2,
}
public static UIElementsDebugger UIElementsDebugger;
DynamicAtlasPage m_SelectedAtlasPage;
public DynamicAtlas GetDynamicAtlas()
{
if (null == UIElementsDebugger)
return null;
var panel = UIElementsDebugger.debuggerContext?.selection?.panel as BaseVisualElementPanel;
return panel?.atlas as DynamicAtlas;
}
void FetchAtlasPage(AtlasType atlasType)
{
m_SelectedAtlasPage = null;
if (null == UIElementsDebugger)
return;
// This code could probably be dropped right into the final product
var debuggerContext = UIElementsDebugger.debuggerContext;
if (null == debuggerContext)
return;
DynamicAtlas atlas = GetDynamicAtlas();
if (atlas == null)
return;
switch (atlasType)
{
case AtlasType.Nearest:
m_SelectedAtlasPage = atlas.PointPage;
break;
case AtlasType.Bilinear:
m_SelectedAtlasPage = atlas.BilinearPage;
break;
default:
return;
}
}
public Texture GetAtlasTexture(AtlasType atlasType)
{
FetchAtlasPage(atlasType);
return m_SelectedAtlasPage?.atlas;
}
static void DrawRect(Painter2D painter, RectInt rect, Color color, float atlasTextureHeight)
{
if (null == painter)
return;
painter.lineWidth = 1.0f;
painter.lineCap = LineCap.Butt;
painter.strokeColor = color;
painter.BeginPath();
painter.MoveTo(new Vector2(rect.min.x, atlasTextureHeight - rect.max.y));
painter.LineTo(new Vector2(rect.max.x, atlasTextureHeight - rect.max.y));
painter.LineTo(new Vector2(rect.max.x, atlasTextureHeight - rect.min.y));
painter.LineTo(new Vector2(rect.min.x, atlasTextureHeight - rect.min.y));
painter.LineTo(new Vector2(rect.min.x, atlasTextureHeight - rect.max.y));
painter.Stroke();
}
public void DrawOverlay(Painter2D painter2D, DisplayOptions displayOptions)
{
if (m_SelectedAtlasPage == null)
return;
Texture atlasTexture = m_SelectedAtlasPage.atlas;
if (atlasTexture == null)
return;
DynamicAtlas dynamicAtlas = GetDynamicAtlas();
Debug.Assert(dynamicAtlas != null);
var database = dynamicAtlas.Database;
RectInt atlasRect = new RectInt(0, 0, atlasTexture.width, atlasTexture.height);
DrawRect(painter2D, atlasRect, Color.gray, atlasTexture.height);
if ((displayOptions & DisplayOptions.AllocationAreas) != 0)
{
foreach (Allocator2D.Area area in m_SelectedAtlasPage.allocator.areas)
{
if (area.rect.xMax > atlasRect.width || area.rect.yMax > atlasRect.height)
continue;
RectInt areaRect = area.rect;
DrawRect(painter2D, areaRect, Color.green, atlasTexture.height);
}
}
foreach (var texInfo in database.Values)
{
if (texInfo.page != m_SelectedAtlasPage) continue;
if ((displayOptions & DisplayOptions.SubTextures) != 0)
{
RectInt texInfoRect = texInfo.rect;
DrawRect(painter2D, texInfoRect, Color.red, atlasTexture.height);
}
if ((displayOptions & DisplayOptions.AllocationRows) != 0)
{
var alloc = texInfo.alloc;
var row = alloc.row;
RectInt AllocPageRect = row.rect;
DrawRect(painter2D, AllocPageRect, Color.blue, atlasTexture.height);
}
}
}
}
}
| UnityCsReference/Modules/UIElementsEditor/Debugger/TextureAtlas/TextureAtlasViewer.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsEditor/Debugger/TextureAtlas/TextureAtlasViewer.cs",
"repo_id": "UnityCsReference",
"token_count": 2395
} | 522 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.UIElements;
using UnityEngine;
using System;
using Object = UnityEngine.Object;
namespace UnityEditor.UIElements.Inspector
{
[CustomEditor(typeof(UIDocument))]
internal class UIDocumentInspector : Editor
{
const string k_DefaultStyleSheetPath = "UIPackageResources/StyleSheets/Inspector/UIDocumentInspector.uss";
const string k_InspectorVisualTreeAssetPath = "UIPackageResources/UXML/Inspector/UIDocumentInspector.uxml";
private const string k_StyleClassWithParentHidden = "unity-ui-document-inspector--with-parent--hidden";
private const string k_StyleClassPanelMissing = "unity-ui-document-inspector--panel-missing--hidden";
private static StyleSheet k_DefaultStyleSheet = null;
private VisualElement m_RootVisualElement;
private VisualTreeAsset m_InspectorUxml;
private ObjectField m_PanelSettingsField;
private ObjectField m_ParentField;
private ObjectField m_SourceAssetField;
private Foldout m_WorldSpaceDimensionsFoldout;
private EnumField m_WorldSpaceSizeField;
private VisualElement m_WorldSpaceWidthField;
private VisualElement m_WorldSpaceHeightField;
private HelpBox m_DrivenByParentWarning;
private HelpBox m_MissingPanelSettings;
private void ConfigureFields()
{
// Using MandatoryQ instead of just Q to make sure modifications of the UXML file don't make the
// necessary elements disappear unintentionally.
m_DrivenByParentWarning = m_RootVisualElement.MandatoryQ<HelpBox>("driven-by-parent-warning");
m_MissingPanelSettings = m_RootVisualElement.MandatoryQ<HelpBox>("missing-panel-warning");
m_PanelSettingsField = m_RootVisualElement.MandatoryQ<ObjectField>("panel-settings-field");
m_PanelSettingsField.objectType = typeof(PanelSettings);
m_ParentField = m_RootVisualElement.MandatoryQ<ObjectField>("parent-field");
m_ParentField.objectType = typeof(UIDocument);
m_ParentField.SetEnabled(false);
m_SourceAssetField = m_RootVisualElement.MandatoryQ<ObjectField>("source-asset-field");
m_SourceAssetField.objectType = typeof(VisualTreeAsset);
m_WorldSpaceDimensionsFoldout = m_RootVisualElement.MandatoryQ<Foldout>("world-space-dimensions");
m_WorldSpaceSizeField = m_RootVisualElement.MandatoryQ<EnumField>("size-mode");
m_WorldSpaceWidthField = m_RootVisualElement.MandatoryQ<VisualElement>("width-field");
m_WorldSpaceHeightField = m_RootVisualElement.MandatoryQ<VisualElement>("height-field");
m_WorldSpaceDimensionsFoldout.style.display = DisplayStyle.None;
}
private void BindFields()
{
m_ParentField.RegisterCallback<ChangeEvent<Object>>(evt => UpdateValues());
m_PanelSettingsField.RegisterCallback<ChangeEvent<Object>>(evt => UpdateValues());
m_WorldSpaceSizeField.RegisterCallback<ChangeEvent<Enum>>(evt => UpdateValues());
}
private void UpdateValues()
{
UIDocument uiDocument = (UIDocument)target;
bool isNotDrivenByParent = uiDocument.parentUI == null;
m_DrivenByParentWarning.EnableInClassList(k_StyleClassWithParentHidden, isNotDrivenByParent);
m_ParentField.EnableInClassList(k_StyleClassWithParentHidden, isNotDrivenByParent);
bool displayPanelMissing = !(isNotDrivenByParent && uiDocument.panelSettings == null);
m_MissingPanelSettings.EnableInClassList(k_StyleClassPanelMissing, displayPanelMissing);
m_PanelSettingsField.SetEnabled(isNotDrivenByParent);
m_WorldSpaceDimensionsFoldout.style.display = (uiDocument.panelSettings?.renderMode == PanelRenderMode.WorldSpace) ? DisplayStyle.Flex : DisplayStyle.None;
bool isFixedSize = (uiDocument.worldSpaceSizeMode == UIDocument.WorldSpaceSizeMode.Fixed);
var display = isFixedSize ? DisplayStyle.Flex : DisplayStyle.None;
m_WorldSpaceWidthField.style.display = display;
m_WorldSpaceHeightField.style.display = display;
}
public override VisualElement CreateInspectorGUI()
{
if (m_RootVisualElement == null)
{
m_RootVisualElement = new VisualElement();
}
else
{
m_RootVisualElement.Clear();
}
if (m_InspectorUxml == null)
{
m_InspectorUxml = EditorGUIUtility.Load(k_InspectorVisualTreeAssetPath) as VisualTreeAsset;
}
if (k_DefaultStyleSheet == null)
{
k_DefaultStyleSheet = EditorGUIUtility.Load(k_DefaultStyleSheetPath) as StyleSheet;
}
m_RootVisualElement.styleSheets.Add(k_DefaultStyleSheet);
m_InspectorUxml.CloneTree(m_RootVisualElement);
ConfigureFields();
BindFields();
UpdateValues();
return m_RootVisualElement;
}
}
}
| UnityCsReference/Modules/UIElementsEditor/GameObjects/Inspector/UIDocumentInspector.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsEditor/GameObjects/Inspector/UIDocumentInspector.cs",
"repo_id": "UnityCsReference",
"token_count": 2121
} | 523 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements
{
internal static class UIElementsEditorRuntimeUtility
{
public static void CreateRuntimePanelDebug(IPanel panel)
{
var panelDebug = new PanelDebug(panel);
(panel as Panel).panelDebug = panelDebug;
}
}
}
| UnityCsReference/Modules/UIElementsEditor/UIElementsEditorRuntimeUtility.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsEditor/UIElementsEditorRuntimeUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 181
} | 524 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEditor.Compilation;
using UnityEngine.Scripting;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements
{
internal class UXMLFactoryPreserver
{
static HashSet<string> s_PrecompiledUnityAssemblies;
static readonly HashSet<string> s_UsedTypesInsideAsset = new HashSet<string>();
static readonly List<Type> s_FactoryTypesUsedInAsset = new List<Type>();
// Called from native code when preparing assets for a build
[RequiredByNativeCode]
public static List<Type> ExtractTypesFromVisualTreeAsset(VisualTreeAsset asset)
{
if (s_PrecompiledUnityAssemblies == null)
{
// Ignore all precompiled Unity assemblies, but include those from users
CompilationPipeline.PrecompiledAssemblySources sources = CompilationPipeline.PrecompiledAssemblySources.All;
sources &= ~CompilationPipeline.PrecompiledAssemblySources.UserAssembly;
s_PrecompiledUnityAssemblies = new HashSet<string>(CompilationPipeline.GetPrecompiledAssemblyPaths(sources));
}
s_FactoryTypesUsedInAsset.Clear();
s_UsedTypesInsideAsset.Clear();
asset.ExtractUsedUxmlQualifiedNames(s_UsedTypesInsideAsset);
#pragma warning disable CS0618 // Type or member is obsolete
foreach (var qualifiedName in s_UsedTypesInsideAsset)
{
if (VisualElementFactoryRegistry.TryGetValue(qualifiedName, out List<IUxmlFactory> factoryList))
{
foreach (var factory in factoryList)
{
var type = factory.GetType();
if (s_PrecompiledUnityAssemblies.Contains(type.Assembly.Location))
continue;
s_FactoryTypesUsedInAsset.Add(type);
}
}
}
#pragma warning restore CS0618 // Type or member is obsolete
return s_FactoryTypesUsedInAsset;
}
}
}
| UnityCsReference/Modules/UIElementsEditor/UXMLFactoryPreserver.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsEditor/UXMLFactoryPreserver.cs",
"repo_id": "UnityCsReference",
"token_count": 976
} | 525 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements.Samples
{
internal class EnumFlagsFieldSnippet : ElementSnippet<EnumFlagsFieldSnippet>
{
[Flags]
enum EnumFlags
{
First = 1,
Second = 2,
Third = 4
}
internal override void Apply(VisualElement container)
{
#region sample
/// <sample>
// Get a reference to the field from UXML,
// initialize it with an Enum type,
// and assign a value to it.
var uxmlField = container.Q<EnumFlagsField>("the-uxml-field");
uxmlField.Init(EnumFlags.First);
uxmlField.value = EnumFlags.Second;
// Create a new field, disable it, and give it a style class.
var csharpField = new EnumFlagsField("C# Field", uxmlField.value);
csharpField.SetEnabled(false);
csharpField.AddToClassList("some-styled-field");
csharpField.value = uxmlField.value;
container.Add(csharpField);
// Mirror the value of the UXML field into the C# field.
uxmlField.RegisterCallback<ChangeEvent<Enum>>((evt) =>
{
csharpField.value = evt.newValue;
});
/// </sample>
#endregion
}
}
}
| UnityCsReference/Modules/UIElementsSamplesEditor/Snippets/EnumFlagsFieldSnippet.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsSamplesEditor/Snippets/EnumFlagsFieldSnippet.cs",
"repo_id": "UnityCsReference",
"token_count": 722
} | 526 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements.Samples
{
internal class RadioButtonGroupSnippet : ElementSnippet<RadioButtonGroupSnippet>
{
internal override void Apply(VisualElement container)
{
#region sample
/// <sample>
// You can provide the list of choices by code, or by comma separated values in UXML
// <DropdownField .... choices="Option 1,Option 2,Option 3" .... />
var choices = new List<string> { "Option 1", "Option 2", "Option 3" };
// Get a reference to the radio button group field from UXML and assign a value to it.
var uxmlField = container.Q<RadioButtonGroup>("the-uxml-field");
uxmlField.choices = choices;
uxmlField.value = 0;
// Create a new field, disable it, and give it a style class.
var csharpField = new RadioButtonGroup("C# Field", choices);
csharpField.value = 0;
csharpField.SetEnabled(false);
csharpField.AddToClassList("some-styled-field");
csharpField.value = uxmlField.value;
container.Add(csharpField);
// Mirror the value of the UXML field into the C# field.
uxmlField.RegisterCallback<ChangeEvent<int>>((evt) =>
{
csharpField.value = evt.newValue;
});
/// </sample>
#endregion
}
}
}
| UnityCsReference/Modules/UIElementsSamplesEditor/Snippets/RadioButtonGroupSnippet.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsSamplesEditor/Snippets/RadioButtonGroupSnippet.cs",
"repo_id": "UnityCsReference",
"token_count": 698
} | 527 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.UIElements.Samples
{
internal class Vector2IntFieldSnippet : ElementSnippet<Vector2IntFieldSnippet>
{
internal override void Apply(VisualElement container)
{
#region sample
/// <sample>
// Get a reference to the field from UXML and assign a value to it.
var uxmlField = container.Q<Vector2IntField>("the-uxml-field");
uxmlField.value = new Vector2Int(23, 12);
// Create a new field, disable it, and give it a style class.
var csharpField = new Vector2IntField("C# Field");
csharpField.SetEnabled(false);
csharpField.AddToClassList("some-styled-field");
csharpField.value = uxmlField.value;
container.Add(csharpField);
// Mirror the value of the UXML field into the C# field.
uxmlField.RegisterCallback<ChangeEvent<Vector2Int>>((evt) =>
{
csharpField.value = evt.newValue;
});
/// </sample>
#endregion
}
}
}
| UnityCsReference/Modules/UIElementsSamplesEditor/Snippets/Vector2IntFieldSnippet.cs/0 | {
"file_path": "UnityCsReference/Modules/UIElementsSamplesEditor/Snippets/Vector2IntFieldSnippet.cs",
"repo_id": "UnityCsReference",
"token_count": 569
} | 528 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Object = UnityEngine.Object;
namespace UnityEngine.Analytics
{
internal partial class CustomEventData : IDisposable
{
public bool AddDictionary(IDictionary<string, object> eventData)
{
foreach (var item in eventData)
{
string key = item.Key;
object value = item.Value;
if (value == null)
{
AddString(key, "null");
continue;
}
Type type = value.GetType();
if (type == typeof(System.String))
AddString(key, (string)value);
else if (type == typeof(System.Char))
AddString(key, Char.ToString((Char)value));
else if (type == typeof(System.SByte))
AddInt32(key, (SByte)value);
else if (type == typeof(System.Byte))
AddInt32(key, (Byte)value);
else if (type == typeof(System.Int16))
AddInt32(key, (Int16)value);
else if (type == typeof(System.UInt16))
AddUInt32(key, (UInt16)value);
else if (type == typeof(System.Int32))
AddInt32(key, (Int32)value);
else if (type == typeof(System.UInt32))
AddUInt32(item.Key, (UInt32)value);
else if (type == typeof(System.Int64))
AddInt64(key, (Int64)value);
else if (type == typeof(System.UInt64))
AddUInt64(key, (UInt64)value);
else if (type == typeof(System.Boolean))
AddBool(key, (bool)value);
else if (type == typeof(System.Single))
AddDouble(key, (double)System.Convert.ToDecimal((Single)value));
else if (type == typeof(System.Double))
AddDouble(key, (double)value);
else if (type == typeof(System.Decimal))
AddDouble(key, (double)System.Convert.ToDecimal((Decimal)value));
else if (type.IsValueType)
AddString(key, value.ToString());
else
throw new ArgumentException(String.Format("Invalid type: {0} passed", type));
}
return true;
}
}
}
| UnityCsReference/Modules/UnityAnalytics/Public/Events/CustomEventData.cs/0 | {
"file_path": "UnityCsReference/Modules/UnityAnalytics/Public/Events/CustomEventData.cs",
"repo_id": "UnityCsReference",
"token_count": 1409
} | 529 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
namespace UnityEngine.Analytics
{
[StructLayout(LayoutKind.Sequential)]
[NativeHeader("Modules/UnityAnalyticsCommon/Public/UnityAnalyticsCommon.h")]
public static partial class AnalyticsCommon
{
[StaticAccessor("GetUnityAnalyticsCommon()", StaticAccessorType.Dot)]
private extern static bool ugsAnalyticsEnabledInternal
{
[NativeMethod("UGSAnalyticsUserOptStatus")]
get;
[NativeMethod("SetUGSAnalyticsUserOptStatus")]
set;
}
}
}
| UnityCsReference/Modules/UnityAnalyticsCommon/Public/UnityAnalyticsCommon.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/UnityAnalyticsCommon/Public/UnityAnalyticsCommon.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 280
} | 530 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEditor.Connect
{
/// <summary>
/// A very lightweight state machine which uses generics as events
/// (unless you have specific needs, enums are recommended) and states
/// (either instance of the base state or your own extensions).
/// </summary>
internal class SimpleStateMachine<T>
{
HashSet<T> m_Events = new HashSet<T>();
Dictionary<string, State> m_StateByName = new Dictionary<string, State>();
bool m_Initialized;
/// <summary>
/// The current state
/// </summary>
public State currentState { get; private set; }
/// <summary>
/// Initializes the state machine.
/// This should be called after instantiating the state machine and instantiating the initial state.
/// Since the state machine needs an initial state instance and the state needs a state machine instance, the
/// proper order is:
/// 1- instantiate state machine
/// 2- instantiate initial state
/// 3- initialize state machine with initial state
/// A state machine cannot be initialized multiple times. Further attempts will be ignored.
/// </summary>
/// <param name="initialState"></param>
public void Initialize(State initialState)
{
if (!m_Initialized)
{
if (!StateExists(initialState))
{
AddState(initialState);
}
m_Initialized = true;
currentState = initialState;
currentState.EnterState();
}
}
/// <summary>
/// Clears the current state
/// Allows for a full redraw on the state machine in the activate action without reallocating memory
/// </summary>
public void ClearCurrentState()
{
if (m_Initialized)
{
currentState = null;
m_Initialized = false;
}
}
/// <summary>
/// Adds a new event to the state machine
/// Don't forget that events are sent to states. So when adding an event to the state machine,
/// it generally means that this event should also be configured on some states by using
/// mySimpleStateMachineState.ModifyActionForEvent(myEvent, myHandler);
/// </summary>
/// <param name="simpleStateMachineEvent">the event</param>
public void AddEvent(T simpleStateMachineEvent)
{
m_Events.Add(simpleStateMachineEvent);
}
public bool EventExists(T simpleStateMachineEvent)
{
foreach (T knownEvent in m_Events)
{
if (knownEvent.Equals(simpleStateMachineEvent))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets a copy of the state machine events.
/// Copy means you cannot alter the state machine by altering this list.
/// It's a shallow copy though, be careful what you do with the list entries
/// </summary>
/// <returns>a copy of the state machine events</returns>
public List<T> GetEvents()
{
return new List<T>(m_Events);
}
/// <summary>
/// Adds a new state to the state machine.
/// This state can be generic (straight instance of SimpleStateMachineState) or an extended version if you need
/// to override the EnterState() method of the SimpleStateMachineState.
/// A state should react to events. Configure the state by using ModifyActionForEvent
/// </summary>
/// <param name="state"></param>
public void AddState(State state)
{
m_StateByName.Add(state.name, state);
}
/// <summary>
/// This method is exposed to allow states to return a new state when an event action is completed successfully
/// and a transition is made to another state.
/// </summary>
/// <param name="stateName">The name of the state to find</param>
/// <returns>The state; or null if none found</returns>
public State GetStateByName(string stateName)
{
return m_StateByName.ContainsKey(stateName) ? m_StateByName[stateName] : null;
}
public bool StateExists(State state)
{
return m_StateByName.ContainsKey(state.name);
}
/// <summary>
/// Gets a shallow copy of the state machine states.
/// Copy means you cannot alter the state machine by altering this list
/// (but changing the configuration of a state will modify the state machine: shallow copy)
/// </summary>
/// <returns>a copy of the state machine states</returns>
public List<State> GetStates()
{
return new List<State>(m_StateByName.Values);
}
/// <summary>
/// Call this method when an event occurs on the state machine.
/// This will often result in a state change, but it's not mandatory.
/// Nothing will happen if the event does not exist within the state machine events'
/// </summary>
/// <param name="simpleStateMachineEvent">The event to process</param>
public void ProcessEvent(T simpleStateMachineEvent)
{
if (m_Initialized && EventExists(simpleStateMachineEvent))
{
var previousState = currentState;
currentState = currentState.GetActionForEvent(simpleStateMachineEvent).Invoke(simpleStateMachineEvent);
if (currentState != previousState)
{
if (currentState != null)
{
currentState.EnterState();
}
else
{
Debug.LogError("SimpleStateMachine.ProcessEvent: " + L10n.Tr("Attempting to change to an undefined state. Contact Unity Support."));
}
}
}
}
/// <summary>
/// Base state for a simple state machine. It can be used as-is or extended to gain additional functionality
/// </summary>
internal class State
{
List<ActionForEvent> m_ActionForEvent = new List<ActionForEvent>();
/// <summary>
/// Access to the state machine. Mostly to GetStateByName when transitioning from one state to another
/// </summary>
protected SimpleStateMachine<T> stateMachine { get; }
public string name { get; }
public State(string name, SimpleStateMachine<T> simpleStateMachine)
{
this.name = name;
stateMachine = simpleStateMachine;
}
public virtual bool ActionExistsForEvent(T simpleStateMachineEvent)
{
foreach (var actionForEvent in m_ActionForEvent)
{
if (actionForEvent.simpleStateMachineEvent.Equals(simpleStateMachineEvent))
{
return true;
}
}
return false;
}
/// <summary>
/// Updates or Inserts a new action to execute when an event occurs when the state machine is at this state.
/// </summary>
/// <param name="simpleStateMachineEvent">The event</param>
/// <param name="transitionAction">The action to accomplish when the specified event occurs</param>
public virtual void ModifyActionForEvent(T simpleStateMachineEvent, Func<T, State> transitionAction)
{
foreach (var actionForEvent in m_ActionForEvent)
{
if (actionForEvent.simpleStateMachineEvent.Equals(simpleStateMachineEvent))
{
actionForEvent.action = transitionAction;
return;
}
}
m_ActionForEvent.Add(new ActionForEvent(simpleStateMachineEvent, transitionAction));
}
/// <summary>
/// This method is called by the state machine when an event occurs. By default,
/// if the state machine does not find an action to execute, the state will remain unchanged
/// and the event will be ignored.
/// </summary>
/// <param name="simpleStateMachineEvent">the event we search an action for</param>
/// <returns>an action to execute; can be DoNothing if ModifyActionForEvent wasn't done for this event</returns>
public virtual Func<T, State> GetActionForEvent(T simpleStateMachineEvent)
{
foreach (var actionForEvent in m_ActionForEvent)
{
if (actionForEvent.simpleStateMachineEvent.Equals(simpleStateMachineEvent))
{
return actionForEvent.action;
}
}
return DoNothing;
}
/// <summary>
/// Default action taken when no handler is found for an event.
/// Will simply return the current state and thus, does nothing
/// </summary>
/// <returns></returns>
State DoNothing(T simpleStateMachineEvent)
{
return this;
}
/// <summary>
/// This method will be called by the state machine when the a state becomes active.
/// It allows to do a common operation on the current state without having all the other states repeat this
/// code within their transition actions.
/// </summary>
public virtual void EnterState() {}
class ActionForEvent
{
internal T simpleStateMachineEvent { get; }
internal Func<T, State> action { get; set; }
internal ActionForEvent(T simpleStateMachineEvent, Func<T, State> action)
{
this.simpleStateMachineEvent = simpleStateMachineEvent;
this.action = action;
}
}
}
}
}
| UnityCsReference/Modules/UnityConnectEditor/Common/SimpleStateMachine.cs/0 | {
"file_path": "UnityCsReference/Modules/UnityConnectEditor/Common/SimpleStateMachine.cs",
"repo_id": "UnityCsReference",
"token_count": 4599
} | 531 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine;
using UnityEngine.Networking;
namespace UnityEditor.Connect
{
internal class AnalyticsValidationPoller
{
const double k_TickIntervalSeconds = 15.0;
readonly TickTimerHelper m_Ticker = new TickTimerHelper(k_TickIntervalSeconds);
//Auth signature for project, needed to access and validate data
string m_ProjectAuthSignature;
UnityWebRequest m_DataValidationRequest;
private bool m_IsStarted;
private string m_RawValidationData;
Action<string> m_NotifyOnDataUpdate;
public string projectAuthSignature
{
get { return m_ProjectAuthSignature; }
}
public void Setup(string authSignature, Action<string> updateNotification)
{
m_ProjectAuthSignature = authSignature;
m_NotifyOnDataUpdate = updateNotification;
}
public void Shutdown()
{
Stop();
m_ProjectAuthSignature = null;
m_RawValidationData = null;
m_NotifyOnDataUpdate = null;
if (m_DataValidationRequest != null)
{
m_DataValidationRequest.Abort();
m_DataValidationRequest.Dispose();
m_DataValidationRequest = null;
}
}
public bool IsReady()
{
return m_ProjectAuthSignature != null;
}
public void Start()
{
if (!m_IsStarted)
{
EditorApplication.update += Update;
m_Ticker.Reset(); // ensures immediate tick on begin
m_IsStarted = true;
}
}
public void Stop()
{
if (m_IsStarted)
{
EditorApplication.update -= Update;
m_IsStarted = false;
}
}
private void Update()
{
if (m_Ticker.DoTick())
{
Poll();
}
}
private bool HasDataChanged(string newRawData)
{
return m_RawValidationData != newRawData;
}
//Can be called independently without Start/Stopping, however will not adjust tick interval (it's private)
public void Poll()
{
if (IsReady() && m_DataValidationRequest == null)
{
AnalyticsService.instance.RequestValidationData(OnPolled, m_ProjectAuthSignature, out m_DataValidationRequest);
}
}
private void OnPolled(AsyncOperation op)
{
if (op.isDone)
{
if (m_DataValidationRequest != null)
{
if ((m_DataValidationRequest.result != UnityWebRequest.Result.ProtocolError) && (m_DataValidationRequest.result != UnityWebRequest.Result.ConnectionError))
{
string newRawData = m_DataValidationRequest.downloadHandler.text;
if (HasDataChanged(newRawData))
{
m_RawValidationData = newRawData;
if (m_NotifyOnDataUpdate != null)
{
m_NotifyOnDataUpdate(m_RawValidationData);
}
}
}
m_DataValidationRequest.Dispose();
m_DataValidationRequest = null;
}
}
}
}
}
| UnityCsReference/Modules/UnityConnectEditor/Services/AnalyticsValidationPoller.cs/0 | {
"file_path": "UnityCsReference/Modules/UnityConnectEditor/Services/AnalyticsValidationPoller.cs",
"repo_id": "UnityCsReference",
"token_count": 1894
} | 532 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections;
using System.Reflection;
using System.Runtime.CompilerServices;
using Unity.Profiling;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using UnityEngine.Analytics;
using UnityEditor.PackageManager;
using UnityEngine;
using UnityEditor.Modules;
namespace UnityEditor
{
[RequiredByNativeCode]
[NativeHeader("Modules/UnityEditorAnalyticsEditor/UnityEditorAnalytics.h")]
[NativeHeader("Modules/UnityAnalytics/ContinuousEvent/Manager.h")]
[NativeHeader("Modules/UnityEditorAnalyticsEditor/UnityEditorAnalyticsManager.h")]
public static class EditorAnalytics
{
[RequiredByNativeCode]
internal static void SendAnalyticsToEditor(string analytics)
{
DebuggerEventListHandler.AddAnalytic(analytics);
}
internal static AnalyticsResult SendEventRefreshAccess(object parameters)
{
return EditorAnalytics.SendEvent("refreshAccess", parameters);
}
internal static AnalyticsResult SendEventNewLink(object parameters)
{
return EditorAnalytics.SendEvent("newLink", parameters);
}
internal static AnalyticsResult SendEventScriptableBuildPipelineInfo(object parameters)
{
return EditorAnalytics.SendEvent("scriptableBuildPipeline", parameters);
}
internal static AnalyticsResult SendEventBuildFrameworkList(object parameters)
{
return EditorAnalytics.SendEvent("buildFrameworkList", parameters, SendEventOptions.kAppendBuildGuid | SendEventOptions.kAppendBuildTarget);
}
internal static AnalyticsResult SendEventServiceInfo(object parameters)
{
return EditorAnalytics.SendEvent("serviceInfo", parameters);
}
internal static AnalyticsResult SendEventShowService(object parameters)
{
return EditorAnalytics.SendEvent("showService", parameters);
}
internal static AnalyticsResult SendEventCloseServiceWindow(object parameters)
{
return EditorAnalytics.SendEvent("closeService", parameters);
}
const string k_EventName = "editorgameserviceeditor";
internal static bool RegisterEventEditorGameService()
{
const int maxEventsPerHour = 100;
const int maxItems = 10;
const string vendorKey = "unity.services.core.editor";
const int version = 1;
var result = RegisterEventWithLimit(k_EventName, maxEventsPerHour, maxItems, vendorKey, version, "", Assembly.GetCallingAssembly());
return result == AnalyticsResult.Ok;
}
internal static AnalyticsResult SendEventEditorGameService(object parameters)
{
return EditorAnalytics.SendEvent(k_EventName, parameters);
}
internal static AnalyticsResult SendImportServicePackageEvent(object parameters)
{
return EditorAnalytics.SendEvent("importServicePackage", parameters);
}
internal static AnalyticsResult SendOpenPackManFromServiceSettings(object parameters)
{
return EditorAnalytics.SendEvent("openPackageManager", parameters);
}
internal static AnalyticsResult SendOpenDashboardForService(object parameters)
{
return EditorAnalytics.SendEvent("openDashboard", parameters);
}
internal static AnalyticsResult SendValidatePublicKeyEvent(object parameters)
{
return EditorAnalytics.SendEvent("validatePublicKey", parameters);
}
internal static AnalyticsResult SendLaunchCloudBuildEvent(object parameters)
{
return EditorAnalytics.SendEvent("launchCloudBuild", parameters);
}
internal static AnalyticsResult SendClearAnalyticsDataEvent(object parameters)
{
return EditorAnalytics.SendEvent("clearAnalyticsData", parameters);
}
internal static AnalyticsResult SendProjectServiceBindingEvent(object parameters)
{
return EditorAnalytics.SendEvent("projectServiceBinding", parameters);
}
internal static AnalyticsResult SendCoppaComplianceEvent(object parameters)
{
return EditorAnalytics.SendEvent("coppaSetting", parameters);
}
internal static AnalyticsResult SendEventTimelineInfo(object parameters)
{
return EditorAnalytics.SendEvent("timelineInfo", parameters);
}
internal static AnalyticsResult SendEventBuildTargetDevice(object parameters)
{
return EditorAnalytics.SendEvent("buildTargetDevice", parameters, SendEventOptions.kAppendBuildGuid);
}
internal static AnalyticsResult SendEventSceneViewInfo(object parameters)
{
return EditorAnalytics.SendEvent("sceneViewInfo", parameters);
}
internal static AnalyticsResult SendEventBuildPackageList(object parameters)
{
return EditorAnalytics.SendEvent("buildPackageList", parameters, SendEventOptions.kAppendBuildGuid | SendEventOptions.kAppendBuildTarget);
}
internal static AnalyticsResult SendEventBuildTargetPermissions(object parameters)
{
return EditorAnalytics.SendEventWithVersion("buildTargetPermissions", parameters, 2, SendEventOptions.kAppendBuildGuid | SendEventOptions.kAppendBuildTarget);
}
internal static AnalyticsResult SendCollabUserAction(object parameters)
{
return EditorAnalytics.SendEvent("collabUserAction", parameters);
}
internal static AnalyticsResult SendCollabOperation(object parameters)
{
return EditorAnalytics.SendEvent("collabOperation", parameters);
}
internal static AnalyticsResult SendAssetPostprocessorsUsage(object parameters)
{
return SendEventWithVersion("assetPostProcessorsUsage", parameters, 2);
}
internal extern static AnalyticsResult SendAssetDownloadEvent(object parameters);
public extern static bool enabled
{
get;
set;
}
public extern static bool recordEventsEnabled
{
get;
set;
}
public extern static bool SendAnalyticsEventsImmediately
{
get;
set;
}
internal static AnalyticsResult TryRegisterAnalytic(Analytic analytic, Assembly assembly)
{
if (enabled == false) return AnalyticsResult.AnalyticsDisabled;
AnalyticsResult result = RegisterEventWithLimit(analytic.info.eventName, analytic.info.maxEventsPerHour, analytic.info.maxNumberOfElements, analytic.info.vendorKey, analytic.info.version, "", assembly);
if (result != AnalyticsResult.Ok)
{
Debug.LogWarning($"Unable to register event {analytic.info.eventName} with vendor key: {analytic.info.vendorKey} and error code {result.ToString()}. Editor Analyitics will not be gathered.");
}
return result;
}
internal static AnalyticsResult TrySendAnalytic(Analytic analytic)
{
if (enabled == false) return AnalyticsResult.AnalyticsDisabled;
AnalyticsResult result = AnalyticsResult.Ok;
try
{
if (!analytic.instance.TryGatherData(out var data, out Exception error))
{
Debug.LogWarning(error);
return AnalyticsResult.InvalidData;
}
if (data is IEnumerable enumerable)
{
foreach (var subData in enumerable)
{
result = EditorAnalytics.SendEventWithLimit(analytic.info.eventName, subData, analytic.info.version, "");
}
}
else
{
result = EditorAnalytics.SendEventWithLimit(analytic.info.eventName, data, analytic.info.version, "");
}
}
catch (Exception ex) // We do not want to break the build if any analytic crashes for any reason, Simply we won't send the data to the server
{
Debug.LogWarning($"Exception {ex} found while sending analytic of {analytic.info.eventName}.");
return AnalyticsResult.InvalidData;
}
DebuggerEventListHandler.AddCSharpAnalytic(analytic);
return result;
}
public static AnalyticsResult SendAnalytic(IAnalytic analytic)
{
var analyticType = analytic.GetType();
if (Attribute.IsDefined(analyticType, typeof(AnalyticInfoAttribute)))
{
AnalyticInfoAttribute info = (AnalyticInfoAttribute)analyticType.GetCustomAttributes(typeof(AnalyticInfoAttribute), true)[0];
System.Reflection.Assembly assembly = Assembly.GetCallingAssembly();
return SendAnalytic(new Analytic(analytic, info), assembly);
}
else
{
Debug.LogError($"{analyticType} must contain an attribute of {nameof(AnalyticInfoAttribute)}");
return AnalyticsResult.InvalidData;
}
}
public static AnalyticsResult SendAnalytic(Analytic analytic, Assembly assembly)
{
AnalyticsResult result = AnalyticsResult.Ok;
{
result = TryRegisterAnalytic(analytic, assembly);
if (result != AnalyticsResult.Ok)
return result;
result = TrySendAnalytic(analytic);
}
return result;
}
extern private static AnalyticsResult SendEvent(string eventName, object parameters, SendEventOptions sendEventOptions = SendEventOptions.kAppendNone);
extern internal static AnalyticsResult SendEventWithVersion(string eventName, object parameters, int ver, SendEventOptions sendEventOptions = SendEventOptions.kAppendNone);
const string DeprecatedApiMsg = "Editor Analytics APIs have changed significantly, please see: https://docs.editor-data.unity3d.com/Contribute/EditorAnalytics/cs_guide/";
[MethodImpl(MethodImplOptions.NoInlining)]
[Obsolete(DeprecatedApiMsg)]
public static AnalyticsResult RegisterEventWithLimit(string eventName, int maxEventPerHour, int maxItems, string vendorKey)
{
return RegisterEventWithLimit(eventName, maxEventPerHour, maxItems, vendorKey, 1, "", Assembly.GetCallingAssembly());
}
[MethodImpl(MethodImplOptions.NoInlining)]
[Obsolete(DeprecatedApiMsg)]
public static AnalyticsResult RegisterEventWithLimit(string eventName, int maxEventPerHour, int maxItems, string vendorKey, int ver)
{
return RegisterEventWithLimit(eventName, maxEventPerHour, maxItems, vendorKey, ver, "", Assembly.GetCallingAssembly());
}
[Obsolete(DeprecatedApiMsg)]
public static AnalyticsResult SendEventWithLimit(string eventName, object parameters)
{
return SendEventWithLimit(eventName, parameters, 1, "");
}
[Obsolete(DeprecatedApiMsg)]
public static AnalyticsResult SendEventWithLimit(string eventName, object parameters, int ver)
{
return SendEventWithLimit(eventName, parameters, ver, "");
}
[Obsolete(DeprecatedApiMsg)]
public static AnalyticsResult SetEventWithLimitEndPoint(string eventName, string endPoint, int ver)
{
return SetEventWithLimitEndPoint(eventName, endPoint, ver, "");
}
[Obsolete(DeprecatedApiMsg)]
public static AnalyticsResult SetEventWithLimitPriority(string eventName, AnalyticsEventPriority eventPriority, int ver)
{
return SetEventWithLimitPriority(eventName, eventPriority, ver, "");
}
private static AnalyticsResult RegisterEventWithLimit(string eventName, int maxEventPerHour, int maxItems, string vendorKey, int ver, string prefix, Assembly assembly)
{
string assemblyInfo = null;
string packageName = null;
string packageVersion = null;
if (assembly != null)
{
assemblyInfo = assembly.FullName;
PackageManager.PackageInfo packageInfo = PackageManager.PackageInfo.FindForAssembly(assembly);
if (packageInfo != null)
{
packageName = packageInfo.name;
packageVersion = packageInfo.version;
}
}
return RegisterEventWithLimit(eventName, maxEventPerHour, maxItems, vendorKey, ver, prefix, assemblyInfo, packageName, packageVersion, true);
}
private extern static AnalyticsResult RegisterEventWithLimit(string eventName, int maxEventPerHour, int maxItems, string vendorKey, int ver, string prefix, string assemblyInfo, string packageName, string packageVersion, bool notifyServer);
private extern static AnalyticsResult SendEventWithLimit(string eventName, object parameters, int ver, string prefix);
private extern static AnalyticsResult SetEventWithLimitEndPoint(string eventName, string endPoint, int ver, string prefix);
private extern static AnalyticsResult SetEventWithLimitPriority(string eventName, AnalyticsEventPriority eventPriority, int ver, string prefix);
[RequiredByNativeCode]
internal static void AddExtraBuildAnalyticsFields(string target, IntPtr eventData, BuildOptions buildOptions)
{
var extension = ModuleManager.GetEditorAnalyticsExtension(target);
if (extension == null)
return;
extension.AddExtraBuildAnalyticsFields(eventData, buildOptions);
}
}
[RequiredByNativeCode]
[NativeHeader("Modules/UnityEditorAnalyticsEditor/UnityEditorAnalytics.h")]
public static class EditorAnalyticsSessionInfo
{
public extern static long id
{
[NativeMethod("GetSessionId")]
get;
}
public extern static long sessionCount
{
get;
}
public extern static long elapsedTime
{
[NativeMethod("GetSessionElapsedTime")]
get;
}
public extern static long focusedElapsedTime
{
[NativeMethod("GetSessionFocusedElapsedTime")]
get;
}
public extern static long playbackElapsedTime
{
[NativeMethod("GetSessionPlaybackElapsedTime")]
get;
}
public extern static long activeElapsedTime
{
[NativeMethod("GetSessionUserActiveElapsedTime")]
get;
}
public extern static string userId
{
get;
}
}
internal abstract class EditorAnalyticsExtension : IEditorAnalyticsExtension
{
public virtual void AddExtraBuildAnalyticsFields(IntPtr eventData, BuildOptions buildOptions)
{
var evt = new UnityEditor.Analytics.EditorAnalyticsEvent(eventData);
AddExtraBuildAnalyticsFields(evt, buildOptions);
}
public abstract void AddExtraBuildAnalyticsFields(UnityEditor.Analytics.EditorAnalyticsEvent eventData, BuildOptions buildOptions);
public void AddAllowedOrientationsParameter(UnityEditor.Analytics.EditorAnalyticsEvent eventData)
{
int res = 1;
if (PlayerSettings.allowedAutorotateToPortrait)
res |= (1 << 1);
if (PlayerSettings.allowedAutorotateToPortraitUpsideDown)
res |= (1 << 2);
if (PlayerSettings.allowedAutorotateToLandscapeRight)
res |= (1 << 3);
if (PlayerSettings.allowedAutorotateToLandscapeLeft)
res |= (1 << 4);
eventData.AddParameter("orientations_allowed", res);
}
}
}
| UnityCsReference/Modules/UnityEditorAnalyticsEditor/EditorAnalytics.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/UnityEditorAnalyticsEditor/EditorAnalytics.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 6388
} | 533 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
using UnityEngineInternal;
using Unity.Collections;
namespace UnityEngine.Networking
{
[StructLayout(LayoutKind.Sequential)]
[NativeHeader("Modules/UnityWebRequestTexture/Public/DownloadHandlerTexture.h")]
public sealed class DownloadHandlerTexture : DownloadHandler
{
private NativeArray<byte> m_NativeData;
private bool mNonReadable;
private static extern IntPtr Create([Unmarshalled] DownloadHandlerTexture obj, bool readable);
private void InternalCreateTexture(bool readable)
{
m_Ptr = Create(this, readable);
}
public DownloadHandlerTexture()
{
InternalCreateTexture(true);
}
public DownloadHandlerTexture(bool readable)
{
InternalCreateTexture(readable);
mNonReadable = !readable;
}
protected override NativeArray<byte> GetNativeData()
{
return InternalGetNativeArray(this, ref m_NativeData);
}
public override void Dispose()
{
DisposeNativeArray(ref m_NativeData);
base.Dispose();
}
public Texture2D texture
{
get { return InternalGetTextureNative(); }
}
[NativeThrows]
private extern Texture2D InternalGetTextureNative();
public static Texture2D GetContent(UnityWebRequest www)
{
return GetCheckedDownloader<DownloadHandlerTexture>(www).texture;
}
new internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(DownloadHandlerTexture handler) => handler.m_Ptr;
}
}
}
| UnityCsReference/Modules/UnityWebRequestTexture/Public/DownloadHandlerTexture.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/UnityWebRequestTexture/Public/DownloadHandlerTexture.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 748
} | 534 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Runtime.InteropServices;
using UnityEngine;
using UnityEngine.Bindings;
using UnityEngine.Rendering;
using UnityEngine.Scripting;
namespace UnityEditor.VFX
{
[RequiredByNativeCode]
[NativeType(Header = "Modules/VFX/Public/VFXExpressionTextureFunctions.h")]
[StaticAccessor("VFXExpressionTextureFunctions", StaticAccessorType.DoubleColon)]
internal class VFXExpressionTexture
{
extern static internal uint GetTextureFormat(Texture texture);
}
}
| UnityCsReference/Modules/VFXEditor/Public/ScriptBindings/VFXExpressionTexture.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/VFXEditor/Public/ScriptBindings/VFXExpressionTexture.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 209
} | 535 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace UnityEngine.Video
{
[RequiredByNativeCode]
public enum VideoRenderMode
{
CameraFarPlane = 0,
CameraNearPlane = 1,
RenderTexture = 2,
MaterialOverride = 3,
APIOnly = 4
}
[RequiredByNativeCode]
public enum Video3DLayout
{
No3D = 0,
SideBySide3D = 1,
OverUnder3D = 2
}
[RequiredByNativeCode]
public enum VideoAspectRatio
{
NoScaling = 0,
FitVertically = 1,
FitHorizontally = 2,
FitInside = 3,
FitOutside = 4,
Stretch = 5
}
[RequiredByNativeCode]
[System.Obsolete("VideoTimeSource is deprecated. Use TimeUpdateMode instead. (UnityUpgradable) -> VideoTimeUpdateMode")]
public enum VideoTimeSource
{
[System.Obsolete("AudioDSPTimeSource is deprecated. Use DSPTime instead. (UnityUpgradable) -> DSPTime")]
AudioDSPTimeSource = 0,
[System.Obsolete("GameTimeSource is deprecated. Use GameTime instead. (UnityUpgradable) -> GameTime")]
GameTimeSource = 1
}
[RequiredByNativeCode]
public enum VideoTimeReference
{
Freerun = 0,
InternalTime = 1,
ExternalTime = 2
}
[RequiredByNativeCode]
public enum VideoSource
{
VideoClip = 0,
Url = 1
}
[RequiredByNativeCode]
public enum VideoTimeUpdateMode
{
DSPTime = 0,
GameTime = 1,
UnscaledGameTime = 2
}
[RequiredByNativeCode]
public enum VideoAudioOutputMode
{
None = 0,
AudioSource = 1,
Direct = 2,
APIOnly = 3
}
[RequiredByNativeCode]
[RequireComponent(typeof(Transform))]
[NativeHeader("Modules/Video/Public/VideoPlayer.h")]
public sealed class VideoPlayer : Behaviour
{
public extern VideoSource source { get; set; }
public extern VideoTimeUpdateMode timeUpdateMode { get; set; }
[NativeName("VideoUrl")]
public extern string url { get; set; }
[NativeName("VideoClip")]
public extern VideoClip clip { get; set; }
public extern VideoRenderMode renderMode { get; set; }
public extern bool canSetTimeUpdateMode
{
[NativeName("CanSetTimeUpdateMode")]
get;
}
[NativeHeader("Runtime/Camera/Camera.h")]
public extern Camera targetCamera { get; set; }
[NativeHeader("Runtime/Graphics/RenderTexture.h")]
public extern RenderTexture targetTexture { get; set; }
[NativeHeader("Runtime/Graphics/Renderer.h")]
public extern Renderer targetMaterialRenderer { get; set; }
public extern string targetMaterialProperty { get; set; }
internal extern string effectiveTargetMaterialProperty { get; }
public extern VideoAspectRatio aspectRatio { get; set; }
public extern float targetCameraAlpha { get; set; }
public extern Video3DLayout targetCamera3DLayout { get; set; }
[NativeHeader("Runtime/Graphics/Texture.h")]
public extern Texture texture { get; }
public extern void Prepare();
public extern bool isPrepared
{
[NativeName("IsPrepared")]
get;
}
public extern bool waitForFirstFrame { get; set; }
public extern bool playOnAwake { get; set; }
public extern void Play();
public extern void Pause();
public extern void Stop();
public extern bool isPlaying
{
[NativeName("IsPlaying")]
get;
}
public extern bool isPaused
{
[NativeName("IsPaused")]
get;
}
public extern bool canSetTime
{
[NativeName("CanSetTime")]
get;
}
[NativeName("SecPosition")]
public extern double time { get; set; }
[NativeName("FramePosition")]
public extern long frame { get; set; }
public extern double clockTime { get; }
public extern bool canStep
{
[NativeName("CanStep")]
get;
}
public extern void StepForward();
public extern bool canSetPlaybackSpeed
{
[NativeName("CanSetPlaybackSpeed")]
get;
}
public extern float playbackSpeed { get; set; }
[NativeName("Loop")]
public extern bool isLooping { get; set; }
[System.Obsolete("VideoPlayer.canSetTimeSource is deprecated. Use canSetTimeUpdateMode instead. (UnityUpgradable) -> canSetTimeUpdateMode")]
public extern bool canSetTimeSource
{
[NativeName("CanSetTimeSource")]
get;
}
[System.Obsolete("VideoPlayer.timeSource is deprecated. Use timeUpdateMode instead. (UnityUpgradable) -> timeUpdateMode")]
public extern VideoTimeSource timeSource { get; set; }
public extern VideoTimeReference timeReference { get; set; }
public extern double externalReferenceTime { get; set; }
public extern bool canSetSkipOnDrop
{
[NativeName("CanSetSkipOnDrop")]
get;
}
public extern bool skipOnDrop { get; set; }
public extern ulong frameCount { get; }
public extern float frameRate { get; }
[NativeName("Duration")]
public extern double length
{
get;
}
public extern uint width { get; }
public extern uint height { get; }
public extern uint pixelAspectRatioNumerator { get; }
public extern uint pixelAspectRatioDenominator { get; }
public extern ushort audioTrackCount { get; }
public extern string GetAudioLanguageCode(ushort trackIndex);
public extern ushort GetAudioChannelCount(ushort trackIndex);
public extern uint GetAudioSampleRate(ushort trackIndex);
public static extern ushort controlledAudioTrackMaxCount { get; }
public ushort controlledAudioTrackCount
{
get
{
return GetControlledAudioTrackCount();
}
set
{
int maxNumTracks = controlledAudioTrackMaxCount;
if (value > maxNumTracks)
throw new ArgumentException(string.Format("Cannot control more than {0} tracks.", maxNumTracks), "value");
SetControlledAudioTrackCount(value);
}
}
private extern ushort GetControlledAudioTrackCount();
private extern void SetControlledAudioTrackCount(ushort value);
public extern void EnableAudioTrack(ushort trackIndex, bool enabled);
public extern bool IsAudioTrackEnabled(ushort trackIndex);
public extern VideoAudioOutputMode audioOutputMode { get; set; }
public extern bool canSetDirectAudioVolume
{
[NativeName("CanSetDirectAudioVolume")]
get;
}
public extern float GetDirectAudioVolume(ushort trackIndex);
public extern void SetDirectAudioVolume(ushort trackIndex, float volume);
public extern bool GetDirectAudioMute(ushort trackIndex);
public extern void SetDirectAudioMute(ushort trackIndex, bool mute);
[NativeHeader("Modules/Audio/Public/AudioSource.h")]
public extern AudioSource GetTargetAudioSource(ushort trackIndex);
public extern void SetTargetAudioSource(ushort trackIndex, AudioSource source);
public delegate void EventHandler(VideoPlayer source);
public delegate void ErrorEventHandler(VideoPlayer source, string message);
public delegate void FrameReadyEventHandler(VideoPlayer source, long frameIdx);
public delegate void TimeEventHandler(VideoPlayer source, double seconds);
public event EventHandler prepareCompleted;
public event EventHandler loopPointReached;
public event EventHandler started;
public event EventHandler frameDropped;
public event ErrorEventHandler errorReceived;
public event EventHandler seekCompleted;
public event TimeEventHandler clockResyncOccurred;
public extern bool sendFrameReadyEvents
{
[NativeName("AreFrameReadyEventsEnabled")]
get;
[NativeName("EnableFrameReadyEvents")]
set;
}
public event FrameReadyEventHandler frameReady;
[RequiredByNativeCode]
private static void InvokePrepareCompletedCallback_Internal(VideoPlayer source)
{
if (source.prepareCompleted != null)
source.prepareCompleted(source);
}
[RequiredByNativeCode]
private static void InvokeFrameReadyCallback_Internal(VideoPlayer source, long frameIdx)
{
if (source.frameReady != null)
source.frameReady(source, frameIdx);
}
[RequiredByNativeCode]
private static void InvokeLoopPointReachedCallback_Internal(VideoPlayer source)
{
if (source.loopPointReached != null)
source.loopPointReached(source);
}
[RequiredByNativeCode]
private static void InvokeStartedCallback_Internal(VideoPlayer source)
{
if (source.started != null)
source.started(source);
}
[RequiredByNativeCode]
private static void InvokeFrameDroppedCallback_Internal(VideoPlayer source)
{
if (source.frameDropped != null)
source.frameDropped(source);
}
[RequiredByNativeCode]
private static void InvokeErrorReceivedCallback_Internal(VideoPlayer source, string errorStr)
{
if (source.errorReceived != null)
source.errorReceived(source, errorStr);
}
[RequiredByNativeCode]
private static void InvokeSeekCompletedCallback_Internal(VideoPlayer source)
{
if (source.seekCompleted != null)
source.seekCompleted(source);
}
[RequiredByNativeCode]
private static void InvokeClockResyncOccurredCallback_Internal(VideoPlayer source, double seconds)
{
if (source.clockResyncOccurred != null)
source.clockResyncOccurred(source, seconds);
}
internal static event Action<string> analyticsSent;
[RequiredByNativeCode]
private static void InvokeAnalyticsSentCallback_Internal(string analytics)
{
if (analyticsSent != null)
analyticsSent(analytics);
}
[RequiredByNativeCode]
private static bool AnalyticsEventHandlerAttached_Internal()
{
return analyticsSent != null;
}
}
}
| UnityCsReference/Modules/Video/Public/ScriptBindings/VideoPlayer.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/Video/Public/ScriptBindings/VideoPlayer.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 4709
} | 536 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace UnityEngine.XR
{
public enum TrackingOriginModeFlags
{
Unknown = 0,
Device = 1,
Floor = 2,
TrackingReference = 4,
Unbounded = 8
}
[NativeType(Header = "Modules/XR/Subsystems/Input/XRInputSubsystem.h")]
[UsedByNativeCode]
[NativeConditional("ENABLE_XR")]
public class XRInputSubsystem : IntegratedSubsystem<XRInputSubsystemDescriptor>
{
internal extern UInt32 GetIndex();
public extern bool TryRecenter();
public bool TryGetInputDevices(List<InputDevice> devices)
{
if (devices == null)
throw new ArgumentNullException("devices");
devices.Clear();
if (m_DeviceIdsCache == null)
m_DeviceIdsCache = new List<UInt64>();
m_DeviceIdsCache.Clear();
TryGetDeviceIds_AsList(m_DeviceIdsCache);
for (int i = 0; i < m_DeviceIdsCache.Count; i++)
{
devices.Add(new InputDevice(m_DeviceIdsCache[i]));
}
return true;
}
public extern bool TrySetTrackingOriginMode(TrackingOriginModeFlags origin);
public extern TrackingOriginModeFlags GetTrackingOriginMode();
public extern TrackingOriginModeFlags GetSupportedTrackingOriginModes();
public bool TryGetBoundaryPoints(List<Vector3> boundaryPoints)
{
if (boundaryPoints == null)
throw new ArgumentNullException("boundaryPoints");
return TryGetBoundaryPoints_AsList(boundaryPoints);
}
private extern bool TryGetBoundaryPoints_AsList(List<Vector3> boundaryPoints);
public event Action<XRInputSubsystem> trackingOriginUpdated;
public event Action<XRInputSubsystem> boundaryChanged;
[RequiredByNativeCode(GenerateProxy = true)]
private static void InvokeTrackingOriginUpdatedEvent(IntPtr internalPtr)
{
IntegratedSubsystem subsystem = SubsystemManager.GetIntegratedSubsystemByPtr(internalPtr);
XRInputSubsystem inputSubsystem = subsystem as XRInputSubsystem;
if ((inputSubsystem != null) && (inputSubsystem.trackingOriginUpdated != null))
inputSubsystem.trackingOriginUpdated(inputSubsystem);
}
[RequiredByNativeCode(GenerateProxy = true)]
private static void InvokeBoundaryChangedEvent(IntPtr internalPtr)
{
IntegratedSubsystem subsystem = SubsystemManager.GetIntegratedSubsystemByPtr(internalPtr);
XRInputSubsystem inputSubsystem = subsystem as XRInputSubsystem;
if ((inputSubsystem != null) && (inputSubsystem.boundaryChanged != null))
inputSubsystem.boundaryChanged(inputSubsystem);
}
internal extern void TryGetDeviceIds_AsList(List<UInt64> deviceIds);
private List<UInt64> m_DeviceIdsCache;
new internal static class BindingsMarshaller
{
public static IntPtr ConvertToNative(XRInputSubsystem xrInputSubsystem) => xrInputSubsystem.m_Ptr;
}
}
}
| UnityCsReference/Modules/XR/Subsystems/Input/XRInputSubsystem.bindings.cs/0 | {
"file_path": "UnityCsReference/Modules/XR/Subsystems/Input/XRInputSubsystem.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1375
} | 537 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
namespace UnityEngine.Sprites
{
public sealed partial class DataUtility
{
// UV coordinates for the inner part of a sliced Sprite or the whole Sprite if borders=0
public static Vector4 GetInnerUV(Sprite sprite)
{
return sprite.GetInnerUVs();
}
// UV coordinates for the outer part of a sliced Sprite (the whole Sprite)
public static Vector4 GetOuterUV(Sprite sprite)
{
return sprite.GetOuterUVs();
}
// Pixel padding from the edges of the sprite to the drawn rectangle (left, bottom, right, top). Valid when the RenderData rect does not match the definition rect (i.e. alpha trimming).
public static Vector4 GetPadding(Sprite sprite)
{
return sprite.GetPadding();
}
// Gets the minimum size of a sliced Sprite
public static Vector2 GetMinSize(Sprite sprite)
{
Vector2 v;
v.x = sprite.border.x + sprite.border.z;
v.y = sprite.border.y + sprite.border.w;
return v;
}
}
}
| UnityCsReference/Runtime/2D/Common/ScriptBindings/SpriteDataUtility.cs/0 | {
"file_path": "UnityCsReference/Runtime/2D/Common/ScriptBindings/SpriteDataUtility.cs",
"repo_id": "UnityCsReference",
"token_count": 499
} | 538 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Diagnostics;
using UnityEngine;
using UnityEngine.Assertions.Comparers;
namespace UnityEngine.Assertions
{
public static partial class Assert
{
[Conditional(UNITY_ASSERTIONS)]
public static void AreApproximatelyEqual(float expected, float actual)
{
AreEqual(expected, actual, null, FloatComparer.s_ComparerWithDefaultTolerance);
}
[Conditional(UNITY_ASSERTIONS)]
public static void AreApproximatelyEqual(float expected, float actual, string message)
{
AreEqual(expected, actual, message, FloatComparer.s_ComparerWithDefaultTolerance);
}
[Conditional(UNITY_ASSERTIONS)]
public static void AreApproximatelyEqual(float expected, float actual, float tolerance)
{
AreApproximatelyEqual(expected, actual, tolerance, null);
}
[Conditional(UNITY_ASSERTIONS)]
public static void AreApproximatelyEqual(float expected, float actual, float tolerance, string message)
{
AreEqual(expected, actual, message, new FloatComparer(tolerance));
}
[Conditional(UNITY_ASSERTIONS)]
public static void AreNotApproximatelyEqual(float expected, float actual)
{
AreNotEqual(expected, actual, null, FloatComparer.s_ComparerWithDefaultTolerance);
}
[Conditional(UNITY_ASSERTIONS)]
public static void AreNotApproximatelyEqual(float expected, float actual, string message)
{
AreNotEqual(expected, actual, message, FloatComparer.s_ComparerWithDefaultTolerance);
}
[Conditional(UNITY_ASSERTIONS)]
public static void AreNotApproximatelyEqual(float expected, float actual, float tolerance)
{
AreNotApproximatelyEqual(expected, actual, tolerance, null);
}
[Conditional(UNITY_ASSERTIONS)]
public static void AreNotApproximatelyEqual(float expected, float actual, float tolerance, string message)
{
AreNotEqual(expected, actual, message, new FloatComparer(tolerance));
}
}
}
| UnityCsReference/Runtime/Export/Assertions/Assert/AssertFloat.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/Assertions/Assert/AssertFloat.cs",
"repo_id": "UnityCsReference",
"token_count": 872
} | 539 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
using UnityEngine.Bindings;
namespace Unity.Burst.LowLevel
{
internal static partial class BurstCompilerService
{
public delegate bool ExtractCompilerFlags(Type jobType, out string flags);
public enum BurstLogType
{
Info,
Warning,
Error,
}
public static void Initialize(string folderRuntime, ExtractCompilerFlags extractCompilerFlags)
{
if (folderRuntime == null) throw new ArgumentNullException(nameof(folderRuntime));
if (extractCompilerFlags == null) throw new ArgumentNullException(nameof(extractCompilerFlags));
if (!Directory.Exists(folderRuntime))
{
Debug.LogError($"Unable to initialize the burst JIT compiler. The folder `{folderRuntime}` does not exist");
return;
}
var message = InitializeInternal(folderRuntime, extractCompilerFlags);
if (!String.IsNullOrEmpty(message))
Debug.LogError($"Unexpected error while trying to initialize the burst JIT compiler: {message}");
}
}
}
| UnityCsReference/Runtime/Export/Burst/BurstCompilerService.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/Burst/BurstCompilerService.cs",
"repo_id": "UnityCsReference",
"token_count": 530
} | 540 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Scripting;
namespace UnityEngine.Experimental.Rendering
{
[RequiredByNativeCode]
class ScriptableRuntimeReflectionSystemWrapper
{
internal IScriptableRuntimeReflectionSystem implementation { get; set; }
[RequiredByNativeCode]
void Internal_ScriptableRuntimeReflectionSystemWrapper_TickRealtimeProbes(out bool result)
{
result = implementation != null
&& implementation.TickRealtimeProbes();
}
}
}
| UnityCsReference/Runtime/Export/Camera/ScriptableRuntimeReflectionSystemWrapper.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/Camera/ScriptableRuntimeReflectionSystemWrapper.cs",
"repo_id": "UnityCsReference",
"token_count": 232
} | 541 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using UnityEngine.Bindings;
namespace UnityEngine
{
[NativeHeader("Runtime/Director/Core/ExposedPropertyTable.bindings.h")]
[NativeHeader("Runtime/Utilities/PropertyName.h")]
public struct ExposedPropertyResolver
{
internal IntPtr table;
internal static Object ResolveReferenceInternal(IntPtr ptr, PropertyName name, out bool isValid)
{
if (ptr == IntPtr.Zero)
throw new ArgumentNullException("Argument \"ptr\" can't be null.");
return ResolveReferenceBindingsInternal(ptr, name, out isValid);
}
[FreeFunction("ExposedPropertyTableBindings::ResolveReferenceInternal")]
extern private static Object ResolveReferenceBindingsInternal(IntPtr ptr, PropertyName name, out bool isValid);
}
}
| UnityCsReference/Runtime/Export/Director/ExposedPropertyTable.bindings.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/Director/ExposedPropertyTable.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 352
} | 542 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
namespace UnityEngine.Playables
{
// This must always be in sync with DirectorWrapMode in Runtime/Director/Core/Playable.h
public enum PlayableTraversalMode
{
Mix = 0,
Passthrough = 1
}
public static class PlayableExtensions
{
public static bool IsNull<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().IsNull();
}
public static bool IsValid<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().IsValid();
}
public static void Destroy<U>(this U playable)
where U : struct, IPlayable
{
playable.GetHandle().Destroy();
}
public static PlayableGraph GetGraph<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetGraph();
}
[Obsolete("SetPlayState() has been deprecated. Use Play(), Pause() or SetDelay() instead", false)]
public static void SetPlayState<U>(this U playable, PlayState value)
where U : struct, IPlayable
{
if (value == PlayState.Delayed)
throw new ArgumentException("Can't set Delayed: use SetDelay() instead");
switch (value)
{
case PlayState.Playing:
playable.GetHandle().Play();
break;
case PlayState.Paused:
playable.GetHandle().Pause();
break;
}
}
public static PlayState GetPlayState<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetPlayState();
}
public static void Play<U>(this U playable)
where U : struct, IPlayable
{
playable.GetHandle().Play();
}
public static void Pause<U>(this U playable)
where U : struct, IPlayable
{
playable.GetHandle().Pause();
}
public static void SetSpeed<U>(this U playable, double value)
where U : struct, IPlayable
{
playable.GetHandle().SetSpeed(value);
}
public static double GetSpeed<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetSpeed();
}
public static void SetDuration<U>(this U playable, double value)
where U : struct, IPlayable
{
playable.GetHandle().SetDuration(value);
}
public static double GetDuration<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetDuration();
}
public static void SetTime<U>(this U playable, double value)
where U : struct, IPlayable
{
playable.GetHandle().SetTime(value);
}
public static double GetTime<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetTime();
}
public static double GetPreviousTime<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetPreviousTime();
}
public static void SetDone<U>(this U playable, bool value)
where U : struct, IPlayable
{
playable.GetHandle().SetDone(value);
}
public static bool IsDone<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().IsDone();
}
public static void SetPropagateSetTime<U>(this U playable, bool value)
where U : struct, IPlayable
{
playable.GetHandle().SetPropagateSetTime(value);
}
public static bool GetPropagateSetTime<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetPropagateSetTime();
}
public static bool CanChangeInputs<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().CanChangeInputs();
}
public static bool CanSetWeights<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().CanSetWeights();
}
public static bool CanDestroy<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().CanDestroy();
}
public static void SetInputCount<U>(this U playable, int value)
where U : struct, IPlayable
{
playable.GetHandle().SetInputCount(value);
}
public static int GetInputCount<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetInputCount();
}
public static void SetOutputCount<U>(this U playable, int value)
where U : struct, IPlayable
{
playable.GetHandle().SetOutputCount(value);
}
public static int GetOutputCount<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetOutputCount();
}
public static Playable GetInput<U>(this U playable, int inputPort)
where U : struct, IPlayable
{
return playable.GetHandle().GetInput(inputPort);
}
public static Playable GetOutput<U>(this U playable, int outputPort)
where U : struct, IPlayable
{
return playable.GetHandle().GetOutput(outputPort);
}
public static void SetInputWeight<U>(this U playable, int inputIndex, float weight)
where U : struct, IPlayable
{
playable.GetHandle().SetInputWeight(inputIndex, weight);
}
public static void SetInputWeight<U, V>(this U playable, V input, float weight)
where U : struct, IPlayable
where V : struct, IPlayable
{
playable.GetHandle().SetInputWeight(input.GetHandle(), weight);
}
public static float GetInputWeight<U>(this U playable, int inputIndex)
where U : struct, IPlayable
{
return playable.GetHandle().GetInputWeight(inputIndex);
}
public static void ConnectInput<U, V>(this U playable, int inputIndex, V sourcePlayable, int sourceOutputIndex)
where U : struct, IPlayable
where V : struct, IPlayable
{
ConnectInput(playable, inputIndex, sourcePlayable, sourceOutputIndex, 0.0f);
}
public static void ConnectInput<U, V>(this U playable, int inputIndex, V sourcePlayable, int sourceOutputIndex, float weight)
where U : struct, IPlayable
where V : struct, IPlayable
{
playable.GetGraph().Connect(sourcePlayable, sourceOutputIndex, playable, inputIndex);
playable.SetInputWeight(inputIndex, weight);
}
public static void DisconnectInput<U>(this U playable, int inputPort)
where U : struct, IPlayable
{
playable.GetGraph().Disconnect(playable, inputPort);
}
public static int AddInput<U, V>(this U playable, V sourcePlayable, int sourceOutputIndex, float weight = 0.0f)
where U : struct, IPlayable
where V : struct, IPlayable
{
var inputIndex = playable.GetInputCount();
playable.SetInputCount(inputIndex + 1);
playable.ConnectInput(inputIndex, sourcePlayable, sourceOutputIndex, weight);
return inputIndex;
}
[Obsolete("SetDelay is obsolete; use a custom ScriptPlayable to implement this feature", false)]
public static void SetDelay<U>(this U playable, double delay)
where U : struct, IPlayable
{
playable.GetHandle().SetDelay(delay);
}
[Obsolete("GetDelay is obsolete; use a custom ScriptPlayable to implement this feature", false)]
public static double GetDelay<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetDelay();
}
[Obsolete("IsDelayed is obsolete; use a custom ScriptPlayable to implement this feature", false)]
public static bool IsDelayed<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().IsDelayed();
}
public static void SetLeadTime<U>(this U playable, float value)
where U : struct, IPlayable
{
playable.GetHandle().SetLeadTime(value);
}
public static float GetLeadTime<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetLeadTime();
}
public static PlayableTraversalMode GetTraversalMode<U>(this U playable)
where U : struct, IPlayable
{
return playable.GetHandle().GetTraversalMode();
}
public static void SetTraversalMode<U>(this U playable, PlayableTraversalMode mode)
where U : struct, IPlayable
{
playable.GetHandle().SetTraversalMode(mode);
}
internal static DirectorWrapMode GetTimeWrapMode<U>(this U playable) where U : struct, IPlayable
{
return playable.GetHandle().GetTimeWrapMode();
}
internal static void SetTimeWrapMode<U>(this U playable, DirectorWrapMode value) where U : struct, IPlayable
{
playable.GetHandle().SetTimeWrapMode(value);
}
internal static int GetOutputPortFromInputConnection<U>(this U playable, int inputIndex)
where U : struct, IPlayable
{
return playable.GetHandle().GetOutputPortFromInputConnection(inputIndex);
}
internal static int GetInputPortFromOutputConnection<U>(this U playable, int outputIndex)
where U : struct, IPlayable
{
return playable.GetHandle().GetInputPortFromOutputConnection(outputIndex);
}
}
}
| UnityCsReference/Runtime/Export/Director/PlayableExtensions.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/Director/PlayableExtensions.cs",
"repo_id": "UnityCsReference",
"token_count": 4583
} | 543 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using Unity.Content;
using Unity.Jobs;
using UnityEngine.Bindings;
using UnityEngine.Scripting;
namespace Unity.IO.Archive
{
[RequiredByNativeCode]
public enum ArchiveStatus
{
InProgress,
Complete,
Failed
}
[NativeHeader("Runtime/VirtualFileSystem/ArchiveFileSystem/ArchiveFileHandle.h")]
[RequiredByNativeCode]
public struct ArchiveFileInfo
{
public string Filename;
public ulong FileSize;
}
[NativeHeader("Runtime/VirtualFileSystem/ArchiveFileSystem/ArchiveFileHandle.h")]
[RequiredByNativeCode]
public struct ArchiveHandle
{
internal UInt64 Handle;
public ArchiveStatus Status
{
get
{
ThrowIfInvalid();
return ArchiveFileInterface.Archive_GetStatus(this);
}
}
public JobHandle JobHandle
{
get
{
ThrowIfInvalid();
return ArchiveFileInterface.Archive_GetJobHandle(this);
}
}
public JobHandle Unmount()
{
ThrowIfInvalid();
return ArchiveFileInterface.Archive_UnmountAsync(this);
}
void ThrowIfInvalid()
{
if (!ArchiveFileInterface.Archive_IsValid(this))
throw new InvalidOperationException("The archive has already been unmounted.");
}
public string GetMountPath()
{
ThrowIfInvalid();
return ArchiveFileInterface.Archive_GetMountPath(this);
}
public UnityEngine.CompressionType Compression
{
get
{
ThrowIfInvalid();
return ArchiveFileInterface.Archive_GetCompression(this);
}
}
public bool IsStreamed
{
get
{
ThrowIfInvalid();
return ArchiveFileInterface.Archive_IsStreamed(this);
}
}
public ArchiveFileInfo[] GetFileInfo()
{
ThrowIfInvalid();
return ArchiveFileInterface.Archive_GetFileInfo(this);
}
}
[RequiredByNativeCode]
[NativeHeader("Runtime/VirtualFileSystem/ArchiveFileSystem/ArchiveFileHandle.h")]
[StaticAccessor("GetManagedArchiveSystem()", StaticAccessorType.Dot)]
public static class ArchiveFileInterface
{
public static extern ArchiveHandle MountAsync(ContentNamespace namespaceId, string filePath, string prefix);
public static extern ArchiveHandle[] GetMountedArchives(ContentNamespace namespaceId);
internal static extern ArchiveStatus Archive_GetStatus(ArchiveHandle handle);
internal static extern JobHandle Archive_GetJobHandle(ArchiveHandle handle);
internal static extern bool Archive_IsValid(ArchiveHandle handle);
internal static extern JobHandle Archive_UnmountAsync(ArchiveHandle handle);
internal static extern string Archive_GetMountPath(ArchiveHandle handle);
internal static extern UnityEngine.CompressionType Archive_GetCompression(ArchiveHandle handle);
internal static extern bool Archive_IsStreamed(ArchiveHandle handle);
internal static extern ArchiveFileInfo[] Archive_GetFileInfo(ArchiveHandle handle);
}
}
| UnityCsReference/Runtime/Export/File/ArchiveFile.bindings.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/File/ArchiveFile.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 1438
} | 544 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Globalization;
using System.Runtime.CompilerServices;
namespace UnityEngine
{
// Representation of 2D rays.
public partial struct Ray2D : IFormattable
{
private Vector2 m_Origin;
private Vector2 m_Direction;
// Creates a ray starting at /origin/ along /direction/.
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public Ray2D(Vector2 origin, Vector2 direction) { m_Origin = origin; m_Direction = direction.normalized; }
// The origin point of the ray.
public Vector2 origin
{
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)] get { return m_Origin; }
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)] set { m_Origin = value; }
}
// The direction of the ray.
public Vector2 direction
{
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)] get { return m_Direction; }
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)] set { m_Direction = value.normalized; }
}
// Returns a point at /distance/ units along the ray.
public Vector2 GetPoint(float distance)
{
return m_Origin + m_Direction * distance;
}
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public override string ToString()
{
return ToString(null, null);
}
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public string ToString(string format)
{
return ToString(format, null);
}
[MethodImpl(MethodImplOptionsEx.AggressiveInlining)]
public string ToString(string format, IFormatProvider formatProvider)
{
if (string.IsNullOrEmpty(format))
format = "F2";
if (formatProvider == null)
formatProvider = CultureInfo.InvariantCulture.NumberFormat;
return UnityString.Format("Origin: {0}, Dir: {1}", m_Origin.ToString(format, formatProvider), m_Direction.ToString(format, formatProvider));
}
}
}
| UnityCsReference/Runtime/Export/Geometry/Ray2D.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/Geometry/Ray2D.cs",
"repo_id": "UnityCsReference",
"token_count": 902
} | 545 |
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using UnityEngine.Bindings;
using UnityEngine.Scripting;
using UnityEngine.Rendering;
namespace UnityEngine
{
[NativeHeader("Runtime/Camera/OcclusionPortal.h")]
public sealed partial class OcclusionPortal : Component
{
[NativeProperty("IsOpen")] public extern bool open { get; set; }
}
[NativeHeader("Runtime/Camera/OcclusionArea.h")]
public sealed partial class OcclusionArea : Component
{
public extern Vector3 center { get; set; }
public extern Vector3 size { get; set; }
}
[NativeHeader("Runtime/Camera/Flare.h")]
public sealed partial class Flare : Object
{
public Flare()
{
Internal_Create(this);
}
extern static void Internal_Create([Writable] Flare self);
}
[NativeHeader("Runtime/Camera/Flare.h")]
public sealed partial class LensFlare : Behaviour
{
extern public float brightness { get; set; }
extern public float fadeSpeed { get; set; }
extern public Color color { get; set; }
extern public Flare flare { get; set; }
}
[NativeHeader("Runtime/Camera/Projector.h")]
public sealed partial class Projector : Behaviour
{
extern public float nearClipPlane { get; set; }
extern public float farClipPlane { get; set; }
extern public float fieldOfView { get; set; }
extern public float aspectRatio { get; set; }
extern public bool orthographic { get; set; }
extern public float orthographicSize { get; set; }
extern public int ignoreLayers { get; set; }
extern public Material material { get; set; }
}
[NativeHeader("Runtime/Camera/SharedLightData.h")]
public struct LightBakingOutput
{
public int probeOcclusionLightIndex;
public int occlusionMaskChannel;
[NativeName("lightmapBakeMode.lightmapBakeType")]
public LightmapBakeType lightmapBakeType;
[NativeName("lightmapBakeMode.mixedLightingMode")]
public MixedLightingMode mixedLightingMode;
public bool isBaked;
}
[NativeHeader("Runtime/Camera/SharedLightData.h")]
public enum LightShadowCasterMode
{
Default,
NonLightmappedOnly,
Everything
}
[RequireComponent(typeof(Transform))]
[NativeHeader("Runtime/Camera/Light.h")]
public sealed partial class Light : Behaviour
{
[NativeProperty("LightType")] extern public LightType type { get; set; }
[System.Obsolete("This property has been deprecated. Use Light.type instead.")] public LightShape shape { get; set; }
extern public float spotAngle { get; set; }
extern public float innerSpotAngle { get; set; }
extern public Color color { get; set; }
extern public float colorTemperature { get; set; }
extern public bool useColorTemperature { get; set; }
extern public float intensity { get; set; }
extern public float bounceIntensity { get; set; }
extern public LightUnit lightUnit { get; set; }
extern public float luxAtDistance { get; set; }
extern public bool enableSpotReflector { get; set; }
extern public bool useBoundingSphereOverride { get; set; }
extern public Vector4 boundingSphereOverride { get; set; }
extern public bool useViewFrustumForShadowCasterCull { get; set; }
extern public bool forceVisible { get; set; }
extern public int shadowCustomResolution { get; set; }
extern public float shadowBias { get; set; }
extern public float shadowNormalBias { get; set; }
extern public float shadowNearPlane { get; set; }
extern public bool useShadowMatrixOverride { get; set; }
extern public Matrix4x4 shadowMatrixOverride { get; set; }
extern public float range { get; set; }
extern public float dilatedRange { get; }
extern public Flare flare { get; set; }
extern public LightBakingOutput bakingOutput { get; set; }
extern public int cullingMask { get; set; }
extern public int renderingLayerMask { get; set; }
extern public LightShadowCasterMode lightShadowCasterMode { get; set; }
extern public float shadowRadius { get; set; }
extern public float shadowAngle { get; set; }
}
[NativeHeader("Runtime/Camera/Skybox.h")]
public sealed partial class Skybox : Behaviour
{
extern public Material material { get; set; }
}
[RequireComponent(typeof(Transform))]
[NativeHeader("Runtime/Graphics/Mesh/MeshFilter.h")]
public sealed partial class MeshFilter : Component
{
[RequiredByNativeCode] // MeshFilter is used in the VR Splash screen.
private void DontStripMeshFilter() {}
extern public Mesh sharedMesh { get; set; }
extern public Mesh mesh {[NativeName("GetInstantiatedMeshFromScript")] get; [NativeName("SetInstantiatedMesh")] set; }
}
[RequireComponent(typeof(Transform))]
[NativeHeader("Runtime/Camera/HaloManager.h")]
internal sealed partial class Halo : Behaviour
{
}
}
| UnityCsReference/Runtime/Export/Graphics/GraphicsComponents.bindings.cs/0 | {
"file_path": "UnityCsReference/Runtime/Export/Graphics/GraphicsComponents.bindings.cs",
"repo_id": "UnityCsReference",
"token_count": 2062
} | 546 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.