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; using System.Collections.Generic; using System.Security; using UnityEngine.Scripting; using UnityEngineInternal; using UnityEngine.Bindings; namespace UnityEngine { // Basic layout element [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal class GUILayoutEntry { // The min and max sizes. Used during calculations... public float minWidth, maxWidth, minHeight, maxHeight; // The rectangle that this element ends up having public Rect rect = new Rect(0, 0, 0, 0); // Can this element stretch? public int stretchWidth, stretchHeight; public bool consideredForMargin = true; // The style to use. GUIStyle m_Style = GUIStyle.none; public GUIStyle style { get { return m_Style; } set { m_Style = value; ApplyStyleSettings(value); } } internal static Rect kDummyRect = new Rect(0, 0, 1, 1); // The margins of this element. public virtual int marginLeft => style.margin.left; public virtual int marginRight => style.margin.right; public virtual int marginTop => style.margin.top; public virtual int marginBottom => style.margin.bottom; public int marginHorizontal => marginLeft + marginRight; public int marginVertical => marginBottom + marginTop; public GUILayoutEntry(float _minWidth, float _maxWidth, float _minHeight, float _maxHeight, GUIStyle _style) { minWidth = _minWidth; maxWidth = _maxWidth; minHeight = _minHeight; maxHeight = _maxHeight; if (_style == null) _style = GUIStyle.none; style = _style; } public GUILayoutEntry(float _minWidth, float _maxWidth, float _minHeight, float _maxHeight, GUIStyle _style, GUILayoutOption[] options) { minWidth = _minWidth; maxWidth = _maxWidth; minHeight = _minHeight; maxHeight = _maxHeight; style = _style; ApplyOptions(options); } public virtual void CalcWidth() {} public virtual void CalcHeight() {} public virtual void SetHorizontal(float x, float width) { rect.x = x; rect.width = width; } public virtual void SetVertical(float y, float height) { rect.y = y; rect.height = height; } protected virtual void ApplyStyleSettings(GUIStyle style) { stretchWidth = (style.fixedWidth == 0 && style.stretchWidth) ? 1 : 0; stretchHeight = (style.fixedHeight == 0 && style.stretchHeight) ? 1 : 0; m_Style = style; } public virtual void ApplyOptions(GUILayoutOption[] options) { if (options == null) return; foreach (GUILayoutOption i in options) { switch (i.type) { case GUILayoutOption.Type.fixedWidth: minWidth = maxWidth = (float)i.value; stretchWidth = 0; break; case GUILayoutOption.Type.fixedHeight: minHeight = maxHeight = (float)i.value; stretchHeight = 0; break; case GUILayoutOption.Type.minWidth: minWidth = (float)i.value; if (maxWidth < minWidth) maxWidth = minWidth; break; case GUILayoutOption.Type.maxWidth: maxWidth = (float)i.value; if (minWidth > maxWidth) minWidth = maxWidth; stretchWidth = 0; break; case GUILayoutOption.Type.minHeight: minHeight = (float)i.value; if (maxHeight < minHeight) maxHeight = minHeight; break; case GUILayoutOption.Type.maxHeight: maxHeight = (float)i.value; if (minHeight > maxHeight) minHeight = maxHeight; stretchHeight = 0; break; case GUILayoutOption.Type.stretchWidth: stretchWidth = (int)i.value; break; case GUILayoutOption.Type.stretchHeight: stretchHeight = (int)i.value; break; } } if (maxWidth != 0 && maxWidth < minWidth) maxWidth = minWidth; if (maxHeight != 0 && maxHeight < minHeight) maxHeight = minHeight; } protected static int indent = 0; public override string ToString() { string space = ""; for (int i = 0; i < indent; i++) space += " "; return space + UnityString.Format("{1}-{0} (x:{2}-{3}, y:{4}-{5})", style != null ? style.name : "NULL", GetType(), rect.x, rect.xMax, rect.y, rect.yMax) + " - W: " + minWidth + "-" + maxWidth + (stretchWidth != 0 ? "+" : "") + ", H: " + minHeight + "-" + maxHeight + (stretchHeight != 0 ? "+" : ""); } } // Layouter that makes elements which sizes will always conform to a specific aspect ratio. internal sealed class GUIAspectSizer : GUILayoutEntry { float aspect; public GUIAspectSizer(float aspect, GUILayoutOption[] options) : base(0, 0, 0, 0, GUIStyle.none) { this.aspect = aspect; ApplyOptions(options); } public override void CalcHeight() { minHeight = maxHeight = rect.width / aspect; } } // Will layout a button grid so it can fit within the given rect. // *undocumented* internal sealed class GUIGridSizer : GUILayoutEntry { // Helper: Create the layout group and scale it to fit public static Rect GetRect(GUIContent[] contents, int xCount, GUIStyle style, GUILayoutOption[] options) { Rect r = new Rect(0, 0, 0, 0); switch (Event.current.type) { case EventType.Layout: GUILayoutUtility.current.topLevel.Add(new GUIGridSizer(contents, xCount, style, options)); break; case EventType.Used: return kDummyRect; default: r = GUILayoutUtility.current.topLevel.GetNext().rect; break; } return r; } readonly int m_Count; readonly int m_XCount; readonly float m_MinButtonWidth = -1; readonly float m_MaxButtonWidth = -1; readonly float m_MinButtonHeight = -1; readonly float m_MaxButtonHeight = -1; private GUIGridSizer(GUIContent[] contents, int xCount, GUIStyle buttonStyle, GUILayoutOption[] options) : base(0, 0, 0, 0, GUIStyle.none) { m_Count = contents.Length; m_XCount = xCount; // Most settings comes from the button style (can we stretch, etc). Hence, I apply the style here ApplyStyleSettings(buttonStyle); // We can have custom options coming from userland. We apply this last so it overrides ApplyOptions(options); if (xCount == 0 || contents.Length == 0) return; // internal horizontal spacing float totalHorizSpacing = Mathf.Max(buttonStyle.margin.left, buttonStyle.margin.right) * (m_XCount - 1); // Debug.Log (String.Format ("margins: {0}, {1} totalHoriz: {2}", buttonStyle.margin.left, buttonStyle.margin.right, totalHorizSpacing)); // internal horizontal margins float totalVerticalSpacing = Mathf.Max(buttonStyle.margin.top, buttonStyle.margin.bottom) * (rows - 1); // Handle fixedSize buttons if (buttonStyle.fixedWidth != 0) m_MinButtonWidth = m_MaxButtonWidth = buttonStyle.fixedWidth; // Debug.Log ("buttonStyle.fixedHeight " + buttonStyle.fixedHeight); if (buttonStyle.fixedHeight != 0) m_MinButtonHeight = m_MaxButtonHeight = buttonStyle.fixedHeight; // Apply GUILayout.Width/Height/whatever properties. if (m_MinButtonWidth == -1) { if (minWidth != 0) m_MinButtonWidth = (minWidth - totalHorizSpacing) / m_XCount; if (maxWidth != 0) m_MaxButtonWidth = (maxWidth - totalHorizSpacing) / m_XCount; } if (m_MinButtonHeight == -1) { if (minHeight != 0) m_MinButtonHeight = (minHeight - totalVerticalSpacing) / rows; if (maxHeight != 0) m_MaxButtonHeight = (maxHeight - totalVerticalSpacing) / rows; } // Debug.Log (String.Format ("minButtonWidth {0}, maxButtonWidth {1}, minButtonHeight {2}, maxButtonHeight{3}", minButtonWidth, maxButtonWidth, minButtonHeight, maxButtonHeight)); // if anything is left unknown, we need to iterate over all elements and figure out the sizes. if (m_MinButtonHeight == -1 || m_MaxButtonHeight == -1 || m_MinButtonWidth == -1 || m_MaxButtonWidth == -1) { // figure out the max size. Since the buttons are in a grid, the max size determines stuff. float calcHeight = 0, calcWidth = 0; foreach (GUIContent i in contents) { Vector2 size = buttonStyle.CalcSize(i); calcWidth = Mathf.Max(calcWidth, size.x); calcHeight = Mathf.Max(calcHeight, size.y); } // If the user didn't supply minWidth, we need to calculate that if (m_MinButtonWidth == -1) { // if the user has supplied a maxButtonWidth, the buttons can never get larger. if (m_MaxButtonWidth != -1) m_MinButtonWidth = Mathf.Min(calcWidth, m_MaxButtonWidth); else m_MinButtonWidth = calcWidth; } // If the user didn't supply maxWidth, we need to calculate that if (m_MaxButtonWidth == -1) { // if the user has supplied a minButtonWidth, the buttons can never get smaller. if (m_MinButtonWidth != -1) m_MaxButtonWidth = Mathf.Max(calcWidth, m_MinButtonWidth); else m_MaxButtonWidth = calcWidth; } // If the user didn't supply minWidth, we need to calculate that if (m_MinButtonHeight == -1) { // if the user has supplied a maxButtonWidth, the buttons can never get larger. if (m_MaxButtonHeight != -1) m_MinButtonHeight = Mathf.Min(calcHeight, m_MaxButtonHeight); else m_MinButtonHeight = calcHeight; } // If the user didn't supply maxWidth, we need to calculate that if (m_MaxButtonHeight == -1) { // if the user has supplied a minButtonWidth, the buttons can never get smaller. if (m_MinButtonHeight != -1) maxHeight = Mathf.Max(maxHeight, m_MinButtonHeight); m_MaxButtonHeight = maxHeight; } } // We now know the button sizes. Calculate min & max values from that minWidth = m_MinButtonWidth * m_XCount + totalHorizSpacing; maxWidth = m_MaxButtonWidth * m_XCount + totalHorizSpacing; minHeight = m_MinButtonHeight * rows + totalVerticalSpacing; maxHeight = m_MaxButtonHeight * rows + totalVerticalSpacing; // Debug.Log (String.Format ("minWidth {0}, maxWidth {1}, minHeight {2}, maxHeight{3}", minWidth, maxWidth, minHeight, maxHeight)); } int rows { get { int rows = m_Count / m_XCount; if (m_Count % m_XCount != 0) rows++; return rows; } } } // Class that can handle word-wrap sizing. this is specialcased as setting width can make the text wordwrap, which would then increase height... internal sealed class GUIWordWrapSizer : GUILayoutEntry { readonly GUIContent m_Content; // We need to differentiate between min & maxHeight we calculate for ourselves and one that is forced by the user // (When inside a scrollview, we can be told to layout twice, so we need to know the difference) readonly float m_ForcedMinHeight; readonly float m_ForcedMaxHeight; public GUIWordWrapSizer(GUIStyle style, GUIContent content, GUILayoutOption[] options) : base(0, 0, 0, 0, style) { m_Content = new GUIContent(content); ApplyOptions(options); m_ForcedMinHeight = minHeight; m_ForcedMaxHeight = maxHeight; } public override void CalcWidth() { if (minWidth == 0 || maxWidth == 0) { float _minWidth, _maxWidth; style.CalcMinMaxWidth(m_Content, out _minWidth, out _maxWidth); // Further layout calculations might round this value to nearest which could force the text over several lines // when rounding down. Make sure to actual give enough space by always rounding up (case 1047812). _minWidth = Mathf.Ceil(_minWidth); _maxWidth = Mathf.Ceil(_maxWidth); if (minWidth == 0) minWidth = _minWidth; if (maxWidth == 0) maxWidth = _maxWidth; } } public override void CalcHeight() { // When inside a scrollview, this can get called twice (as vertical scrollbar reduces width, which causes a reflow). // Hence, we need to use the separately cached values for min & maxHeight coming from the user... if (m_ForcedMinHeight == 0 || m_ForcedMaxHeight == 0) { float height = style.CalcHeight(m_Content, rect.width); if (m_ForcedMinHeight == 0) minHeight = height; else minHeight = m_ForcedMinHeight; if (m_ForcedMaxHeight == 0) maxHeight = height; else maxHeight = m_ForcedMaxHeight; } } } }
UnityCsReference/Modules/IMGUI/LayoutEntry.cs/0
{ "file_path": "UnityCsReference/Modules/IMGUI/LayoutEntry.cs", "repo_id": "UnityCsReference", "token_count": 6863 }
362
// 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; namespace UnityEngine.InputForUI; /// <summary> /// Beware values determinate order of some events (pointer events). /// </summary> [VisibleToOtherModules("UnityEngine.UIElementsModule")] internal enum EventSource { /// <summary> /// Unspecified source, can be any device or even an event generated/simulated by code. /// </summary> Unspecified = 0, /// <summary> /// Event was generated from a keyboard interaction. /// </summary> Keyboard = 1, /// <summary> /// Event was generated from a gamepad interaction. /// </summary> Gamepad = 2, /// <summary> /// Event was generated from a mouse interaction. /// </summary> Mouse = 3, /// <summary> /// Event was generated from a pen interaction. /// </summary> Pen = 4, /// <summary> /// Event was generated from a touch interaction. /// </summary> Touch = 5, }
UnityCsReference/Modules/InputForUI/Events/EventSource.cs/0
{ "file_path": "UnityCsReference/Modules/InputForUI/Events/EventSource.cs", "repo_id": "UnityCsReference", "token_count": 351 }
363
// 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.Collections.Generic; using System.Reflection; using UnityEngine.Scripting; using UnityEngine; namespace UnityEngine { internal class SendMouseEvents { struct HitInfo { public GameObject target; public Camera camera; public void SendMessage(string name) { target.SendMessage(name, null, SendMessageOptions.DontRequireReceiver); } public static implicit operator bool(HitInfo exists) { return exists.target != null && exists.camera != null; } public static bool Compare(HitInfo lhs, HitInfo rhs) { return lhs.target == rhs.target && lhs.camera == rhs.camera; } } private const int m_HitIndexGUI = 0; private const int m_HitIndexPhysics3D = 1; private const int m_HitIndexPhysics2D = 2; private static bool s_MouseUsed = false; static readonly HitInfo[] m_LastHit = { new HitInfo(), new HitInfo(), new HitInfo() }; static readonly HitInfo[] m_MouseDownHit = { new HitInfo(), new HitInfo(), new HitInfo() }; static readonly HitInfo[] m_CurrentHit = { new HitInfo(), new HitInfo(), new HitInfo() }; static Camera[] m_Cameras; public enum LeftMouseButtonState { NotPressed = 0, Pressed = 1, PressedThisFrame = 2, } public static Func<KeyValuePair<int, Vector2>> s_GetMouseState; private static Vector2 s_MousePosition; private static bool s_MouseButtonPressedThisFrame; private static bool s_MouseButtonIsPressed; private static void UpdateMouse() { if (s_GetMouseState != null) { // Allow handler to override input from UnityEngine.Input. // Tuple value would be more elegant here but is .NET 5+. var state = s_GetMouseState(); s_MousePosition = state.Value; s_MouseButtonPressedThisFrame = (state.Key == (int)LeftMouseButtonState.PressedThisFrame); s_MouseButtonIsPressed = state.Key != (int)LeftMouseButtonState.NotPressed; } else if (!UnityEngine.Input.CheckDisabled()) { s_MousePosition = Input.mousePosition; s_MouseButtonPressedThisFrame = Input.GetMouseButtonDown(0); s_MouseButtonIsPressed = Input.GetMouseButton(0); } else { s_MousePosition = default; s_MouseButtonPressedThisFrame = default; s_MouseButtonIsPressed = default; } } [RequiredByNativeCode] static void SetMouseMoved() { s_MouseUsed = true; } [RequiredByNativeCode] static void DoSendMouseEvents(int skipRTCameras) { UpdateMouse(); var mousePosition = s_MousePosition; int camerasCount = Camera.allCamerasCount; if (m_Cameras == null || m_Cameras.Length != camerasCount) m_Cameras = new Camera[camerasCount]; // Fetch all cameras. Camera.GetAllCameras(m_Cameras); // Clear the HitInfos from last time for (var hitIndex = 0; hitIndex < m_CurrentHit.Length; ++hitIndex) m_CurrentHit[hitIndex] = new HitInfo(); // If UnityGUI has the mouse over, we simply don't do any mouse hit detection. // That way, it will appear as if the mouse has missed everything. if (!s_MouseUsed) { foreach (var camera in m_Cameras) { // we do not want to check cameras that are rendering to textures, starting with 4.0 if (camera == null || skipRTCameras != 0 && camera.targetTexture != null) continue; int displayIndex = camera.targetDisplay; var eventPosition = Display.RelativeMouseAt(mousePosition); if (eventPosition != Vector3.zero) { // We support multiple display and display identification based on event position. int eventDisplayIndex = (int)eventPosition.z; // Discard events that are not part of this display so the user does not interact with multiple displays at once. if (eventDisplayIndex != displayIndex) continue; // Multiple display support only when not the main display. For display 0 the reported // resolution is always the desktop resolution since it's part of the display API, // so we use the standard non multiple display method. float w = Screen.width; float h = Screen.height; if (displayIndex > 0 && displayIndex < Display.displays.Length) { w = Display.displays[displayIndex].systemWidth; h = Display.displays[displayIndex].systemHeight; } Vector2 pos = new Vector2(eventPosition.x / w, eventPosition.y / h); // If the mouse is outside the display bounds, do nothing if (pos.x < 0f || pos.x > 1f || pos.y < 0f || pos.y > 1f) continue; } else { // The multiple display system is not supported on all platforms, when it is not supported the returned position // will be all zeros so when the returned index is 0 we will default to the mouse position to be safe. eventPosition = mousePosition; if (Display.activeEditorGameViewTarget != displayIndex) continue; eventPosition.z = Display.activeEditorGameViewTarget ; } // Is the mouse inside the cameras viewport? var rect = camera.pixelRect; if (!rect.Contains(eventPosition)) continue; // There is no need to continue if the camera shouldn't be sending out events if (camera.eventMask == 0) continue; // Calculate common physics projection and distance. var screenProjectionRay = camera.ScreenPointToRay(eventPosition); var projectionDirection = screenProjectionRay.direction.z; var distanceToClipPlane = Mathf.Approximately(0.0f, projectionDirection) ? Mathf.Infinity : Mathf.Abs((camera.farClipPlane - camera.nearClipPlane) / projectionDirection); // Did we hit any 3D colliders? var hit3D = CameraRaycastHelper.RaycastTry(camera, screenProjectionRay, distanceToClipPlane, camera.cullingMask & camera.eventMask); if (hit3D != null) { m_CurrentHit[m_HitIndexPhysics3D].target = hit3D; m_CurrentHit[m_HitIndexPhysics3D].camera = camera; } // We did not hit anything with a raycast from this camera. But our camera // clears the screen and renders on top of whatever was below, thus making things // rendered before invisible. So clear any previous hit we have found. else if (camera.clearFlags == CameraClearFlags.Skybox || camera.clearFlags == CameraClearFlags.SolidColor) { m_CurrentHit[m_HitIndexPhysics3D].target = null; m_CurrentHit[m_HitIndexPhysics3D].camera = null; } // Did we hit any 2D colliders? var hit2D = CameraRaycastHelper.RaycastTry2D(camera, screenProjectionRay, distanceToClipPlane, camera.cullingMask & camera.eventMask); if (hit2D != null) { m_CurrentHit[m_HitIndexPhysics2D].target = hit2D; m_CurrentHit[m_HitIndexPhysics2D].camera = camera; } // We did not hit anything with a raycast from this camera. But our camera // clears the screen and renders on top of whatever was below, thus making things // rendered before invisible. So clear any previous hit we have found. else if (camera.clearFlags == CameraClearFlags.Skybox || camera.clearFlags == CameraClearFlags.SolidColor) { m_CurrentHit[m_HitIndexPhysics2D].target = null; m_CurrentHit[m_HitIndexPhysics2D].camera = null; } } } // Send hit events. for (var hitIndex = 0; hitIndex < m_CurrentHit.Length; ++hitIndex) SendEvents(hitIndex, m_CurrentHit[hitIndex]); s_MouseUsed = false; } /// <summary> /// Old-style mouse events used prior to the new event system of 4.2. /// </summary> static void SendEvents(int i, HitInfo hit) { // Handle MouseDown, MouseDrag, MouseUp bool mouseDownThisFrame = s_MouseButtonPressedThisFrame; bool mousePressed = s_MouseButtonIsPressed; if (mouseDownThisFrame) { if (hit) { m_MouseDownHit[i] = hit; m_MouseDownHit[i].SendMessage("OnMouseDown"); } } else if (!mousePressed) { if (m_MouseDownHit[i]) { // For button like behavior only fire this event if same as on MouseDown if (HitInfo.Compare(hit, m_MouseDownHit[i])) m_MouseDownHit[i].SendMessage("OnMouseUpAsButton"); // For backwards compatibility we keep the event name OnMouseUp m_MouseDownHit[i].SendMessage("OnMouseUp"); m_MouseDownHit[i] = new HitInfo(); } } else if (m_MouseDownHit[i]) { m_MouseDownHit[i].SendMessage("OnMouseDrag"); } // Handle MouseOver, MouseEnter, MouseExit if (HitInfo.Compare(hit, m_LastHit[i])) { if (hit) hit.SendMessage("OnMouseOver"); } else { if (m_LastHit[i]) { m_LastHit[i].SendMessage("OnMouseExit"); } if (hit) { hit.SendMessage("OnMouseEnter"); hit.SendMessage("OnMouseOver"); } } m_LastHit[i] = hit; } } }
UnityCsReference/Modules/InputLegacy/MouseEvents.cs/0
{ "file_path": "UnityCsReference/Modules/InputLegacy/MouseEvents.cs", "repo_id": "UnityCsReference", "token_count": 5743 }
364
// 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.Licensing.UI.Events.Text; namespace UnityEditor.Licensing.UI.Events.Buttons; sealed class ManageLicenseButton : TemplateEventsButton { INativeApiWrapper m_NativeApiWrapper; Action m_CloseAction; public ManageLicenseButton(Action closeAction, Action additionalClickAction, INativeApiWrapper nativeApiWrapper) : base(LicenseTrStrings.BtnManageLicense, additionalClickAction) { m_NativeApiWrapper = nativeApiWrapper; m_CloseAction = closeAction; } protected override void Click() { m_CloseAction?.Invoke(); m_NativeApiWrapper.OpenHubLicenseManagementWindow(); } }
UnityCsReference/Modules/Licensing/UI/Events/Buttons/ManageLicenseButton.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Events/Buttons/ManageLicenseButton.cs", "repo_id": "UnityCsReference", "token_count": 288 }
365
// 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.Licensing.UI.Helper; interface ILicenseLogger { const string tag = "License"; public void DebugLogNoStackTrace(string message, LogType logType = LogType.Log, string tag = tag); public void LogError(string message); }
UnityCsReference/Modules/Licensing/UI/Helper/ILicenseLogger.cs/0
{ "file_path": "UnityCsReference/Modules/Licensing/UI/Helper/ILicenseLogger.cs", "repo_id": "UnityCsReference", "token_count": 130 }
366
// 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 System.Runtime.CompilerServices; using UnityEngine.Scripting.APIUpdating; using UnityEngine.Scripting; namespace UnityEngine { [NativeType(Header = "Modules/Multiplayer/MultiplayerRolesData.h")] internal class MultiplayerRolesData : Component { } }
UnityCsReference/Modules/Multiplayer/Managed/MultiplayerRolesData.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Multiplayer/Managed/MultiplayerRolesData.bindings.cs", "repo_id": "UnityCsReference", "token_count": 141 }
367
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager { public enum ErrorCode { Unknown, NotFound, Forbidden, InvalidParameter, Conflict, AggregateError, // NOTE: Error code success from the C++ API is not defined here // since we never create errors for successful requests } }
UnityCsReference/Modules/PackageManager/Editor/Managed/ErrorCode.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/ErrorCode.cs", "repo_id": "UnityCsReference", "token_count": 179 }
368
// 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.PackageManager { internal static class PackageValidation { private static readonly Regex s_CompleteNameRegEx = new Regex(@"^([a-z\d][a-z\d-._]{0,213})$"); private static readonly Regex s_NameRegEx = new Regex(@"^([a-z\d][a-z\d\-\._]{0,112})$"); private static readonly Regex s_OrganizationNameRegEx = new Regex(@"^([a-z\d][a-z\d\-_]{0,99})$"); private static readonly Regex s_AllowedSemverRegEx = new Regex(@"^(?<major>0|[1-9]\d*)\.(?<minor>0|[1-9]\d*)\.(?<patch>0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"); private static readonly Regex s_UnityMajorVersionRegEx = new Regex(@"^([1-9][0-9]{3})$"); private static readonly Regex s_UnityMinorVersionRegEx = new Regex(@"^([1-9])$"); private static readonly Regex s_UnityReleaseVersionRegEx = new Regex(@"^(0|[1-9]\d*)([abfp])(0|[1-9]\d*)$"); public static bool ValidateCompleteName(string completeName) { return !string.IsNullOrEmpty(completeName) && s_CompleteNameRegEx.IsMatch(completeName); } public static bool ValidateName(string name) { return !string.IsNullOrEmpty(name) && s_NameRegEx.IsMatch(name); } public static bool ValidateOrganizationName(string organizationName) { return !string.IsNullOrEmpty(organizationName) && s_OrganizationNameRegEx.IsMatch(organizationName); } public static bool ValidateVersion(string version) { return ValidateVersion(version, out _, out _, out _); } public static bool ValidateVersion(string version, out string major, out string minor, out string patch) { major = string.Empty; minor = string.Empty; patch = string.Empty; var match = s_AllowedSemverRegEx.Match(version); if (!match.Success) return false; major = match.Groups["major"].Value; minor = match.Groups["minor"].Value; patch = match.Groups["patch"].Value; return true; } public static bool ValidateUnityVersion(string version) { if (string.IsNullOrEmpty(version)) return false; var splitVersions = version.Split('.'); switch (splitVersions.Length) { case 2: return ValidateUnityVersion(splitVersions[0], splitVersions[1]); case 3: return ValidateUnityVersion(splitVersions[0], splitVersions[1], splitVersions[2]); default: return false; } } public static bool ValidateUnityVersion(string majorVersion, string minorVersion, string releaseVersion = null) { return !string.IsNullOrEmpty(majorVersion) && s_UnityMajorVersionRegEx.IsMatch(majorVersion) && !string.IsNullOrEmpty(minorVersion) && s_UnityMinorVersionRegEx.IsMatch(minorVersion) && (string.IsNullOrEmpty(releaseVersion) || s_UnityReleaseVersionRegEx.IsMatch(releaseVersion)); } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/PackageValidation.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/PackageValidation.cs", "repo_id": "UnityCsReference", "token_count": 1597 }
369
// 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; namespace UnityEditor.PackageManager.Requests { [Serializable] public sealed partial class PackRequest : Request<PackOperationResult> { private PackRequest() { } internal PackRequest(long operationId, NativeStatusCode initialStatus) : base(operationId, initialStatus) { } protected override PackOperationResult GetResult() { return GetOperationData(Id); } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/PackRequest.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Requests/PackRequest.cs", "repo_id": "UnityCsReference", "token_count": 256 }
370
// 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 RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; namespace UnityEditor.PackageManager { [Serializable] [RequiredByNativeCode] [StructLayout(LayoutKind.Sequential)] [NativeAsStruct] [NativeType(IntermediateScriptingStructName = "PackageManager_SearchResults")] internal sealed class SearchResults { [SerializeField] [NativeName("capabilities")] private SearchCapabilities m_Capabilities = new SearchCapabilities(); [SerializeField] [NativeName("packages")] private SearchResultEntry[] m_Packages; [SerializeField] [NativeName("total")] private ulong m_Total = 0; internal SearchResults() {} public ulong total { get { return m_Total; } } public SearchCapabilities capabilities { get { return m_Capabilities; } } public SearchResultEntry[] packages { get { return m_Packages; } } } }
UnityCsReference/Modules/PackageManager/Editor/Managed/Search/SearchResults.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManager/Editor/Managed/Search/SearchResults.cs", "repo_id": "UnityCsReference", "token_count": 551 }
371
// 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; namespace UnityEditor.PackageManager.UI { internal interface IPackageActionButton : IExtension { string text { get; set; } Texture2D icon { set; } string tooltip { get; set; } Action<PackageSelectionArgs> action { get; set; } IPackageActionDropdownItem AddDropdownItem(); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IPackageActionButton.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Extensions/Interfaces/IPackageActionButton.cs", "repo_id": "UnityCsReference", "token_count": 184 }
372
// 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.Analytics; namespace UnityEditor.PackageManager.UI.Internal { [AnalyticInfo(eventName: k_EventName, vendorKey: k_VendorKey)] internal class PackageCacheManagementAnalytics : IAnalytic { private const string k_EventName = "packageCacheManagementUserAction"; private const string k_VendorKey = "unity.package-manager-ui"; [Serializable] private class Data : IAnalytic.IData { public string action; public string type; public string[] old_path_statuses; public string[] new_path_statuses; } private Data m_Data; private PackageCacheManagementAnalytics(string action, string type, string[] oldPathStatuses, string[] newPathStatuses) { m_Data = new Data { action = action, type = type, old_path_statuses = oldPathStatuses, new_path_statuses = newPathStatuses }; } public bool TryGatherData(out IAnalytic.IData data, out Exception error) { data = m_Data; error = null; return data != null; } public static void SendAssetStoreEvent(string action, string[] oldPathStatuses, string[] newPathStatuses = null) { SendEvent(action, "AssetStore", oldPathStatuses, newPathStatuses); } public static void SendUpmEvent(string action, string[] oldPathStatuses, string[] newPathStatuses = null) { SendEvent(action, "UPM", oldPathStatuses, newPathStatuses); } private static void SendEvent(string action, string type, string[] oldPathStatuses, string[] newPathStatuses) { var editorAnalyticsProxy = ServicesContainer.instance.Resolve<IEditorAnalyticsProxy>(); editorAnalyticsProxy.SendAnalytic(new PackageCacheManagementAnalytics(action, type, oldPathStatuses, newPathStatuses)); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageCacheManagementAnalytics.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Analytics/PackageCacheManagementAnalytics.cs", "repo_id": "UnityCsReference", "token_count": 896 }
373
// 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 UnityEditor.PackageManager.UI.Internal { internal class AssetStorePackageFactory : Package.Factory { private readonly IUniqueIdMapper m_UniqueIdMapper; private readonly IUnityConnectProxy m_UnityConnect; private readonly IAssetStoreCache m_AssetStoreCache; private readonly IAssetStoreDownloadManager m_AssetStoreDownloadManager; private readonly IPackageDatabase m_PackageDatabase; private readonly IFetchStatusTracker m_FetchStatusTracker; private readonly IBackgroundFetchHandler m_BackgroundFetchHandler; public AssetStorePackageFactory(IUniqueIdMapper uniqueIdMapper, IUnityConnectProxy unityConnect, IAssetStoreCache assetStoreCache, IAssetStoreDownloadManager assetStoreDownloadManager, IPackageDatabase packageDatabase, IFetchStatusTracker fetchStatusTracker, IBackgroundFetchHandler backgroundFetchHandler) { m_UniqueIdMapper = RegisterDependency(uniqueIdMapper); m_UnityConnect = RegisterDependency(unityConnect); m_AssetStoreCache = RegisterDependency(assetStoreCache); m_AssetStoreDownloadManager = RegisterDependency(assetStoreDownloadManager); m_PackageDatabase = RegisterDependency(packageDatabase); m_FetchStatusTracker = RegisterDependency(fetchStatusTracker); m_BackgroundFetchHandler = RegisterDependency(backgroundFetchHandler); } public override void OnEnable() { m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange; m_AssetStoreCache.onLocalInfosChanged += OnLocalInfosChanged; m_AssetStoreCache.onPurchaseInfosChanged += OnPurchaseInfosChanged; m_AssetStoreCache.onProductInfoChanged += OnProductInfoChanged; m_AssetStoreCache.onUpdateInfosChanged += OnUpdateInfosChanged; m_AssetStoreCache.onImportedPackagesChanged += OnImportedPackagesChanged; m_AssetStoreDownloadManager.onDownloadProgress += OnDownloadProgress; m_AssetStoreDownloadManager.onDownloadFinalized += OnDownloadFinalized; m_AssetStoreDownloadManager.onDownloadError += OnDownloadError; m_AssetStoreDownloadManager.onDownloadStateChanged += OnDownloadStateChanged; m_AssetStoreDownloadManager.onBeforeDownloadStart += OnBeforeDownloadStart; m_FetchStatusTracker.onFetchStatusChanged += OnFetchStatusChanged; } public override void OnDisable() { m_UnityConnect.onUserLoginStateChange -= OnUserLoginStateChange; m_AssetStoreCache.onLocalInfosChanged -= OnLocalInfosChanged; m_AssetStoreCache.onPurchaseInfosChanged -= OnPurchaseInfosChanged; m_AssetStoreCache.onProductInfoChanged -= OnProductInfoChanged; m_AssetStoreCache.onUpdateInfosChanged -= OnUpdateInfosChanged; m_AssetStoreCache.onImportedPackagesChanged -= OnImportedPackagesChanged; m_AssetStoreDownloadManager.onDownloadProgress -= OnDownloadProgress; m_AssetStoreDownloadManager.onDownloadFinalized -= OnDownloadFinalized; m_AssetStoreDownloadManager.onDownloadError -= OnDownloadError; m_AssetStoreDownloadManager.onDownloadStateChanged -= OnDownloadStateChanged; m_AssetStoreDownloadManager.onBeforeDownloadStart -= OnBeforeDownloadStart; m_FetchStatusTracker.onFetchStatusChanged -= OnFetchStatusChanged; } private void OnUserLoginStateChange(bool userInfoReady, bool loggedIn) { if (loggedIn) return; m_AssetStoreCache.ClearOnlineCache(); m_FetchStatusTracker.ClearCache(); // We only regenerate and remove packages from the Asset Store that are of Legacy format. We handle the UPM format in UpmPackageFactory. var packagesToRemove = new List<IPackage>(); var packagesToRegenerate = new List<IPackage>(); foreach (var package in m_PackageDatabase.allPackages.Where(p => p.product != null && p.versions.Any(v => v.HasTag(PackageTag.LegacyFormat)))) { if (package.versions.Any(v => v.importedAssets?.Any() == true)) packagesToRegenerate.Add(package); else packagesToRemove.Add(package); } // We use `ToArray` here as m_PackageDatabase.UpdatePackages will modify the enumerable and throw an error if we don't if (packagesToRemove.Any()) m_PackageDatabase.UpdatePackages(toRemove: packagesToRemove.Select(p => p.uniqueId).ToArray()); if (packagesToRegenerate.Any()) GeneratePackagesAndTriggerChangeEvent(packagesToRegenerate.Select(p => p.product.id)); } private void AddPackageError(Package package, UIError error) { AddError(package, error); m_PackageDatabase.OnPackagesModified(new[] { package }); } private void SetPackagesProgress(IEnumerable<IPackage> packages, PackageProgress progress) { var packagesUpdated = packages.OfType<Package>().Where(p => p.progress != progress).ToArray(); foreach (var package in packagesUpdated) SetProgress(package, progress); if (packagesUpdated.Any()) m_PackageDatabase.OnPackagesModified(packagesUpdated, true); } private void SetPackageProgress(IPackage package, PackageProgress progress) { SetPackagesProgress(new[] { package }, progress); } private void OnBeforeDownloadStart(long productId) { var package = m_PackageDatabase.GetPackage(productId) as Package; if (package == null) return; // When we start a new download, we want to clear past operation errors to give it a fresh start. // Eventually we want a better design on how to show errors, to be further addressed in https://jira.unity3d.com/browse/PAX-1332 // We need to clear errors before calling download because Download can fail right away var numErrorsRemoved = ClearErrors(package, e => e.errorCode == UIErrorCode.AssetStoreOperationError); if (numErrorsRemoved > 0) m_PackageDatabase.OnPackagesModified(new[] { package }); } private void OnDownloadStateChanged(AssetStoreDownloadOperation operation) { var package = m_PackageDatabase.GetPackage(operation.packageUniqueId); if (package == null) return; if (operation.state == DownloadState.Pausing) SetPackageProgress(package, PackageProgress.Pausing); else if (operation.state == DownloadState.ResumeRequested) SetPackageProgress(package, PackageProgress.Resuming); else if (operation.state == DownloadState.Paused || operation.state == DownloadState.AbortRequested || operation.state == DownloadState.Aborted) SetPackageProgress(package, PackageProgress.None); } private void OnDownloadProgress(AssetStoreDownloadOperation operation) { var package = m_PackageDatabase.GetPackage(operation.packageUniqueId); if (package == null) return; SetPackageProgress(package, operation.isInProgress ? PackageProgress.Downloading : PackageProgress.None); } private void OnDownloadFinalized(AssetStoreDownloadOperation operation) { var package = m_PackageDatabase.GetPackage(operation.packageUniqueId) as Package; if (package == null) return; if (operation.state == DownloadState.Error) AddPackageError(package, new UIError(UIErrorCode.AssetStoreOperationError, operation.errorMessage, UIError.Attribute.Clearable)); else if (operation.state == DownloadState.Aborted) m_PackageDatabase.OnPackagesModified(new[] { package }); SetPackageProgress(package, PackageProgress.None); } private void OnDownloadError(AssetStoreDownloadOperation operation, UIError error) { var package = m_PackageDatabase.GetPackage(operation.packageUniqueId) as Package; if (package == null) return; AddPackageError(package, error); } private void OnLocalInfosChanged(IEnumerable<AssetStoreLocalInfo> addedOrUpdated, IEnumerable<AssetStoreLocalInfo> removed) { // Since users could have way more locally downloaded .unitypackages than what's in their purchase list // we don't want to trigger change events for all of them, only the ones we already checked before (the ones with productInfos) var productIds = addedOrUpdated?.Select(info => info.productId).Concat(removed.Select(info => info.productId) ?? new long[0])?. Where(id => m_AssetStoreCache.GetProductInfo(id) != null); GeneratePackagesAndTriggerChangeEvent(productIds); } private void OnImportedPackagesChanged(IEnumerable<AssetStoreImportedPackage> addedOrUpdated, IEnumerable<AssetStoreImportedPackage> removed) { // Since users could have way more locally downloaded .unitypackages than what's in their purchase list // we don't want to trigger change events for all of them, only the ones we already checked before (the ones with productInfos) var productIds = addedOrUpdated?.Select(info => info.productId).Concat(removed.Select(info => info.productId) ?? new long[0]); GeneratePackagesAndTriggerChangeEvent(productIds); } private void OnUpdateInfosChanged(IEnumerable<AssetStoreUpdateInfo> updateInfos) { // Right now updateInfo goes hands in hands with localInfo, so we handle it the same way as localInfo changes // and only check packages we already checked before (the ones with productInfos). This behaviour might change in the future GeneratePackagesAndTriggerChangeEvent(updateInfos?.Select(info => info.productId).Where(id => m_AssetStoreCache.GetProductInfo(id) != null)); } private void OnProductInfoChanged(AssetStoreProductInfo productInfo) { GeneratePackagesAndTriggerChangeEvent(new[] { productInfo.productId }); } private void OnPurchaseInfosChanged(IEnumerable<AssetStorePurchaseInfo> purchaseInfos) { GeneratePackagesAndTriggerChangeEvent(purchaseInfos.Select(info => info.productId)); } private void OnFetchStatusChanged(FetchStatus fetchStatus) { GeneratePackagesAndTriggerChangeEvent(new[] { fetchStatus.productId }); } public void GeneratePackagesAndTriggerChangeEvent(IEnumerable<long> productIds) { if (productIds?.Any() != true) return; var packagesChanged = new List<IPackage>(); var packagesToRemove = new List<string>(); foreach (var productId in productIds) { var purchaseInfo = m_AssetStoreCache.GetPurchaseInfo(productId); var productInfo = m_AssetStoreCache.GetProductInfo(productId); var importedPackage = m_AssetStoreCache.GetImportedPackage(productId); if (purchaseInfo == null && productInfo == null && importedPackage == null) { packagesToRemove.Add(productId.ToString()); continue; } var packageName = string.IsNullOrEmpty(productInfo?.packageName) ? m_UniqueIdMapper.GetNameByProductId(productId) : productInfo.packageName; // ProductInfos with package names are handled in UpmOnAssetStorePackageFactory, we don't want to worry about it here. if (!string.IsNullOrEmpty(packageName)) continue; var fetchStatus = m_FetchStatusTracker.GetOrCreateFetchStatus(productId); var productInfoFetchError = fetchStatus.GetFetchError(FetchType.ProductInfo); if (importedPackage == null && productInfo == null) { var version = new PlaceholderPackageVersion(productId.ToString(), purchaseInfo.displayName, tag: PackageTag.LegacyFormat, error: productInfoFetchError?.error); var placeholderPackage = CreatePackage(string.Empty, new PlaceholderVersionList(version), new Product(productId, null, null)); if (productInfoFetchError == null) SetProgress(placeholderPackage, PackageProgress.Refreshing); packagesChanged.Add(placeholderPackage); continue; } var isFetchingProductInfo = fetchStatus.IsFetchInProgress(FetchType.ProductInfo); if (importedPackage != null && productInfo == null && !isFetchingProductInfo && productInfoFetchError == null) { m_BackgroundFetchHandler.AddToFetchPurchaseInfoQueue(productId); m_BackgroundFetchHandler.AddToFetchProductInfoQueue(productId); m_BackgroundFetchHandler.PushToCheckUpdateStack(productId); } var isDeprecated = productInfo?.state.Equals("deprecated", StringComparison.InvariantCultureIgnoreCase) ?? false; var localInfo = m_AssetStoreCache.GetLocalInfo(productId); var updateInfo = m_AssetStoreCache.GetUpdateInfo(productId); var versionList = new AssetStoreVersionList(productInfo, localInfo, importedPackage, updateInfo); var package = CreatePackage(string.Empty, versionList, new Product(productId, purchaseInfo, productInfo), isDeprecated: isDeprecated); if (m_AssetStoreDownloadManager.GetDownloadOperation(productId)?.isInProgress == true) SetProgress(package, PackageProgress.Downloading); else if (productInfoFetchError != null) AddError(package, productInfoFetchError.error); packagesChanged.Add(package); } if (packagesChanged.Any() || packagesToRemove.Any()) m_PackageDatabase.UpdatePackages(packagesChanged, packagesToRemove); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePackageFactory.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/AssetStore/AssetStorePackageFactory.cs", "repo_id": "UnityCsReference", "token_count": 5830 }
374
// 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.PackageManager.UI.Internal { [Flags] internal enum DownloadState { None = 0, Connecting = 1 << 0, DownloadRequested = 1 << 1, Downloading = 1 << 2, Pausing = 1 << 3, Paused = 1 << 4, ResumeRequested = 1 << 5, Completed = 1 << 6, Decrypting = 1 << 7, Aborted = 1 << 8, AbortRequested = 1 << 9, Error = 1 << 10, InProgress = Connecting | DownloadRequested | Downloading | ResumeRequested | Decrypting, InPause = Pausing | Paused } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/DownloadState.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Common/DownloadState.cs", "repo_id": "UnityCsReference", "token_count": 509 }
375
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; namespace UnityEditor.PackageManager.UI.Internal { internal static class EntitlementsErrorAndDeprecationChecker { // These strings shouldn't be localized because they're used for string matching with UPM server error messages. internal const string k_NoSubscriptionUpmErrorMessage = "You do not have a subscription for this package"; internal const string k_NotAcquiredUpmErrorMessage = "Your account does not grant permission to use the package"; internal const string k_NotSignedInUpmErrorMessage = "You are not signed in"; public static void ManagePackageManagerEntitlementErrorAndDeprecation(IUpmClient upmClient) { upmClient.onListOperation += OnListOperation; upmClient.List(true); } private static void OnListOperation(IOperation operation) { var listOperation = operation as UpmListOperation; if (listOperation?.isOfflineMode == true) { listOperation.onProcessResult += (request) => { var servicesContainer = ServicesContainer.instance; var upmClient = servicesContainer.Resolve<IUpmClient>(); upmClient.onListOperation -= OnListOperation; // Package Manager Window always seems to default to name ascending order var packages = request.Result; if (FindEntitielmentErrorAndOpenPackageManager(packages)) return; FindDeprecationPackagesAndOpenPackageManager(packages); }; } } // Returns true if packages with entitlement errors are found and package manager window is opened private static bool FindEntitielmentErrorAndOpenPackageManager(PackageCollection packages) { var entitlementErrorPackage = packages.Where(p => p.entitlements?.isAllowed == false || p.errors.Any(error => error.message.Contains(k_NoSubscriptionUpmErrorMessage) || // The following two string matching is used to check for Asset Store // entitlement errors because upm-core only exposes them via strings. error.message.Contains(k_NotAcquiredUpmErrorMessage) || error.message.Contains(k_NotSignedInUpmErrorMessage))) .OrderBy(p => p.displayName ?? p.name) .FirstOrDefault(); if (entitlementErrorPackage != null) { PackageManagerWindow.OpenPackageManager(entitlementErrorPackage.name); return true; } return false; } // Returns true if deprecated packages are found and package manager window is opened private static bool FindDeprecationPackagesAndOpenPackageManager(PackageCollection packages) { var servicesContainer = ServicesContainer.instance; var settingsProxy = servicesContainer.Resolve<IProjectSettingsProxy>(); if (settingsProxy.oneTimeDeprecatedPopUpShown) return false; var deprecatedPackage = packages.Where(p => (p.versions.deprecated.Contains(p.version)) || p.unityLifecycle.isDeprecated) .OrderBy(p => p.displayName ?? p.name) .FirstOrDefault(); if (deprecatedPackage == null) return false; var applicationProxy = servicesContainer.Resolve<IApplicationProxy>(); var dialogResult = applicationProxy.DisplayDialogComplex("openPackageManagerWithDeprecatedPackages", L10n.Tr("Deprecated packages"), L10n.Tr("This project contains one or more deprecated packages. Do you want to open Package Manager?"), L10n.Tr("Open Package Manager"), L10n.Tr("Dismiss"), L10n.Tr("Dismiss Forever")); switch (dialogResult) { case 0: PackageManagerWindow.OpenPackageManager(deprecatedPackage.name); return true; // Dismiss Forever case 2: settingsProxy.oneTimeDeprecatedPopUpShown = true; settingsProxy.Save(); break; } return false; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/EntitlementsErrorAndDeprecationChecker.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/EntitlementsErrorAndDeprecationChecker.cs", "repo_id": "UnityCsReference", "token_count": 2069 }
376
// 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 UnityEditor.PackageManager.UI.Internal; internal abstract class ImportActionBase : PackageAction { protected readonly IPackageOperationDispatcher m_OperationDispatcher; protected readonly IAssetStoreDownloadManager m_AssetStoreDownloadManager; protected readonly IApplicationProxy m_Application; protected readonly IUnityConnectProxy m_UnityConnect; protected ImportActionBase(IPackageOperationDispatcher operationDispatcher, IAssetStoreDownloadManager assetStoreDownloadManager, IApplicationProxy application, IUnityConnectProxy unityConnect) { m_OperationDispatcher = operationDispatcher; m_AssetStoreDownloadManager = assetStoreDownloadManager; m_Application = application; m_UnityConnect = unityConnect; } protected abstract string analyticEventName { get; } protected override bool TriggerActionImplementation(IPackageVersion version) { m_OperationDispatcher.Import(version.package); PackageManagerWindowAnalytics.SendEvent(analyticEventName, version); return true; } public override bool IsVisible(IPackageVersion version) { return m_UnityConnect.isUserLoggedIn && version.HasTag(PackageTag.LegacyFormat) && version.package.versions.importAvailable != null && version.package.progress == PackageProgress.None && m_AssetStoreDownloadManager.GetDownloadOperation(version.package.product?.id)?.isProgressVisible != true; } public override bool IsInProgress(IPackageVersion version) => false; protected override IEnumerable<DisableCondition> GetAllTemporaryDisableConditions() { yield return new DisableIfCompiling(m_Application); } protected override IEnumerable<DisableCondition> GetAllDisableConditions(IPackageVersion version) { yield return new DisableIfPackageDisabled(version); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/ImportActionBase.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/Actions/ImportActionBase.cs", "repo_id": "UnityCsReference", "token_count": 750 }
377
// 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 UnityEngine; using UnityEditor.Scripting.ScriptCompilation; namespace UnityEditor.PackageManager.UI.Internal { internal interface IPackageDatabase : IService { event Action<string, string> onPackageUniqueIdFinalize; event Action<PackagesChangeArgs> onPackagesChanged; bool isEmpty { get; } IEnumerable<IPackage> allPackages { get; } IPackage GetPackage(string uniqueId); IPackage GetPackage(long productId); void GetPackageAndVersionByIdOrName(string idOrName, out IPackage package, out IPackageVersion version, bool bruteForceSearch); IPackage GetPackageByIdOrName(string idOrName); void GetPackageAndVersion(string packageUniqueId, string versionUniqueId, out IPackage package, out IPackageVersion version); void GetPackageAndVersion(PackageAndVersionIdPair pair, out IPackage package, out IPackageVersion version); void GetPackageAndVersion(DependencyInfo info, out IPackage package, out IPackageVersion version); IEnumerable<IPackageVersion> GetReverseDependencies(IPackageVersion version, bool directDependenciesOnly = false); IEnumerable<IPackageVersion> GetFeaturesThatUseThisPackage(IPackageVersion version); IPackage[] GetCustomizedDependencies(IPackageVersion version, bool? rootDependenciesOnly = null); IEnumerable<Sample> GetSamples(IPackageVersion version); IPackageVersion GetLifecycleOrPrimaryVersion(string packageUniqueId); void OnPackagesModified(IList<IPackage> modified, bool isProgressUpdated = false); void UpdatePackages(IList<IPackage> toAddOrUpdate = null, IList<string> toRemove = null); void ClearSamplesCache(); } internal class PackagesChangeArgs { public IList<IPackage> added = Array.Empty<IPackage>(); public IList<IPackage> removed = Array.Empty<IPackage>(); public IList<IPackage> updated = Array.Empty<IPackage>(); // To avoid unnecessary cloning of packages, preUpdate is now set to be optional, the list is either empty or the same size as the the postUpdate list public IList<IPackage> preUpdate = Array.Empty<IPackage>(); public IList<IPackage> progressUpdated = Array.Empty<IPackage>(); } [Serializable] internal class PackageDatabase : BaseService<IPackageDatabase>, IPackageDatabase, ISerializationCallbackReceiver { // Normally package unique Id never changes for a package, but when we are installing a package from git or a tarball // we only had a temporary unique id at first. For example, for `com.unity.a` is a unique id for a package, but when // we are installing from git, the only identifier we know is something like `git@example.com/com.unity.a.git`. // We only know the id `com.unity.a` after the package has been successfully installed, and we'll trigger an event for that. public event Action<string, string> onPackageUniqueIdFinalize = delegate {}; public event Action<PackagesChangeArgs> onPackagesChanged = delegate {}; private readonly Dictionary<string, IPackage> m_Packages = new(); // we added m_Feature to speed up reverse dependencies lookup private readonly Dictionary<string, IPackage> m_Features = new(); private readonly Dictionary<string, IEnumerable<Sample>> m_ParsedSamples = new(); [SerializeField] private Package[] m_SerializedPackages = Array.Empty<Package>(); private readonly IUniqueIdMapper m_UniqueIdMapper; private readonly IAssetDatabaseProxy m_AssetDatabase; private readonly IUpmCache m_UpmCache; private readonly IIOProxy m_IOProxy; public PackageDatabase(IUniqueIdMapper uniqueIdMapper, IAssetDatabaseProxy assetDatabase, IUpmCache upmCache, IIOProxy ioProxy) { m_UniqueIdMapper = RegisterDependency(uniqueIdMapper); m_AssetDatabase = RegisterDependency(assetDatabase); m_UpmCache = RegisterDependency(upmCache); m_IOProxy = RegisterDependency(ioProxy); } public bool isEmpty => !m_Packages.Any(); public IEnumerable<IPackage> allPackages => m_Packages.Values; public IPackage GetPackage(string uniqueId) { return GetPackage(uniqueId, false); } public IPackage GetPackage(long productId) { return GetPackage(productId.ToString(), false); } private IPackage GetPackage(string uniqueId, bool retryWithIdMapper) { if (string.IsNullOrEmpty(uniqueId)) return null; var package = m_Packages.Get(uniqueId); if (package != null || !retryWithIdMapper) return package; // We only retry with productId now because in the case where productId and package Name both exist for a package // we use productId as the primary key. var productId = m_UniqueIdMapper.GetProductIdByName(uniqueId); return productId > 0 ? m_Packages.Get(productId.ToString()) : null; } // In some situations, we only know an id (could be package unique id, or version unique id) or just a name (package Name, or display name) // but we still might be able to find a package and a version that matches the criteria public void GetPackageAndVersionByIdOrName(string idOrName, out IPackage package, out IPackageVersion version, bool bruteForceSearch) { // GetPackage by packageUniqueId itself is not an expensive operation, so we want to try and see if the input string is a packageUniqueId first. package = GetPackage(idOrName, true); if (package != null) { version = null; return; } // if we are able to break the string into two by looking at '@' sign, it's possible that the input idOrDisplayName is a versionId var idOrDisplayNameSplit = idOrName?.Split(new[] { '@' }, 2); if (idOrDisplayNameSplit?.Length == 2) { var packageUniqueId = idOrDisplayNameSplit[0]; GetPackageAndVersion(packageUniqueId, idOrName, out package, out version); if (package != null) return; } // If none of those find-by-index options work, we'll just have to find it the brute force way by matching the name & display name package = bruteForceSearch ? m_Packages.Values.FirstOrDefault(p => p.name == idOrName || p.displayName == idOrName) : null; version = null; } public IPackage GetPackageByIdOrName(string idOrName) { GetPackageAndVersionByIdOrName(idOrName, out var package, out _, false); return package; } public void GetPackageAndVersion(string packageUniqueId, string versionUniqueId, out IPackage package, out IPackageVersion version) { package = GetPackage(packageUniqueId, true); version = package?.versions.FirstOrDefault(v => v.uniqueId == versionUniqueId); } public void GetPackageAndVersion(PackageAndVersionIdPair pair, out IPackage package, out IPackageVersion version) { GetPackageAndVersion(pair?.packageUniqueId, pair?.versionUniqueId, out package, out version); } public void GetPackageAndVersion(DependencyInfo info, out IPackage package, out IPackageVersion version) { package = GetPackage(info.name); if (package == null) { version = null; return; } // the versionIdentifier could either be SemVersion or file, git or ssh reference // and the two cases are handled differently. if (!string.IsNullOrEmpty(info.version) && char.IsDigit(info.version.First())) { SemVersionParser.TryParse(info.version, out var parsedVersion); version = package.versions.FirstOrDefault(v => v.version == parsedVersion); } else { var packageId = UpmPackageVersion.FormatPackageId(info.name, info.version); version = package.versions.FirstOrDefault(v => v.uniqueId == packageId); } } public IEnumerable<IPackageVersion> GetReverseDependencies(IPackageVersion version, bool directDependenciesOnly = false) { if (version?.dependencies == null) return null; var installedRoots = allPackages.Select(p => p.versions.installed).Where(p => p?.isDirectDependency ?? false); return installedRoots.Where(p => (directDependenciesOnly ? p.dependencies : p.resolvedDependencies)?.Any(r => r.name == version.name) ?? false); } public IEnumerable<IPackageVersion> GetFeaturesThatUseThisPackage(IPackageVersion version) { if (version?.dependencies == null) return Enumerable.Empty<IPackageVersion>(); var installedFeatures = m_Features.Values.Select(p => p.versions.installed) .Where(p => p?.isDirectDependency ?? false); return installedFeatures.Where(f => f.dependencies?.Any(r => r.name == version.name) ?? false); } public IPackage[] GetCustomizedDependencies(IPackageVersion version, bool? rootDependenciesOnly = null) { return version?.dependencies?.Select(d => GetPackage(d.name)).Where(p => { return p?.versions.isNonLifecycleVersionInstalled == true && (rootDependenciesOnly == null || p.versions.installed.isDirectDependency == rootDependenciesOnly); }).ToArray() ?? new IPackage[0]; } public IEnumerable<Sample> GetSamples(IPackageVersion version) { var packageInfo = version != null ? m_UpmCache.GetBestMatchPackageInfo(version.name, version.isInstalled, version.versionString) : null; if (packageInfo == null || packageInfo.version != version.version?.ToString()) return Enumerable.Empty<Sample>(); if (m_ParsedSamples.TryGetValue(version.uniqueId, out var parsedSamples)) return parsedSamples; var samples = Sample.FindByPackage(packageInfo, m_UpmCache, m_IOProxy, m_AssetDatabase); m_ParsedSamples[version.uniqueId] = samples; return samples; } public IPackageVersion GetLifecycleOrPrimaryVersion(string packageUniqueId) { var versions = GetPackage(packageUniqueId)?.versions; return versions?.lifecycleVersion ?? versions?.primary; } public void OnAfterDeserialize() { foreach (var p in m_SerializedPackages) AddPackage(p.uniqueId, p); } public void OnBeforeSerialize() { m_SerializedPackages = m_Packages.Values.Cast<Package>().ToArray(); } private void TriggerOnPackagesChanged(IList<IPackage> added = null, IList<IPackage> removed = null, IList<IPackage> updated = null, IList<IPackage> preUpdate = null, IList<IPackage> progressUpdated = null) { added ??= Array.Empty<IPackage>(); updated ??= Array.Empty<IPackage>(); removed ??= Array.Empty<IPackage>(); preUpdate ??= Array.Empty<IPackage>(); progressUpdated ??= Array.Empty<IPackage>(); if (added.Count + updated.Count + removed.Count + preUpdate.Count + progressUpdated.Count <= 0) return; onPackagesChanged?.Invoke(new PackagesChangeArgs { added = added, updated = updated, removed = removed, preUpdate = preUpdate, progressUpdated = progressUpdated }); } public void OnPackagesModified(IList<IPackage> modified, bool isProgressUpdated = false) { TriggerOnPackagesChanged(updated: modified, progressUpdated: isProgressUpdated ? modified : null); } public void UpdatePackages(IList<IPackage> toAddOrUpdate = null, IList<string> toRemove = null) { toAddOrUpdate ??= Array.Empty<IPackage>(); toRemove ??= Array.Empty<string>(); if (!toAddOrUpdate.Any() && !toRemove.Any()) return; var featuresWithDependencyChange = new Dictionary<string, IPackage>(); var packagesAdded = new List<IPackage>(); var packagesRemoved = new List<IPackage>(); var packagesPreUpdate = new List<IPackage>(); var packagesUpdated = new List<IPackage>(); var packageProgressUpdated = new List<IPackage>(); foreach (var package in toAddOrUpdate) { foreach (var feature in GetFeaturesThatUseThisPackage(package.versions.primary)) { if (!featuresWithDependencyChange.ContainsKey(feature.uniqueId)) featuresWithDependencyChange[feature.uniqueId] = feature.package; } var packageUniqueId = package.uniqueId; var oldPackage = GetPackage(packageUniqueId); AddPackage(packageUniqueId, package); if (oldPackage != null) { packagesPreUpdate.Add(oldPackage); packagesUpdated.Add(package); if (oldPackage.progress != package.progress) packageProgressUpdated.Add(package); } else packagesAdded.Add(package); // It could happen that before the productId info was available, another package was created with packageName as the uniqueId // Once the productId becomes available it should be the new uniqueId, we want to old package such that there won't be two // entries of the same package with different uniqueIds (one productId, one with packageName) if (package.product != null && !string.IsNullOrEmpty(package.name)) { { var packageWithNameAsUniqueId = GetPackage(package.name); if (packageWithNameAsUniqueId != null) { packagesRemoved.Add(packageWithNameAsUniqueId); RemovePackage(package.name); onPackageUniqueIdFinalize?.Invoke(package.name, package.uniqueId); } } } var tempId = m_UniqueIdMapper.GetTempIdByFinalizedId(package.uniqueId); if (!string.IsNullOrEmpty(tempId)) { var packageWithTempId = GetPackage(tempId); if (packageWithTempId != null) { packagesRemoved.Add(packageWithTempId); RemovePackage(tempId); } onPackageUniqueIdFinalize?.Invoke(tempId, package.uniqueId); m_UniqueIdMapper.RemoveTempId(package.uniqueId); } } packagesUpdated.AddRange(featuresWithDependencyChange.Values.Where(p => !packagesUpdated.Contains(p))); foreach (var packageUniqueId in toRemove) { var oldPackage = GetPackage(packageUniqueId); if (oldPackage != null) { packagesRemoved.Add(oldPackage); RemovePackage(packageUniqueId); } } TriggerOnPackagesChanged(added: packagesAdded, removed: packagesRemoved, preUpdate: packagesPreUpdate, updated: packagesUpdated, progressUpdated: packageProgressUpdated); } private void RemovePackage(string packageUniqueId) { m_Packages.Remove(packageUniqueId); m_Features.Remove(packageUniqueId); } private void AddPackage(string packageUniqueId, IPackage package) { m_Packages[packageUniqueId] = package; if (package.versions.All(v => v.HasTag(PackageTag.Feature))) m_Features[packageUniqueId] = package; } public void ClearSamplesCache() { m_ParsedSamples.Clear(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageDatabase.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Packages/PackageDatabase.cs", "repo_id": "UnityCsReference", "token_count": 7053 }
378
// 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.PackageManager.UI.Internal { [Flags] internal enum PageCapability : uint { None = 0, RequireUserLoggedIn = 1 << 0, RequireNetwork = 1 << 1, SupportLocalReordering = 1 << 2, DynamicEntitlementStatus = 1 << 3 } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageCapability.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/PageCapability.cs", "repo_id": "UnityCsReference", "token_count": 237 }
379
// 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; namespace UnityEditor.PackageManager.UI.Internal { [Flags] internal enum RefreshOptions : uint { None = 0, UpmListOffline = 1 << 0, UpmList = 1 << 1, UpmSearchOffline = 1 << 2, UpmSearch = 1 << 3, Purchased = 1 << 4, LocalInfo = 1 << 5, ImportedAssets = 1 << 6 } internal static class RefreshOptionsExtension { public static RefreshOptions[] Split(this RefreshOptions value) { return Enum.GetValues(typeof(RefreshOptions)).Cast<RefreshOptions>() .Where(r => (value & r) != 0).ToArray(); } public static bool Contains(this RefreshOptions value, RefreshOptions flag) => (value & flag) == flag; } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/RefreshOptions.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Pages/RefreshOptions.cs", "repo_id": "UnityCsReference", "token_count": 425 }
380
// 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.IO; using System.Linq; using System.Diagnostics.CodeAnalysis; using UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { using NiceIO; internal interface IIOProxy : IService { void DirectoryCopy(string sourcePath, string destinationPath, bool makeWritable = false, Action<string, float> progressCallback = null); ulong DirectorySizeInBytes(string path); void RemovePathAndMeta(string path, bool removeEmptyParent = false); string PathsCombine(params string[] components); string CurrentDirectory { get; } string GetParentDirectory(string path); bool IsDirectoryEmpty(string directoryPath); bool DirectoryExists(string directoryPath); string[] DirectoryGetDirectories(string directoryPath, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly); string[] DirectoryGetFiles(string directoryPath, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly); void CreateDirectory(string directoryPath); void DeleteDirectory(string directoryPath); string GetProjectDirectory(); bool IsSamePackageDirectory(string a, string b); void MakeFileWritable(string filePath, bool writable); void CopyFile(string sourceFileName, string destFileName, bool overwrite); ulong GetFileSize(string filePath); string GetFileName(string filePath); void DeleteIfExists(string filePath); bool FileExists(string filePath); byte[] FileReadAllBytes(string filePath); string FileReadAllText(string filePath); void FileWriteAllBytes(string filePath, byte[] bytes); void FileWriteAllText(string filePath, string contents); } [ExcludeFromCodeCoverage] internal class IOProxy : BaseService<IIOProxy>, IIOProxy { // Need to re-create this method since Unity's FileUtil equivalent (with overwrite) is internal only. // From: https://stackoverflow.com/questions/58744/copy-the-entire-contents-of-a-directory-in-c-sharp public void DirectoryCopy(string sourcePath, string destinationPath, bool makeWritable = false, Action<string, float> progressCallback = null) { if (!DirectoryExists(destinationPath)) CreateDirectory(destinationPath); //Now Create all of the directories foreach (var dir in DirectoryGetDirectories(sourcePath, "*", SearchOption.AllDirectories)) { var path = dir.Replace(sourcePath, destinationPath); if (!DirectoryExists(path)) CreateDirectory(path); } //Copy all the files & Replaces any files with the same name var files = DirectoryGetFiles(sourcePath, "*", SearchOption.AllDirectories); float count = 0; foreach (var source in files) { var dest = source.Replace(sourcePath, destinationPath); progressCallback?.Invoke(source, count / files.Length); CopyFile(source, dest, true); if (makeWritable) MakeFileWritable(dest, true); count++; } } public ulong DirectorySizeInBytes(string path) { return DirectoryGetFiles(path, "*", SearchOption.AllDirectories). Aggregate<string, ulong>(0, (current, file) => current + GetFileSize(file)); } public void RemovePathAndMeta(string path, bool removeEmptyParent = false) { while (true) { if (DirectoryExists(path)) DeleteDirectory(path); DeleteIfExists(path + ".meta"); if (removeEmptyParent) { var parent = GetParentDirectory(path); if (DirectoryExists(parent) && IsDirectoryEmpty(parent)) { path = parent; continue; } } break; } } public string PathsCombine(params string[] components) { return components.Where(s => !string.IsNullOrEmpty(s)). Aggregate((path1, path2) => new NPath(path1).Combine(path2).ToString(SlashMode.Native)); } public string CurrentDirectory => NPath.CurrentDirectory.ToString(SlashMode.Native); public string GetParentDirectory(string path) => new NPath(path).Parent.ToString(SlashMode.Native); public bool IsDirectoryEmpty(string directoryPath) => new NPath(directoryPath).Contents().Length == 0; public bool DirectoryExists(string directoryPath) => new NPath(directoryPath).DirectoryExists(); public string[] DirectoryGetDirectories(string directoryPath, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly) => new NPath(directoryPath).Directories(searchPattern, searchOption == SearchOption.AllDirectories).Select(p => p.ToString(SlashMode.Native)).ToArray(); public string[] DirectoryGetFiles(string directoryPath, string searchPattern = "*", SearchOption searchOption = SearchOption.TopDirectoryOnly) => new NPath(directoryPath).Files(searchPattern, searchOption == SearchOption.AllDirectories).Select(p => p.ToString(SlashMode.Native)).ToArray(); public void CreateDirectory(string directoryPath) => new NPath(directoryPath).CreateDirectory(); public void DeleteDirectory(string directoryPath) => new NPath(directoryPath).DeleteIfExists(); private NPath GetPackageAbsoluteDirectory(string relativePath) { var path = new NPath(relativePath); return path.IsRelative ? path.MakeAbsolute(new NPath(PathsCombine(GetProjectDirectory(), "Packages"))) : path; } // The virtual keyword is needed for unit tests public virtual string GetProjectDirectory() { return GetParentDirectory(Application.dataPath); } public bool IsSamePackageDirectory(string a, string b) { return GetPackageAbsoluteDirectory(a) == GetPackageAbsoluteDirectory(b); } public void MakeFileWritable(string filePath, bool writable) { var npath = new NPath(filePath); var attributes = npath.Attributes; if (writable && (attributes & FileAttributes.ReadOnly) != 0) npath.Attributes &= ~FileAttributes.ReadOnly; if (!writable && (attributes & FileAttributes.ReadOnly) == 0) npath.Attributes |= FileAttributes.ReadOnly; } public void CopyFile(string sourceFileName, string destFileName, bool overwrite) { var npath = new NPath(destFileName); if (!overwrite && npath.FileExists()) return; new NPath(sourceFileName).Copy(npath); } public ulong GetFileSize(string filePath) { try { return (ulong)new NPath(filePath).GetFileSize(); } catch (Exception e) { Debug.Log($"Cannot get file size for {filePath} : {e.Message}"); return 0; } } public string GetFileName(string filePath) => new NPath(filePath).FileName; public void DeleteIfExists(string filePath) => new NPath(filePath).DeleteIfExists(); public bool FileExists(string filePath) => new NPath(filePath).FileExists(); public byte[] FileReadAllBytes(string filePath) => new NPath(filePath).ReadAllBytes(); public string FileReadAllText(string filePath) => new NPath(filePath).ReadAllText(); public void FileWriteAllBytes(string filePath, byte[] bytes) => new NPath(filePath).WriteAllBytes(bytes); public void FileWriteAllText(string filePath, string contents) => new NPath(filePath).WriteAllText(contents); } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/IOProxy.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Proxies/IOProxy.cs", "repo_id": "UnityCsReference", "token_count": 3286 }
381
// 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.PackageManager.Requests; namespace UnityEditor.PackageManager.UI.Internal { [Serializable] internal class UpmListOperation : UpmBaseOperation<ListRequest> { public override RefreshOptions refreshOptions => isOfflineMode ? RefreshOptions.UpmListOffline : RefreshOptions.UpmList; protected override string operationErrorMessage => isOfflineMode ? L10n.Tr("Error fetching package list offline.") : L10n.Tr("Error fetching package list."); public void List() { m_OfflineMode = false; Start(); } public void ListOffline(long timestamp) { m_OfflineMode = true; m_Timestamp = timestamp; Start(); } protected override ListRequest CreateRequest() { return m_ClientProxy.List(isOfflineMode, true); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmListOperation.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/Services/Upm/UpmListOperation.cs", "repo_id": "UnityCsReference", "token_count": 402 }
382
// 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 UnityEngine; namespace UnityEditor.PackageManager.UI.Internal { internal interface IInspectorSelectionHandler : IService { PackageSelectionObject GetPackageSelectionObject(PackageAndVersionIdPair pair, bool createIfNotFound = false); PackageSelectionObject GetPackageSelectionObject(IPackage package, IPackageVersion version = null, bool createIfNotFound = false); } [Serializable] internal class InspectorSelectionHandler : BaseService<IInspectorSelectionHandler>, IInspectorSelectionHandler, ISerializationCallbackReceiver { [SerializeField] private int[] m_SerializedPackageSelectionInstanceIds = Array.Empty<int>(); private Dictionary<string, PackageSelectionObject> m_PackageSelectionObjects = new(); private readonly ISelectionProxy m_Selection; private readonly IPackageDatabase m_PackageDatabase; private readonly IPageManager m_PageManager; public InspectorSelectionHandler(ISelectionProxy selection, IPackageDatabase packageDatabase, IPageManager pageManager) { m_Selection = RegisterDependency(selection); m_PackageDatabase = RegisterDependency(packageDatabase); m_PageManager = RegisterDependency(pageManager); } public void OnBeforeSerialize() { m_SerializedPackageSelectionInstanceIds = m_PackageSelectionObjects.Select(kp => kp.Value.GetInstanceID()).ToArray(); } public void OnAfterDeserialize() {} private void OnEditorSelectionChanged() { var selectionIds = new List<PackageAndVersionIdPair>(); var selectedVersions = new List<IPackageVersion>(); foreach (var selectionObject in m_Selection.objects) { var packageSelectionObject = selectionObject as PackageSelectionObject; if (packageSelectionObject == null) return; m_PackageDatabase.GetPackageAndVersion(packageSelectionObject.packageUniqueId, packageSelectionObject.versionUniqueId, out var package, out var version); if (package == null && version == null) continue; selectedVersions.Add(version ?? package?.versions.primary); selectionIds.Add(new PackageAndVersionIdPair(packageSelectionObject.packageUniqueId, packageSelectionObject.versionUniqueId)); } if (!selectionIds.Any()) return; var page = m_PageManager.FindPage(selectedVersions); if (page != null) { m_PageManager.activePage = page; page.SetNewSelection(selectionIds); } } private void OnPageSelectionChanged(PageSelectionChangeArgs args) { if (!args.page.isActivePage) return; // There are 3 situations when we want to select a package in the inspector // 1) we explicitly/force to select it as a result of a manual action (in this case, isExplicitUserSelection should be set to true) // 2) currently there's no active selection at all // 3) currently another package is selected in inspector, hence we are sure that we are not stealing selection from some other window if (args.isExplicitUserSelection || m_Selection.activeObject == null || m_Selection.activeObject is PackageSelectionObject) { var packageSelectionObjects = args.selection.Select(s => GetPackageSelectionObject(s, true)).ToArray(); m_Selection.objects = packageSelectionObjects; } } public PackageSelectionObject GetPackageSelectionObject(PackageAndVersionIdPair pair, bool createIfNotFound = false) { m_PackageDatabase.GetPackageAndVersion(pair?.packageUniqueId, pair?.versionUniqueId, out var package, out var version); return GetPackageSelectionObject(package, version, createIfNotFound); } // The virtual keyword is needed for unit tests public virtual PackageSelectionObject GetPackageSelectionObject(IPackage package, IPackageVersion version = null, bool createIfNotFound = false) { if (package == null) return null; var uniqueId = version?.uniqueId ?? package.uniqueId; var packageSelectionObject = m_PackageSelectionObjects.Get(uniqueId); if (packageSelectionObject == null && createIfNotFound) { packageSelectionObject = ScriptableObject.CreateInstance<PackageSelectionObject>(); packageSelectionObject.hideFlags = HideFlags.DontSave; packageSelectionObject.name = package.displayName; packageSelectionObject.displayName = package.displayName; packageSelectionObject.packageUniqueId = package.uniqueId; packageSelectionObject.versionUniqueId = version?.uniqueId; m_PackageSelectionObjects[uniqueId] = packageSelectionObject; } return packageSelectionObject; } public void OnPackagesChanged(PackagesChangeArgs args) { foreach (var package in args.removed) { var packageSelectionObject = GetPackageSelectionObject(package); if (packageSelectionObject != null) { m_PackageSelectionObjects.Remove(packageSelectionObject.uniqueId); UnityEngine.Object.DestroyImmediate(packageSelectionObject); } } } private void InitializeSelectionObjects() { foreach (var id in m_SerializedPackageSelectionInstanceIds) { var packageSelectionObject = UnityEngine.Object.FindObjectFromInstanceID(id) as PackageSelectionObject; if (packageSelectionObject != null) m_PackageSelectionObjects[packageSelectionObject.uniqueId] = packageSelectionObject; } } public override void OnEnable() { InitializeSelectionObjects(); m_PackageDatabase.onPackagesChanged += OnPackagesChanged; m_PageManager.onSelectionChanged += OnPageSelectionChanged; m_Selection.onSelectionChanged += OnEditorSelectionChanged; } public override void OnDisable() { m_PackageDatabase.onPackagesChanged -= OnPackagesChanged; m_PageManager.onSelectionChanged -= OnPageSelectionChanged; m_Selection.onSelectionChanged -= OnEditorSelectionChanged; } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/InspectorSelectionHandler.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/Common/InspectorSelectionHandler.cs", "repo_id": "UnityCsReference", "token_count": 2784 }
383
// 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; namespace UnityEditor.PackageManager.UI.Internal { internal class DropdownElement : VisualElement { internal static DropdownElement instance { get; private set; } private DropdownContent m_Content; private DropdownElement() { RegisterCallback<MouseDownEvent>(evt => Hide()); } public static void ShowDropdown(VisualElement parent, DropdownContent content) { if (parent == null || content == null) return; instance = new DropdownElement(); instance.Add(content); instance.m_Content = content; parent.Add(instance); content.OnDropdownShown(); } internal void Hide() { if (parent == null || instance == null) return; foreach (var element in parent.Children()) element.SetEnabled(true); parent.Remove(instance); instance = null; m_Content.OnDropdownClosed(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/DropdownElement.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/DropdownElement.cs", "repo_id": "UnityCsReference", "token_count": 533 }
384
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.PackageManager.UI.Internal { internal class MultiSelectFoldoutGroup : IMultiSelectFoldoutElement { public MultiSelectFoldout mainFoldout { get; } public MultiSelectFoldout inProgressFoldout { get; } public PackageAction mainAction => mainFoldout.action; public PackageAction cancelAction => inProgressFoldout.action; public MultiSelectFoldoutGroup(PackageAction mainAction, PackageAction cancelAction = null) : this(new MultiSelectFoldout(mainAction), new MultiSelectFoldout(cancelAction)) { } public MultiSelectFoldoutGroup(MultiSelectFoldout mainFoldout, MultiSelectFoldout inProgressFoldout) { this.mainFoldout = mainFoldout; this.inProgressFoldout = inProgressFoldout; } public virtual bool AddPackageVersion(IPackageVersion version) { var state = mainAction.GetActionState(version, out _, out _); if (state.HasFlag(PackageActionState.InProgress)) inProgressFoldout.AddPackageVersion(version); else if (state == PackageActionState.Visible || state.HasFlag(PackageActionState.DisabledTemporarily)) mainFoldout.AddPackageVersion(version); else return false; return true; } public virtual void Refresh() { mainFoldout.Refresh(); inProgressFoldout.Refresh(); } public void ClearVersions() { mainFoldout.ClearVersions(); inProgressFoldout.ClearVersions(); } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/MultiSelectFoldoutGroup.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/MultiSelect/MultiSelectFoldoutGroup.cs", "repo_id": "UnityCsReference", "token_count": 747 }
385
// 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 UnityEditorInternal; using UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal { internal class PackageDetailsImportedAssetsTab : PackageDetailsTabElement { internal const string k_Id = "importedassets"; internal const int k_LabelColumnId = 0; internal const int k_LocationColumnId = 1; internal const int k_VersionColumnId = 2; private const int k_MinColumnWidth = 70; private static readonly string k_LabelColumnTitle = L10n.Tr("Asset name"); private static readonly string k_LocationColumnTitle = L10n.Tr("Location in project"); private static readonly string k_VersionColumnTitle = L10n.Tr("Version"); private MultiColumnListView m_ListView; private IList<Asset> assets => m_ListView.itemsSource as IList<Asset>; public override bool IsValid(IPackageVersion version) { return version?.importedAssets?.Any() == true; } private readonly IIOProxy m_IOProxy; private readonly IPackageManagerPrefs m_PackageManagerPrefs; public PackageDetailsImportedAssetsTab(IUnityConnectProxy unityConnect, IIOProxy iOProxy, IPackageManagerPrefs packageManagerPrefs) : base(unityConnect) { m_IOProxy = iOProxy; m_PackageManagerPrefs = packageManagerPrefs; m_Id = k_Id; m_DisplayName = L10n.Tr("Imported Assets"); name = "importedAssetsDetailsContainer"; m_ListView = new MultiColumnListView { sortingMode = ColumnSortingMode.Custom, name = "ImportedAssetsList", scrollView = { verticalScrollerVisibility = ScrollerVisibility.Auto}, selectionType = SelectionType.None, itemsSource = Array.Empty<Asset>(), columns = { reorderable = false } }; m_ContentContainer.Add(m_ListView); AddColumnsAndRestoreSorting(); m_ListView.columnSortingChanged += OnColumnSortingChanged; } protected override void RefreshContent(IPackageVersion version) { SortAssetsAndRefreshItems(version.importedAssets); } private void AddColumnsAndRestoreSorting() { var columns = new Column[3]; columns[k_LabelColumnId] = new Column { name = "label", makeHeader = () => new Label { name = "columnHeader", text = k_LabelColumnTitle, tooltip = k_LabelColumnTitle }, makeCell = () => { var ve = new VisualElement { name = "iconAndLabelContainer" }; ve.Add(new Image()); ve.Add(new Label()); return ve; }, bindCell = (ve, index) => { var image = ve.Q<Image>(); image.image = InternalEditorUtility.GetIconForFile(assets[index].importedPath); var label = ve.Q<Label>(); var labelText = m_IOProxy.GetFileName(assets[index].importedPath); label.text = labelText; ve.tooltip = labelText; }, stretchable = true, minWidth = k_MinColumnWidth }; columns[k_LocationColumnId] = new Column { name = "location", makeHeader = () => new Label { name = "columnHeader", text = k_LocationColumnTitle, tooltip = k_LocationColumnTitle }, bindCell = (ve, index) => { ((Label)ve).text = m_IOProxy.GetParentDirectory(assets[index].importedPath); }, stretchable = true, minWidth = k_MinColumnWidth }; columns[k_VersionColumnId] = new Column { name = "version", makeHeader = () => new Label { name = "columnHeader", text = k_VersionColumnTitle, tooltip = k_VersionColumnTitle }, bindCell = (ve, index) => { var versionString = assets[index].origin.packageVersion; if (!string.IsNullOrEmpty(versionString)) { ((Label)ve).text = versionString; ve.tooltip = string.Empty; } else { ((Label)ve).text = "-"; ve.tooltip = L10n.Tr("This asset's version is unknown because it was imported with an older version of Unity. For accurate version tracking, import the asset again or update it."); } }, stretchable = true, resizable = false, minWidth = k_MinColumnWidth }; foreach (var column in columns) m_ListView.columns.Add(column); foreach (var column in m_PackageManagerPrefs.importedAssetsSortedColumns) m_ListView.sortColumnDescriptions.Add(new SortColumnDescription(column.columnIndex, column.sortDirection)); } private void OnColumnSortingChanged() { m_PackageManagerPrefs.importedAssetsSortedColumns = m_ListView.sortedColumns.Select(c => new SortedColumn(c)).ToArray(); SortAssetsAndRefreshItems(assets); } private void SortAssetsAndRefreshItems(IEnumerable<Asset> assets) { if (m_ListView.sortedColumns?.Any() != true) m_ListView.itemsSource = assets != null ? assets.ToArray() : Array.Empty<Asset>(); else m_ListView.itemsSource = assets.OrderBy(a => a, new AssetComparer(m_IOProxy, m_ListView.sortedColumns)).ToArray(); m_ListView.RefreshItems(); } protected override void DerivedRefreshHeight(float detailHeight, float scrollViewHeight, float detailsHeaderHeight, float tabViewHeaderContainerHeight, float customContainerHeight, float extensionContainerHeight) { var headerTotalHeight = detailsHeaderHeight + tabViewHeaderContainerHeight + customContainerHeight + extensionContainerHeight; var leftOverHeight = detailHeight - headerTotalHeight - layout.height; style.height = scrollViewHeight - headerTotalHeight - leftOverHeight; } private class AssetComparer : IComparer<Asset> { private IEnumerable<SortColumnDescription> m_SortColumnDescriptions; private IIOProxy m_IOProxy; public AssetComparer(IIOProxy ioProxy, IEnumerable<SortColumnDescription> sortColumnDescriptions) { m_SortColumnDescriptions = sortColumnDescriptions; m_IOProxy = ioProxy; } public int Compare(Asset x, Asset y) { return m_SortColumnDescriptions.Select(c => CompareByColumn(c, x, y)).FirstOrDefault(result => result != 0); } private int CompareByColumn(SortColumnDescription description, Asset x, Asset y) { var result = 0; if (description.column.index == k_LabelColumnId) result = string.Compare(m_IOProxy.GetFileName(x.importedPath), m_IOProxy.GetFileName(y.importedPath)); else if (description.column.index == k_LocationColumnId) result = string.Compare(m_IOProxy.GetParentDirectory(x.importedPath), m_IOProxy.GetParentDirectory(y.importedPath)); else result = string.Compare(x.origin.packageVersion, y.origin.packageVersion); return description.direction == SortDirection.Ascending ? result : -result; } } } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsImportedAssetsTab.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageDetailsTabs/PackageDetailsImportedAssetsTab.cs", "repo_id": "UnityCsReference", "token_count": 3998 }
386
// 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.PackageManager.UI.Internal { internal class PackageList : VisualElement { [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new PackageList(); } private IResourceLoader m_ResourceLoader; private IUnityConnectProxy m_UnityConnect; private IPackageManagerPrefs m_PackageManagerPrefs; private IPageManager m_PageManager; private IUpmCache m_UpmCache; private IBackgroundFetchHandler m_BackgroundFetchHandler; private IProjectSettingsProxy m_SettingsProxy; private IPageRefreshHandler m_PageRefreshHandler; private void ResolveDependencies() { var container = ServicesContainer.instance; m_ResourceLoader = container.Resolve<IResourceLoader>(); m_UnityConnect = container.Resolve<IUnityConnectProxy>(); m_PackageManagerPrefs = container.Resolve<IPackageManagerPrefs>(); m_PageManager = container.Resolve<IPageManager>(); m_UpmCache = container.Resolve<IUpmCache>(); m_BackgroundFetchHandler = container.Resolve<IBackgroundFetchHandler>(); m_SettingsProxy = container.Resolve<IProjectSettingsProxy>(); m_PageRefreshHandler = container.Resolve<IPageRefreshHandler>(); } private Action m_ButtonAction; public PackageList() { ResolveDependencies(); var root = m_ResourceLoader.GetTemplate("PackageList.uxml"); Add(root); root.StretchToParentSize(); cache = new VisualElementCache(root); emptyAreaButton.clickable.clicked += OnButtonClicked; RegisterCallback<GeometryChangedEvent>(OnGeometryChange); RegisterCallback<AttachToPanelEvent>(OnEnterPanel); RegisterCallback<DetachFromPanelEvent>(OnLeavePanel); focusable = true; } public void OnEnable() { m_PageRefreshHandler.onRefreshOperationStart += OnRefreshOperationStartOrFinish; m_PageRefreshHandler.onRefreshOperationFinish += OnRefreshOperationStartOrFinish; m_PageManager.onVisualStateChange += OnVisualStateChange; m_PageManager.onListRebuild += OnListRebuild; m_PageManager.onListUpdate += OnListUpdate; m_PageManager.onActivePageChanged += OnActivePageChanged; m_PageManager.onSelectionChanged += OnSelectionChanged; m_BackgroundFetchHandler.onCheckUpdateProgress += OnCheckUpdateProgress; m_UnityConnect.onUserLoginStateChange += OnUserLoginStateChange; listView.OnEnable(); packageLoadBar.OnEnable(); if (!Unsupported.IsDeveloperBuild() && m_SettingsProxy.seeAllPackageVersions) { m_SettingsProxy.seeAllPackageVersions = false; m_SettingsProxy.Save(); } // manually build the items on initialization to refresh the UI OnListRebuild(m_PageManager.activePage); } public void OnDisable() { m_PageRefreshHandler.onRefreshOperationStart -= OnRefreshOperationStartOrFinish; m_PageRefreshHandler.onRefreshOperationFinish -= OnRefreshOperationStartOrFinish; m_PageManager.onVisualStateChange -= OnVisualStateChange; m_PageManager.onListRebuild -= OnListRebuild; m_PageManager.onListUpdate -= OnListUpdate; m_PageManager.onActivePageChanged += OnActivePageChanged; m_PageManager.onSelectionChanged -= OnSelectionChanged; m_BackgroundFetchHandler.onCheckUpdateProgress -= OnCheckUpdateProgress; m_UnityConnect.onUserLoginStateChange -= OnUserLoginStateChange; listView.OnDisable(); packageLoadBar.OnDisable(); } private void OnEnterPanel(AttachToPanelEvent e) { if (panel == null) return; panel.visualTree.RegisterCallback<KeyDownEvent>(OnKeyDownShortcut); RegisterCallback<KeyDownEvent>(IgnoreEscapeKeyDown, TrickleDown.TrickleDown); panel.visualTree.RegisterCallback<NavigationMoveEvent>(OnNavigationMoveShortcut); } private void OnLeavePanel(DetachFromPanelEvent e) { if (panel == null) return; panel.visualTree.UnregisterCallback<KeyDownEvent>(OnKeyDownShortcut); UnregisterCallback<KeyDownEvent>(IgnoreEscapeKeyDown, TrickleDown.TrickleDown); panel.visualTree.UnregisterCallback<NavigationMoveEvent>(OnNavigationMoveShortcut); } private void OnKeyDownShortcut(KeyDownEvent evt) { currentView.OnKeyDownShortcut(evt); } private void OnNavigationMoveShortcut(NavigationMoveEvent evt) { currentView.OnNavigationMoveShortcut(evt); } // The default ListView escape key behaviour is to clear all selections, however, we want to always have something selected // therefore we register a TrickleDown callback handler to intercept escape key events to make it do nothing. private void IgnoreEscapeKeyDown(KeyDownEvent evt) { if (evt.keyCode == KeyCode.Escape) { evt.StopImmediatePropagation(); } } private void OnSelectionChanged(PageSelectionChangeArgs args) { if (!args.page.isActivePage) return; var currentView = this.currentView; foreach (var item in args.selection.previousSelections.Where(s => !args.selection.Contains(s.packageUniqueId)).Concat(args.selection)) currentView.GetPackageItem(item.packageUniqueId)?.RefreshSelection(); if (args.selection.previousSelections.Count() == 1) m_UpmCache.SetLoadAllVersions(args.selection.previousSelections.FirstOrDefault().packageUniqueId, false); } private void OnCheckUpdateProgress() { UpdateListVisibility(true); } private void OnUserLoginStateChange(bool userInfoReady, bool loggedIn) { var page = m_PageManager.activePage; if (page.id == MyAssetsPage.k_Id && UpdateListVisibility()) page.UpdateSelectionIfCurrentSelectionIsInvalid(); } private void HideListShowMessage(bool isRefreshInProgress, bool isCheckUpdateInProgress) { string message; if (isRefreshInProgress) { message = L10n.Tr("Refreshing list..."); } else if (isCheckUpdateInProgress) { message = string.Format(L10n.Tr("Checking for updates {0}%..."), m_BackgroundFetchHandler.checkUpdatePercentage); HideListShowEmptyArea(message, L10n.Tr("Cancel"), () => { m_PageManager.activePage.ClearFilters(); m_BackgroundFetchHandler.CancelCheckUpdates(); }); return; } else { var page = m_PageManager.activePage; var searchText = page.searchText; if (string.IsNullOrEmpty(searchText)) message = page.filters.isFilterSet ? L10n.Tr("No results for the specified filters.") : L10n.Tr("No items to display."); else { const int maxSearchTextToDisplay = 64; if (searchText?.Length > maxSearchTextToDisplay) searchText = searchText.Substring(0, maxSearchTextToDisplay) + "..."; message = string.Format(L10n.Tr("No results for \"{0}\""), searchText); } } HideListShowEmptyArea(message); } private void HideListShowLogin() { if (!m_UnityConnect.isUserInfoReady) HideListShowEmptyArea(string.Empty); else HideListShowEmptyArea(L10n.Tr("Sign in to access your assets"), L10n.Tr("Sign in"), m_UnityConnect.ShowLogin); } public void HideListShowEmptyArea(string message, string buttonText = null, Action buttonAction = null) { UIUtils.SetElementDisplay(listContainer, false); UIUtils.SetElementDisplay(packageLoadBar, false); UIUtils.SetElementDisplay(emptyArea, true); emptyAreaMessage.text = message ?? string.Empty; emptyAreaButton.text = buttonText ?? string.Empty; m_ButtonAction = buttonAction; UIUtils.SetElementDisplay(emptyAreaButton, buttonAction != null); m_PageManager.activePage.SetNewSelection(Enumerable.Empty<PackageAndVersionIdPair>()); } private void HideEmptyAreaShowList(bool skipListRebuild) { var rebuild = !skipListRebuild && !UIUtils.IsElementVisible(listContainer); UIUtils.SetElementDisplay(listContainer, true); UIUtils.SetElementDisplay(emptyArea, false); var currentView = this.currentView; UIUtils.SetElementDisplay(listView, listView == currentView); UIUtils.SetElementDisplay(scrollView, scrollView == currentView); packageLoadBar.UpdateVisibility(); var page = m_PageManager.activePage; var selection = page.GetSelection(); if (!selection.Any() && selection.previousSelections.Any()) page.SetNewSelection(selection.previousSelections); if (rebuild) currentView.OnListRebuild(page); } // Returns true if the list of packages is visible (either listView or scrollView), false otherwise private bool UpdateListVisibility(bool skipListRebuild = false) { var page = m_PageManager.activePage; if (page.id == MyAssetsPage.k_Id && !m_UnityConnect.isUserLoggedIn) { HideListShowLogin(); return false; } var isListEmpty = !page.visualStates.Any(v => v.visible); var isInitialFetchingDone = m_PageRefreshHandler.IsInitialFetchingDone(page); var isCheckUpdateInProgress = page.id == MyAssetsPage.k_Id && m_BackgroundFetchHandler.isCheckUpdateInProgress && page.filters.status == PageFilters.Status.UpdateAvailable; if (isListEmpty || !isInitialFetchingDone || isCheckUpdateInProgress) { HideListShowMessage(m_PageRefreshHandler.IsRefreshInProgress(page), isCheckUpdateInProgress); return false; } HideEmptyAreaShowList(skipListRebuild); return true; } private void OnButtonClicked() { m_ButtonAction?.Invoke(); } private void OnGeometryChange(GeometryChangedEvent evt) { const int heightCalculationBuffer = 4; var containerHeight = resolvedStyle.height; if (float.IsNaN(containerHeight)) return; var numItems = ((int)containerHeight - heightCalculationBuffer - PackageLoadBar.k_FixedHeight) / PackageItem.k_MainItemHeight; m_PackageManagerPrefs.numItemsPerPage = numItems <= 0 ? null : numItems; } private void OnRefreshOperationStartOrFinish() { if (UpdateListVisibility()) m_PageManager.activePage.UpdateSelectionIfCurrentSelectionIsInvalid(); } internal void OnFocus() { currentView.ScrollToSelection(); } private void OnVisualStateChange(VisualStateChangeArgs args) { if (args.page.isActivePage && UpdateListVisibility()) currentView.OnVisualStateChange(args.visualStates); } private void OnListRebuild(IPage page) { if (page.isActivePage && UpdateListVisibility(true)) currentView.OnListRebuild(page); } private void OnListUpdate(ListUpdateArgs args) { if (args.page.isActivePage && UpdateListVisibility()) currentView.OnListUpdate(args); } private void OnActivePageChanged(IPage page) { if (m_PageManager.lastActivePage != null) m_PageRefreshHandler.CancelRefresh(m_PageManager.lastActivePage.refreshOptions); if (UpdateListVisibility()) currentView.OnActivePageChanged(page); } internal IPackageListView currentView => m_PageManager.activePage.id == MyAssetsPage.k_Id ? listView : scrollView; private VisualElementCache cache { get; } private PackageListView listView => cache.Get<PackageListView>("listView"); private PackageListScrollView scrollView => cache.Get<PackageListScrollView>("scrollView"); private VisualElement listContainer => cache.Get<VisualElement>("listContainer"); private PackageLoadBar packageLoadBar => cache.Get<PackageLoadBar>("packageLoadBar"); private VisualElement emptyArea => cache.Get<VisualElement>("emptyArea"); private Label emptyAreaMessage => cache.Get<Label>("emptyAreaMessage"); private Button emptyAreaButton => cache.Get<Button>("emptyAreaButton"); } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageList.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageList.cs", "repo_id": "UnityCsReference", "token_count": 5942 }
387
// 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; namespace UnityEditor.PackageManager.UI.Internal { [ExcludeFromPreset] [Serializable] internal class PackageSelectionObject : ScriptableObject { public string displayName; public string packageUniqueId; public string versionUniqueId; public string uniqueId => string.IsNullOrEmpty(versionUniqueId) ? packageUniqueId : versionUniqueId; } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageSelectionObject.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/PackageSelectionObject.cs", "repo_id": "UnityCsReference", "token_count": 188 }
388
// 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 UnityEngine.UIElements; namespace UnityEditor.PackageManager.UI.Internal; internal class SelectionWindowRoot : VisualElement { public event Action<IEnumerable<Asset>> onSelectionCompleted = delegate {}; private SelectionWindowData m_WindowData; // The rows' height must be set in code, not in uss private const int k_ItemHeight = 25; private readonly SelectionWindowHeader m_Header; private readonly SelectionWindowTreeView m_TreeView; private readonly SelectionWindowFooter m_Footer; private readonly IApplicationProxy m_ApplicationProxy; public SelectionWindowRoot(IResourceLoader resourceLoader, IApplicationProxy applicationProxy) { m_ApplicationProxy = applicationProxy; m_Header = new SelectionWindowHeader(); Add(m_Header); m_TreeView = new SelectionWindowTreeView(k_ItemHeight, MakeItem, BindItem); Add(m_TreeView); m_Footer = new SelectionWindowFooter(); m_Footer.onAllButtonClicked += OnClickAll; m_Footer.onNoneButtonClicked += OnClickNone; m_Footer.onActionButtonClicked += OnAction; m_Footer.onCancelButtonClicked += OnCancel; Add(m_Footer); styleSheets.Add(resourceLoader.selectionWindowStyleSheet); } public void SetData(SelectionWindowData data, bool resetExpansion) { m_WindowData = data; m_Header.SetData(data.headerTitle, data.headerDescription); m_TreeView.SetData(data, resetExpansion); m_Footer.SetData(data.actionLabel); RefreshItems(); } private void RefreshItems() { m_TreeView.RefreshItems(); m_Footer.SetActionEnabled(m_WindowData.selectedAssets.Any()); } private VisualElement MakeItem() { var rowElement = new SelectionWindowRow(); rowElement.toggle.RegisterValueChangedCallback(ToggleChanged); return rowElement; } private void BindItem(VisualElement item, int index) { var selectionWindowRow = item as SelectionWindowRow; if (selectionWindowRow == null) return; var node = m_TreeView.GetItemDataForIndex<SelectionWindowData.Node>(index); selectionWindowRow.SetData(m_WindowData, node, m_TreeView.IsExpanded(node.index)); } private void OnClickAll() { m_WindowData.SelectAll(); RefreshItems(); AssetSelectionWindowAnalytics.SendEvent(m_WindowData, "selectAll"); } private void OnClickNone() { m_WindowData.ClearSelection(); RefreshItems(); AssetSelectionWindowAnalytics.SendEvent(m_WindowData, "selectNone"); } private void OnCancel() { onSelectionCompleted?.Invoke(Array.Empty<Asset>()); // We consider an empty list as a cancellation. AssetSelectionWindowAnalytics.SendEvent(m_WindowData, "cancel"); } private void OnAction() { if (!m_ApplicationProxy.DisplayDialog("removeImported", L10n.Tr("Removing imported assets"), L10n.Tr("Remove the selected assets?\nAny changes you made to the assets will be lost."), L10n.Tr("Remove"), L10n.Tr("Cancel"))) return; onSelectionCompleted?.Invoke(m_WindowData.selectedAssets); AssetSelectionWindowAnalytics.SendEvent(m_WindowData, "remove"); } private void ToggleChanged(ChangeEvent<bool> evt) { var node = GetNodeFromElement(evt.currentTarget as VisualElement); if (node == null) return; if (evt.newValue) { m_TreeView.ExpandItem(node.index, true); m_WindowData.AddSelection(node.index); } else { m_WindowData.RemoveSelection(node.index); } RefreshItems(); } private static SelectionWindowData.Node GetNodeFromElement(VisualElement element) { var parentElement = element?.parent; while (parentElement != null) { if (parentElement is SelectionWindowRow) return parentElement.userData as SelectionWindowData.Node; parentElement = parentElement.parent; } return null; } }
UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowRoot.cs/0
{ "file_path": "UnityCsReference/Modules/PackageManagerUI/Editor/UI/SelectionWindow/SelectionWindowRoot.cs", "repo_id": "UnityCsReference", "token_count": 1717 }
389
// 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.InteropServices; using UnityEngine.Bindings; using UnityEngine.Internal; using UnityEngine.Scripting; using RequiredByNativeCodeAttribute = UnityEngine.Scripting.RequiredByNativeCodeAttribute; using Unity.Collections; using Unity.Collections.LowLevel.Unsafe; using Unity.Jobs; using Unity.Jobs.LowLevel.Unsafe; using UnityEngine.ParticleSystemJobs; namespace UnityEngine { [NativeHeader("ParticleSystemScriptingClasses.h")] [NativeHeader("Modules/ParticleSystem/ParticleSystem.h")] [NativeHeader("Modules/ParticleSystem/ParticleSystemGeometryJob.h")] [NativeHeader("Modules/ParticleSystem/ScriptBindings/ParticleSystemScriptBindings.h")] [UsedByNativeCode] [RequireComponent(typeof(Transform))] public sealed partial class ParticleSystem : Component { // Properties extern public bool isPlaying { [NativeName("SyncJobs(false)->IsPlaying")] get; } extern public bool isEmitting { [NativeName("SyncJobs(false)->IsEmitting")] get; } extern public bool isStopped { [NativeName("SyncJobs(false)->IsStopped")] get; } extern public bool isPaused { [NativeName("SyncJobs(false)->IsPaused")] get; } extern public int particleCount { [NativeName("SyncJobs(false)->GetParticleCount")] get; } extern public float time { [NativeName("SyncJobs(false)->GetSecPosition")] get; [NativeName("SyncJobs(false)->SetSecPosition")] set; } extern public float totalTime { [NativeName("SyncJobs(false)->GetTotalSecPosition")] get; } extern public UInt32 randomSeed { [NativeName("GetRandomSeed")] get; [NativeName("SyncJobs(false)->SetRandomSeed")] set; } extern public bool useAutoRandomSeed { [NativeName("GetAutoRandomSeed")] get; [NativeName("SyncJobs(false)->SetAutoRandomSeed")] set; } extern public bool proceduralSimulationSupported { get; } // Current size/color helpers [FreeFunction(Name = "ParticleSystemScriptBindings::GetParticleCurrentSize", HasExplicitThis = true)] extern internal float GetParticleCurrentSize(ref Particle particle); [FreeFunction(Name = "ParticleSystemScriptBindings::GetParticleCurrentSize3D", HasExplicitThis = true)] extern internal Vector3 GetParticleCurrentSize3D(ref Particle particle); [FreeFunction(Name = "ParticleSystemScriptBindings::GetParticleCurrentColor", HasExplicitThis = true)] extern internal Color32 GetParticleCurrentColor(ref Particle particle); // Mesh index helper [FreeFunction(Name = "ParticleSystemScriptBindings::GetParticleMeshIndex", HasExplicitThis = true)] extern internal int GetParticleMeshIndex(ref Particle particle); // Set/get particles [FreeFunction(Name = "ParticleSystemScriptBindings::SetParticles", HasExplicitThis = true, ThrowsException = true)] extern public void SetParticles([Out] Particle[] particles, int size, int offset); public void SetParticles([Out] Particle[] particles, int size) { SetParticles(particles, size, 0); } public void SetParticles([Out] Particle[] particles) { SetParticles(particles, -1); } [FreeFunction(Name = "ParticleSystemScriptBindings::SetParticlesWithNativeArray", HasExplicitThis = true, ThrowsException = true)] extern private void SetParticlesWithNativeArray(IntPtr particles, int particlesLength, int size, int offset); public void SetParticles([Out] NativeArray<Particle> particles, int size, int offset) { unsafe { SetParticlesWithNativeArray((IntPtr)particles.GetUnsafeReadOnlyPtr(), particles.Length, size, offset); } } public void SetParticles([Out] NativeArray<Particle> particles, int size) { SetParticles(particles, size, 0); } public void SetParticles([Out] NativeArray<Particle> particles) { SetParticles(particles, -1); } [FreeFunction(Name = "ParticleSystemScriptBindings::GetParticles", HasExplicitThis = true, ThrowsException = true)] extern public int GetParticles([NotNull][Out] Particle[] particles, int size, int offset); public int GetParticles([Out] Particle[] particles, int size) { return GetParticles(particles, size, 0); } public int GetParticles([Out] Particle[] particles) { return GetParticles(particles, -1); } [FreeFunction(Name = "ParticleSystemScriptBindings::GetParticlesWithNativeArray", HasExplicitThis = true, ThrowsException = true)] extern private int GetParticlesWithNativeArray(IntPtr particles, int particlesLength, int size, int offset); public int GetParticles([Out] NativeArray<Particle> particles, int size, int offset) { unsafe { return GetParticlesWithNativeArray((IntPtr)particles.GetUnsafePtr(), particles.Length, size, offset); } } public int GetParticles([Out] NativeArray<Particle> particles, int size) { return GetParticles(particles, size, 0); } public int GetParticles([Out] NativeArray<Particle> particles) { return GetParticles(particles, -1); } // Set/get custom particle data [FreeFunction(Name = "ParticleSystemScriptBindings::SetCustomParticleData", HasExplicitThis = true, ThrowsException = true)] extern public void SetCustomParticleData([NotNull] List<Vector4> customData, ParticleSystemCustomData streamIndex); [FreeFunction(Name = "ParticleSystemScriptBindings::GetCustomParticleData", HasExplicitThis = true, ThrowsException = true)] extern public int GetCustomParticleData([NotNull] List<Vector4> customData, ParticleSystemCustomData streamIndex); // Set/get the playback state extern public PlaybackState GetPlaybackState(); extern public void SetPlaybackState(PlaybackState playbackState); // Set/get the trail data [FreeFunction(Name = "ParticleSystemScriptBindings::GetTrailData", HasExplicitThis = true)] extern private void GetTrailDataInternal(ref Trails trailData); public Trails GetTrails() { var result = new Trails(); result.Allocate(); GetTrailDataInternal(ref result); return result; } public int GetTrails(ref Trails trailData) { trailData.Allocate(); GetTrailDataInternal(ref trailData); return trailData.positions.Count; } [FreeFunction(Name = "ParticleSystemScriptBindings::SetTrailData", HasExplicitThis = true)] extern public void SetTrails(Trails trailData); // Playback [FreeFunction(Name = "ParticleSystemScriptBindings::Simulate", HasExplicitThis = true)] extern public void Simulate(float t, [DefaultValue("true")] bool withChildren, [DefaultValue("true")] bool restart, [DefaultValue("true")] bool fixedTimeStep); public void Simulate(float t, [DefaultValue("true")] bool withChildren, [DefaultValue("true")] bool restart) { Simulate(t, withChildren, restart, true); } public void Simulate(float t, [DefaultValue("true")] bool withChildren) { Simulate(t, withChildren, true); } public void Simulate(float t) { Simulate(t, true); } [FreeFunction(Name = "ParticleSystemScriptBindings::Play", HasExplicitThis = true)] extern public void Play([DefaultValue("true")] bool withChildren); public void Play() { Play(true); } [FreeFunction(Name = "ParticleSystemScriptBindings::Pause", HasExplicitThis = true)] extern public void Pause([DefaultValue("true")] bool withChildren); public void Pause() { Pause(true); } [FreeFunction(Name = "ParticleSystemScriptBindings::Stop", HasExplicitThis = true)] extern public void Stop([DefaultValue("true")] bool withChildren, [DefaultValue("ParticleSystemStopBehavior.StopEmitting")] ParticleSystemStopBehavior stopBehavior); public void Stop([DefaultValue("true")] bool withChildren) { Stop(withChildren, ParticleSystemStopBehavior.StopEmitting); } public void Stop() { Stop(true); } [FreeFunction(Name = "ParticleSystemScriptBindings::Clear", HasExplicitThis = true)] extern public void Clear([DefaultValue("true")] bool withChildren); public void Clear() { Clear(true); } [FreeFunction(Name = "ParticleSystemScriptBindings::IsAlive", HasExplicitThis = true)] extern public bool IsAlive([DefaultValue("true")] bool withChildren); public bool IsAlive() { return IsAlive(true); } // Emission [RequiredByNativeCode] public void Emit(int count) { Emit_Internal(count); } [NativeName("SyncJobs()->Emit")] extern private void Emit_Internal(int count); [NativeName("SyncJobs()->EmitParticlesExternal")] extern public void Emit(EmitParams emitParams, int count); [NativeName("SyncJobs()->EmitParticleExternal")] extern private void EmitOld_Internal(ref ParticleSystem.Particle particle); // Fire a sub-emitter public void TriggerSubEmitter(int subEmitterIndex) { TriggerSubEmitterForAllParticles(subEmitterIndex); } public void TriggerSubEmitter(int subEmitterIndex, ref ParticleSystem.Particle particle) { TriggerSubEmitterForParticle(subEmitterIndex, particle); } public void TriggerSubEmitter(int subEmitterIndex, List<ParticleSystem.Particle> particles) { if (particles == null) TriggerSubEmitterForAllParticles(subEmitterIndex); else TriggerSubEmitterForParticles(subEmitterIndex, particles); } [FreeFunction(Name = "ParticleSystemScriptBindings::TriggerSubEmitterForParticle", HasExplicitThis = true)] extern internal void TriggerSubEmitterForParticle(int subEmitterIndex, ParticleSystem.Particle particle); [FreeFunction(Name = "ParticleSystemScriptBindings::TriggerSubEmitterForParticles", HasExplicitThis = true)] extern private void TriggerSubEmitterForParticles(int subEmitterIndex, List<ParticleSystem.Particle> particles); [FreeFunction(Name = "ParticleSystemScriptBindings::TriggerSubEmitterForAllParticles", HasExplicitThis = true)] extern private void TriggerSubEmitterForAllParticles(int subEmitterIndex); [FreeFunction(Name = "ParticleSystemGeometryJob::ResetPreMappedBufferMemory")] extern public static void ResetPreMappedBufferMemory(); [FreeFunction(Name = "ParticleSystemGeometryJob::SetMaximumPreMappedBufferCounts")] extern public static void SetMaximumPreMappedBufferCounts(int vertexBuffersCount, int indexBuffersCount); [NativeName("SetUsesAxisOfRotation")] extern public void AllocateAxisOfRotationAttribute(); [NativeName("SetUsesMeshIndex")] extern public void AllocateMeshIndexAttribute(); [NativeName("SetUsesCustomData")] extern public void AllocateCustomDataAttribute(ParticleSystemCustomData stream); extern public bool has3DParticleRotations { [NativeName("Has3DParticleRotations")] get; } extern public bool hasNonUniformParticleSizes { [NativeName("HasNonUniformParticleSizes")] get; } unsafe extern internal void* GetManagedJobData(); extern internal JobHandle GetManagedJobHandle(); extern internal void SetManagedJobHandle(JobHandle handle); [FreeFunction("ScheduleManagedJob", ThrowsException = true)] unsafe internal static extern JobHandle ScheduleManagedJob(ref JobsUtility.JobScheduleParameters parameters, void* additionalData); [ThreadSafe] unsafe internal static extern void CopyManagedJobData(void* systemPtr, out NativeParticleData particleData); [FreeFunction(Name = "ParticleSystemEditor::SetupDefaultParticleSystemType", HasExplicitThis = true)] extern internal void SetupDefaultType(ParticleSystemSubEmitterType type); [NativeProperty("GetState()->localToWorld", TargetType = TargetType.Field)] extern internal Matrix4x4 localToWorldMatrix { get; } [NativeName("GetNoiseModule().GeneratePreviewTexture")] extern internal void GenerateNoisePreviewTexture(Texture2D dst); extern internal void CalculateEffectUIData(ref int particleCount, ref float fastestParticle, ref float slowestParticle); extern internal int GenerateRandomSeed(); [FreeFunction(Name = "ParticleSystemScriptBindings::CalculateEffectUISubEmitterData", HasExplicitThis = true)] extern internal bool CalculateEffectUISubEmitterData(ref int particleCount, ref float fastestParticle, ref float slowestParticle); [FreeFunction(Name = "ParticleSystemScriptBindings::CheckVertexStreamsMatchShader")] extern internal static bool CheckVertexStreamsMatchShader(bool hasTangent, bool hasColor, int texCoordChannelCount, Material material, ref bool tangentError, ref bool colorError, ref bool uvError); [FreeFunction(Name = "ParticleSystemScriptBindings::GetMaxTexCoordStreams")] extern internal static int GetMaxTexCoordStreams(); } public partial struct ParticleCollisionEvent { [FreeFunction(Name = "ParticleSystemScriptBindings::InstanceIDToColliderComponent")] extern static private Component InstanceIDToColliderComponent(int instanceID); } internal class ParticleSystemExtensionsImpl { [FreeFunction(Name = "ParticleSystemScriptBindings::GetSafeCollisionEventSize")] extern internal static int GetSafeCollisionEventSize([NotNull] ParticleSystem ps); [FreeFunction(Name = "ParticleSystemScriptBindings::GetCollisionEventsDeprecated")] extern internal static int GetCollisionEventsDeprecated([NotNull] ParticleSystem ps, GameObject go, [Out] ParticleCollisionEvent[] collisionEvents); [FreeFunction(Name = "ParticleSystemScriptBindings::GetSafeTriggerParticlesSize")] extern internal static int GetSafeTriggerParticlesSize([NotNull] ParticleSystem ps, int type); [FreeFunction(Name = "ParticleSystemScriptBindings::GetCollisionEvents")] extern internal static int GetCollisionEvents([NotNull] ParticleSystem ps, [NotNull] GameObject go, [NotNull] List<ParticleCollisionEvent> collisionEvents); [FreeFunction(Name = "ParticleSystemScriptBindings::GetTriggerParticles")] extern internal static int GetTriggerParticles([NotNull] ParticleSystem ps, int type, [NotNull] List<ParticleSystem.Particle> particles); [FreeFunction(Name = "ParticleSystemScriptBindings::GetTriggerParticlesWithData")] extern internal static int GetTriggerParticlesWithData([NotNull] ParticleSystem ps, int type, [NotNull] List<ParticleSystem.Particle> particles, ref ParticleSystem.ColliderData colliderData); [FreeFunction(Name = "ParticleSystemScriptBindings::SetTriggerParticles")] extern internal static void SetTriggerParticles([NotNull] ParticleSystem ps, int type, [NotNull] List<ParticleSystem.Particle> particles, int offset, int count); } public static partial class ParticlePhysicsExtensions { public static int GetSafeCollisionEventSize(this ParticleSystem ps) { return ParticleSystemExtensionsImpl.GetSafeCollisionEventSize(ps); } public static int GetCollisionEvents(this ParticleSystem ps, GameObject go, List<ParticleCollisionEvent> collisionEvents) { return ParticleSystemExtensionsImpl.GetCollisionEvents(ps, go, collisionEvents); } public static int GetSafeTriggerParticlesSize(this ParticleSystem ps, ParticleSystemTriggerEventType type) { return ParticleSystemExtensionsImpl.GetSafeTriggerParticlesSize(ps, (int)type); } public static int GetTriggerParticles(this ParticleSystem ps, ParticleSystemTriggerEventType type, List<ParticleSystem.Particle> particles) { return ParticleSystemExtensionsImpl.GetTriggerParticles(ps, (int)type, particles); } public static int GetTriggerParticles(this ParticleSystem ps, ParticleSystemTriggerEventType type, List<ParticleSystem.Particle> particles, out ParticleSystem.ColliderData colliderData) { if (type == ParticleSystemTriggerEventType.Exit) throw new InvalidOperationException("Querying the collider data for the Exit event is not currently supported."); else if (type == ParticleSystemTriggerEventType.Outside) throw new InvalidOperationException("Querying the collider data for the Outside event is not supported, because when a particle is outside the collision volume, it is always outside every collider."); colliderData = new ParticleSystem.ColliderData(); return ParticleSystemExtensionsImpl.GetTriggerParticlesWithData(ps, (int)type, particles, ref colliderData); } public static void SetTriggerParticles(this ParticleSystem ps, ParticleSystemTriggerEventType type, List<ParticleSystem.Particle> particles, int offset, int count) { if (particles == null) throw new ArgumentNullException("particles"); if (offset >= particles.Count) throw new ArgumentOutOfRangeException("offset", "offset should be smaller than the size of the particles list."); if ((offset + count) >= particles.Count) throw new ArgumentOutOfRangeException("count", "offset+count should be smaller than the size of the particles list."); ParticleSystemExtensionsImpl.SetTriggerParticles(ps, (int)type, particles, offset, count); } public static void SetTriggerParticles(this ParticleSystem ps, ParticleSystemTriggerEventType type, List<ParticleSystem.Particle> particles) { ParticleSystemExtensionsImpl.SetTriggerParticles(ps, (int)type, particles, 0, particles.Count); } } }
UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystem/ScriptBindings/ParticleSystem.bindings.cs", "repo_id": "UnityCsReference", "token_count": 6486 }
390
// 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 { class InheritVelocityModuleUI : ModuleUI { // Keep in sync with InheritVelocityModule.h enum Modes { Initial = 0, Current = 1 } SerializedProperty m_Mode; SerializedMinMaxCurve m_Curve; class Texts { public GUIContent mode = EditorGUIUtility.TrTextContent("Mode", "Specifies whether the emitter velocity is inherited as a one-shot when a particle is born, always using the current emitter velocity, or using the emitter velocity when the particle was born."); public GUIContent velocity = EditorGUIUtility.TrTextContent("Multiplier", "Controls the amount of emitter velocity inherited during each particle's lifetime."); public GUIContent[] modes = new GUIContent[] { EditorGUIUtility.TrTextContent("Initial"), EditorGUIUtility.TrTextContent("Current") }; } static Texts s_Texts; public InheritVelocityModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "InheritVelocityModule", displayName) { m_ToolTip = "Controls the velocity inherited from the emitter, for each particle."; } protected override void Init() { // Already initialized? if (m_Curve != null) return; if (s_Texts == null) s_Texts = new Texts(); m_Mode = GetProperty("m_Mode"); m_Curve = new SerializedMinMaxCurve(this, GUIContent.none, "m_Curve", kUseSignedRange); } override public void OnInspectorGUI(InitialModuleUI initial) { GUIPopup(s_Texts.mode, m_Mode, s_Texts.modes); GUIMinMaxCurve(s_Texts.velocity, m_Curve); } override public void UpdateCullingSupportedString(ref string text) { Init(); string failureReason = string.Empty; if (!m_Curve.SupportsProcedural(ref failureReason)) text += "\nInherit Velocity module curve: " + failureReason; } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/InheritVelocityModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/InheritVelocityModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 984 }
391
// 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; using UnityEditorInternal; namespace UnityEditor { class TriggerModuleUI : ModuleUI { enum OverlapOptions { Ignore = 0, Kill = 1, Callback = 2 } SerializedProperty m_Primitives; SerializedProperty m_Inside; SerializedProperty m_Outside; SerializedProperty m_Enter; SerializedProperty m_Exit; SerializedProperty m_ColliderQueryMode; SerializedProperty m_RadiusScale; static bool s_VisualizeBounds = false; class Texts { public GUIContent collisionShapes = EditorGUIUtility.TrTextContent("Colliders", "The list of collision shapes to use for the trigger."); public GUIContent createCollisionShape = EditorGUIUtility.TrTextContent("", "Create a GameObject containing a sphere collider and assign it to the list."); public GUIContent inside = EditorGUIUtility.TrTextContent("Inside", "What to do for particles that are inside the collision volume."); public GUIContent outside = EditorGUIUtility.TrTextContent("Outside", "What to do for particles that are outside the collision volume."); public GUIContent enter = EditorGUIUtility.TrTextContent("Enter", "Triggered once when particles enter the collision volume."); public GUIContent exit = EditorGUIUtility.TrTextContent("Exit", "Triggered once when particles leave the collision volume."); public GUIContent colliderQueryMode = EditorGUIUtility.TrTextContent("Collider Query Mode", "Required in order to get collider information when using the ParticleSystem.GetTriggerParticles script API. Disabled by default because it has a performance cost.\nWhen set to One, the script can retrieve the first collider in the list that the particle interacts with.\nSetting to All will return all colliders that the particle interacts with."); public GUIContent radiusScale = EditorGUIUtility.TrTextContent("Radius Scale", "Scale particle bounds by this amount to get more precise collisions."); public GUIContent visualizeBounds = EditorGUIUtility.TrTextContent("Visualize Bounds", "Render the collision bounds of the particles."); public GUIContent[] overlapOptions = new GUIContent[] { EditorGUIUtility.TrTextContent("Ignore"), EditorGUIUtility.TrTextContent("Kill"), EditorGUIUtility.TrTextContent("Callback") }; public GUIContent[] colliderQueryModeOptions = new GUIContent[] { EditorGUIUtility.TrTextContent("Disabled"), EditorGUIUtility.TrTextContent("One"), EditorGUIUtility.TrTextContent("All") }; } private static Texts s_Texts; ReorderableList m_PrimitivesList; public TriggerModuleUI(ParticleSystemUI owner, SerializedObject o, string displayName) : base(owner, o, "TriggerModule", displayName) { m_ToolTip = "Allows you to execute script code based on whether particles are inside or outside the collision shapes."; } protected override void Init() { // Already initialized? if (m_Inside != null) return; if (s_Texts == null) s_Texts = new Texts(); m_Primitives = GetProperty("primitives"); m_Inside = GetProperty("inside"); m_Outside = GetProperty("outside"); m_Enter = GetProperty("enter"); m_Exit = GetProperty("exit"); m_ColliderQueryMode = GetProperty("colliderQueryMode"); m_RadiusScale = GetProperty("radiusScale"); m_PrimitivesList = new ReorderableList(m_Primitives.m_SerializedObject, m_Primitives, true, false, true, true); m_PrimitivesList.headerHeight = 0; m_PrimitivesList.drawElementCallback = DrawPrimitiveElementCallback; m_PrimitivesList.elementHeight = kReorderableListElementHeight; m_PrimitivesList.onAddCallback = OnAddPrimitiveElementCallback; s_VisualizeBounds = EditorPrefs.GetBool("VisualizeTriggerBounds", false); } override public void OnInspectorGUI(InitialModuleUI initial) { DoListOfCollisionShapesGUI(); GUIPopup(s_Texts.inside, m_Inside, s_Texts.overlapOptions); GUIPopup(s_Texts.outside, m_Outside, s_Texts.overlapOptions); GUIPopup(s_Texts.enter, m_Enter, s_Texts.overlapOptions); GUIPopup(s_Texts.exit, m_Exit, s_Texts.overlapOptions); GUIPopup(s_Texts.colliderQueryMode, m_ColliderQueryMode, s_Texts.colliderQueryModeOptions); GUIFloat(s_Texts.radiusScale, m_RadiusScale); if (EditorGUIUtility.comparisonViewMode == EditorGUIUtility.ComparisonViewMode.None) { EditorGUI.BeginChangeCheck(); s_VisualizeBounds = GUIToggle(s_Texts.visualizeBounds, s_VisualizeBounds); if (EditorGUI.EndChangeCheck()) EditorPrefs.SetBool("VisualizeTriggerBounds", s_VisualizeBounds); } } private static GameObject CreateDefaultCollider(string name, ParticleSystem parentOfGameObject) { GameObject go = new GameObject(name); if (go) { if (parentOfGameObject) go.transform.parent = parentOfGameObject.transform; go.AddComponent<SphereCollider>(); return go; } return null; } private void DoListOfCollisionShapesGUI() { // only allow editing in single edit mode if (m_ParticleSystemUI.multiEdit) { EditorGUILayout.HelpBox("Trigger editing is only available when editing a single Particle System", MessageType.Info, true); return; } m_PrimitivesList.DoLayoutList(); } void OnAddPrimitiveElementCallback(ReorderableList list) { int index = m_Primitives.arraySize; m_Primitives.InsertArrayElementAtIndex(index); m_Primitives.GetArrayElementAtIndex(index).objectReferenceValue = null; } void DrawPrimitiveElementCallback(Rect rect, int index, bool isActive, bool isFocused) { var primitive = m_Primitives.GetArrayElementAtIndex(index); rect.height = kSingleLineHeight; Rect objectRect = new Rect(rect.x, rect.y, rect.width - EditorGUI.kSpacing - ParticleSystemStyles.Get().plus.fixedWidth, rect.height); GUIObject(objectRect, GUIContent.none, primitive, null); if (primitive.objectReferenceValue == null) { Rect buttonRect = new Rect(objectRect.xMax + EditorGUI.kSpacing, rect.y + 4, ParticleSystemStyles.Get().plus.fixedWidth, rect.height); if (GUI.Button(buttonRect, s_Texts.createCollisionShape, ParticleSystemStyles.Get().plus)) { GameObject go = CreateDefaultCollider("Collider " + (index + 1), m_ParticleSystemUI.m_ParticleSystems[0]); go.transform.localPosition = new Vector3(0, 0, 10 + index); // ensure each collider is not at the same position primitive.objectReferenceValue = go.GetComponent<Collider>(); } } } override public void OnSceneViewGUI() { if (s_VisualizeBounds == false) return; Color oldColor = Handles.color; Handles.color = CollisionModuleUI.s_CollisionBoundsColor; Matrix4x4 oldMatrix = Handles.matrix; Vector3[] points0 = new Vector3[20]; Vector3[] points1 = new Vector3[20]; Vector3[] points2 = new Vector3[20]; Handles.SetDiscSectionPoints(points0, Vector3.zero, Vector3.forward, Vector3.right, 360, 1.0f); Handles.SetDiscSectionPoints(points1, Vector3.zero, Vector3.up, -Vector3.right, 360, 1.0f); Handles.SetDiscSectionPoints(points2, Vector3.zero, Vector3.right, Vector3.up, 360, 1.0f); Vector3[] points = new Vector3[points0.Length + points1.Length + points2.Length]; points0.CopyTo(points, 0); points1.CopyTo(points, 20); points2.CopyTo(points, 40); foreach (ParticleSystem ps in m_ParticleSystemUI.m_ParticleSystems) { if (!ps.trigger.enabled) continue; ParticleSystem.Particle[] particles = new ParticleSystem.Particle[ps.particleCount]; int count = ps.GetParticles(particles); Matrix4x4 transform = Matrix4x4.identity; if (ps.main.simulationSpace == ParticleSystemSimulationSpace.Local) { transform = ps.localToWorldMatrix; } for (int i = 0; i < count; i++) { ParticleSystem.Particle particle = particles[i]; Vector3 size = particle.GetCurrentSize3D(ps); float radius = System.Math.Max(size.x, System.Math.Max(size.y, size.z)) * 0.5f * ps.trigger.radiusScale; Handles.matrix = transform * Matrix4x4.TRS(particle.position, Quaternion.identity, new Vector3(radius, radius, radius)); Handles.DrawPolyLine(points); } } Handles.color = oldColor; Handles.matrix = oldMatrix; } public override void UpdateCullingSupportedString(ref string text) { text += "\nTriggers module is enabled."; } } } // namespace UnityEditor
UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/TriggerModuleUI.cs/0
{ "file_path": "UnityCsReference/Modules/ParticleSystemEditor/ParticleSystemModules/TriggerModuleUI.cs", "repo_id": "UnityCsReference", "token_count": 4309 }
392
// 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.ComponentModel; namespace UnityEngine { // The definition of limits that can be applied to either ConfigurableJoint or CharacterJoint public partial struct SoftJointLimit { private float m_Limit; private float m_Bounciness; private float m_ContactDistance; public float limit { get { return m_Limit; } set { m_Limit = value; } } public float bounciness { get { return m_Bounciness; } set { m_Bounciness = value; } } public float contactDistance { get { return m_ContactDistance; } set { m_ContactDistance = value; } } } public struct SoftJointLimitSpring { private float m_Spring; private float m_Damper; public float spring { get { return m_Spring; } set { m_Spring = value; } } public float damper { get { return m_Damper; } set { m_Damper = value; } } } // How the joint's movement will behave along a local axis public partial struct JointDrive { private float m_PositionSpring; private float m_PositionDamper; private float m_MaximumForce; private int m_UseAcceleration; public float positionSpring { get { return m_PositionSpring; } set { m_PositionSpring = value; } } public float positionDamper { get { return m_PositionDamper; } set { m_PositionDamper = value; } } public float maximumForce { get { return m_MaximumForce; } set { m_MaximumForce = value; } } public bool useAcceleration { get { return m_UseAcceleration == 1; } set { m_UseAcceleration = value ? 1 : 0; } } } // The JointMotor is used to motorize a joint. public struct JointMotor { private float m_TargetVelocity; private float m_Force; private int m_FreeSpin; public float targetVelocity { get { return m_TargetVelocity; } set { m_TargetVelocity = value; } } public float force { get { return m_Force; } set { m_Force = value; } } public bool freeSpin { get { return m_FreeSpin == 1; } set { m_FreeSpin = value ? 1 : 0; } } } // JointSpring is used add a spring force to HingeJoint. public struct JointSpring { public float spring; public float damper; public float targetPosition; // We have to keep those as public variables because of a bug in the C# raycast sample. } public struct JointLimits { private float m_Min; private float m_Max; private float m_Bounciness; private float m_BounceMinVelocity; private float m_ContactDistance; public float min { get { return m_Min; } set { m_Min = value; } } public float max { get { return m_Max; } set { m_Max = value; } } public float bounciness { get { return m_Bounciness; } set { m_Bounciness = value; } } public float bounceMinVelocity { get { return m_BounceMinVelocity; } set { m_BounceMinVelocity = value; } } public float contactDistance { get { return m_ContactDistance; } set { m_ContactDistance = value; } } // NB - member fields can't be in other partial structs, so we cannot move this out; work out a plan to remove them then [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("minBounce and maxBounce are replaced by a single JointLimits.bounciness for both limit ends.", true)] public float minBounce; [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("minBounce and maxBounce are replaced by a single JointLimits.bounciness for both limit ends.", true)] public float maxBounce; } }
UnityCsReference/Modules/Physics/Managed/JointConstraints.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/Managed/JointConstraints.cs", "repo_id": "UnityCsReference", "token_count": 1363 }
393
// 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; namespace UnityEngine { [RequireComponent(typeof(Rigidbody))] [NativeHeader("Modules/Physics/HingeJoint.h")] [NativeClass("Unity::HingeJoint")] public class HingeJoint : Joint { extern public JointMotor motor { get; set; } extern public JointLimits limits { get; set; } extern public JointSpring spring { get; set; } extern public bool useMotor { get; set; } extern public bool useLimits { get; set; } extern public bool extendedLimits { get; set; } extern public bool useSpring { get; set; } extern public float velocity { get; } extern public float angle { get; } extern public bool useAcceleration { get; set; } } }
UnityCsReference/Modules/Physics/ScriptBindings/HingeJoint.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/HingeJoint.bindings.cs", "repo_id": "UnityCsReference", "token_count": 340 }
394
// 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.ComponentModel; namespace UnityEngine { partial struct RaycastHit { [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use textureCoord2 instead. (UnityUpgradable) -> textureCoord2")] public Vector2 textureCoord1 { get { return textureCoord2; } } } }
UnityCsReference/Modules/Physics/ScriptBindings/RaycastHit.deprecated.cs/0
{ "file_path": "UnityCsReference/Modules/Physics/ScriptBindings/RaycastHit.deprecated.cs", "repo_id": "UnityCsReference", "token_count": 165 }
395
// 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 { [CustomEditor(typeof(CustomCollider2D))] [CanEditMultipleObjects] class CustomCollider2DEditor : Collider2DEditorBase { public override void OnInspectorGUI() { serializedObject.Update(); base.OnInspectorGUI(); // Only show properties if there's a single target. if (targets.Length == 1) { var customCollider = target as CustomCollider2D; EditorGUI.BeginDisabledGroup(true); EditorGUILayout.IntField("Custom Shape Count", customCollider.customShapeCount); EditorGUILayout.IntField("Custom Vertex Count", customCollider.customVertexCount); EditorGUI.EndDisabledGroup(); } FinalizeInspectorGUI(); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/CustomCollider2DEditor.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Colliders/CustomCollider2DEditor.cs", "repo_id": "UnityCsReference", "token_count": 436 }
396
// 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; namespace UnityEditor { [CustomEditor(typeof(DistanceJoint2D))] [CanEditMultipleObjects] internal class DistanceJoint2DEditor : AnchoredJoint2DEditor { new public void OnSceneGUI() { if (!target) return; var distanceJoint2D = (DistanceJoint2D)target; // Ignore disabled joint. if (!distanceJoint2D.enabled) return; // Start and end points for distance gizmo Vector3 anchor = TransformPoint(distanceJoint2D.transform, distanceJoint2D.anchor); Vector3 connectedAnchor = distanceJoint2D.connectedAnchor; // If connectedBody present, convert the position to match that if (distanceJoint2D.connectedBody) connectedAnchor = TransformPoint(distanceJoint2D.connectedBody.transform, connectedAnchor); DrawDistanceGizmo(anchor, connectedAnchor, distanceJoint2D.distance); base.OnSceneGUI(); } } }
UnityCsReference/Modules/Physics2DEditor/Managed/Joints/DistanceJoint2DEditor.cs/0
{ "file_path": "UnityCsReference/Modules/Physics2DEditor/Managed/Joints/DistanceJoint2DEditor.cs", "repo_id": "UnityCsReference", "token_count": 504 }
397
// 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 { class ArticulationBodyEditorCommon { public static ArticulationBody FindEnabledParentArticulationBody(ArticulationBody body) { if (body.isRoot) return body; ArticulationBody parent = body.transform.parent.GetComponentInParent<ArticulationBody>(); while (parent && !parent.enabled) { parent = parent.transform.parent.GetComponentInParent<ArticulationBody>(); } return parent; } } }
UnityCsReference/Modules/PhysicsEditor/ArticulationBodyEditorCommon.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/ArticulationBodyEditorCommon.cs", "repo_id": "UnityCsReference", "token_count": 297 }
398
// 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.Linq; using UnityEngine.SceneManagement; using System; using UnityEditor.SceneManagement; namespace UnityEditor { public partial class PhysicsDebugWindow : EditorWindow { [System.Serializable] private class RenderedTransform : IEquatable<RenderedTransform> { public Transform Transform { get; private set; } public VisualisationState State { get; set; } public bool HasBody { get; private set; } [SerializeField] private bool m_ShowFolduot = false; private Rigidbody m_Rigidbody; private ArticulationBody m_Articulation; public RenderedTransform(Transform transform, VisualisationState visualizationState) { Transform = transform; State = visualizationState; Init(); } public RenderedTransform(Transform transform) { Transform = transform; State = VisualisationState.None; Init(); } private void Init() { if (Transform == null) { m_Rigidbody = null; m_Articulation = null; return; } m_Rigidbody = Transform.GetComponent<Rigidbody>(); if (m_Rigidbody == null) m_Articulation = Transform.GetComponent<ArticulationBody>(); HasBody = !(m_Rigidbody == null && m_Articulation == null); } public static implicit operator RenderedTransform(Transform transform) => new RenderedTransform(transform); public bool Equals(RenderedTransform other) { return Transform == other.Transform; } public bool IsValid() { return m_Rigidbody || m_Articulation; } public void DrawInfoTable() { if (!HasBody) return; if (m_Rigidbody) DrawRigidbodyInfo(m_Rigidbody); else if (m_Articulation) DrawArticulationBodyInfo(m_Articulation); } public void Visualize() { if (!HasBody) return; var showCenterOfMass = (State & VisualisationState.CenterOfMass) == VisualisationState.CenterOfMass; var showInertiaTensor = (State & VisualisationState.InertiaTensor) == VisualisationState.InertiaTensor; if (m_Rigidbody) VisualizeRigidbody(m_Rigidbody, showCenterOfMass, showInertiaTensor); else if (m_Articulation) VisualizeArticulationBody(m_Articulation, showCenterOfMass, showInertiaTensor); } private void DrawRigidbodyInfo(Rigidbody body) { EditorGUI.indentLevel++; EditorGUILayout.FloatField(Style.infoSpeed , body.linearVelocity.magnitude); EditorGUILayout.Vector3Field(Style.infoVel , body.linearVelocity); EditorGUILayout.Vector3Field(Style.infoAngVel , body.angularVelocity); EditorGUILayout.Vector3Field(Style.infoInertiaTensor , body.inertiaTensor); EditorGUILayout.Vector3Field(Style.infoInertiaTensorRotation, body.inertiaTensorRotation.eulerAngles); EditorGUILayout.Vector3Field(Style.infoLocalCenterOfMass , body.centerOfMass); EditorGUILayout.Vector3Field(Style.infoWorldCenterOfMass , body.worldCenterOfMass); EditorGUILayout.LabelField(Style.infoSleepState , body.IsSleeping() ? Style.sleep : Style.awake); EditorGUILayout.FloatField(Style.infoSleepThreshold , body.sleepThreshold); EditorGUILayout.FloatField(Style.infoMaxLinVel , body.maxLinearVelocity); EditorGUILayout.FloatField(Style.infoMaxAngVel , body.maxAngularVelocity); EditorGUILayout.IntField(Style.infoSolverIterations , body.solverIterations); EditorGUILayout.IntField(Style.infoSolverVelIterations , body.solverVelocityIterations); EditorGUI.indentLevel--; } private void DrawArticulationBodyInfo(ArticulationBody body) { EditorGUI.indentLevel++; EditorGUILayout.FloatField(Style.infoSpeed , body.linearVelocity.magnitude); EditorGUILayout.Vector3Field(Style.infoVel , body.linearVelocity); EditorGUILayout.Vector3Field(Style.infoAngVel , body.angularVelocity); EditorGUILayout.Vector3Field(Style.infoInertiaTensor , body.inertiaTensor); EditorGUILayout.Vector3Field(Style.infoInertiaTensorRotation, body.inertiaTensorRotation.eulerAngles); EditorGUILayout.Vector3Field(Style.infoLocalCenterOfMass , body.centerOfMass); EditorGUILayout.Vector3Field(Style.infoWorldCenterOfMass , body.worldCenterOfMass); EditorGUILayout.LabelField(Style.infoSleepState , body.IsSleeping() ? Style.sleep : Style.awake); EditorGUILayout.FloatField(Style.infoSleepThreshold , body.sleepThreshold); EditorGUILayout.FloatField(Style.infoMaxLinVel , body.maxLinearVelocity); EditorGUILayout.FloatField(Style.infoMaxAngVel , body.maxAngularVelocity); EditorGUILayout.IntField(Style.infoSolverIterations , body.solverIterations); EditorGUILayout.IntField(Style.infoSolverVelIterations , body.solverVelocityIterations); EditorGUILayout.IntField(Style.infoBodyIndex, body.index); if (!body.isRoot && body.jointType != ArticulationJointType.FixedJoint) { m_ShowFolduot = EditorGUILayout.Foldout(m_ShowFolduot, Style.infoJointInfo); if (m_ShowFolduot) { DrawArticulationReducedSpaceField(body.jointPosition, Style.infoJointPosition); DrawArticulationReducedSpaceField(body.jointVelocity, Style.infoJointVelocity); DrawArticulationReducedSpaceField(body.jointForce, Style.infoJointForce); DrawArticulationReducedSpaceField(body.jointAcceleration, Style.infoJointAcceleration); } } EditorGUI.indentLevel--; } private void DrawArticulationReducedSpaceField(ArticulationReducedSpace ars, GUIContent label) { if (ars.dofCount == 0) return; if (ars.dofCount == 1) EditorGUILayout.FloatField(label, ars[0]); else if (ars.dofCount == 2) EditorGUILayout.Vector2Field(label, new Vector2(ars[0], ars[1])); else if (ars.dofCount == 3) EditorGUILayout.Vector3Field(label, new Vector3(ars[0], ars[1], ars[2])); } } private bool DrawInfoTabHeader() { m_Collumns.value = EditorGUILayout.IntSlider(Style.numOfItems, m_Collumns.value, 1, 10); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Tracked objects: " + m_TransformsToRender.Count); if (GUILayout.Button(Style.clearLocked, Style.maxWidth150)) ClearAllLockedObjects(); EditorGUILayout.EndHorizontal(); if (m_TransformsToRender.Count == 0) { EditorGUILayout.HelpBox("Select a GameObject with a Rigidbody or an Articulation Body Component to display information about it", MessageType.Info); return false; } return true; } private void DrawSingleInfoItem(RenderedTransform tr) { if (tr == null) return; if (!tr.IsValid()) { m_ObjectsToRemove.AddLast(tr.Transform); return; } DrawObjectHeader(tr); tr.DrawInfoTable(); } private void DrawObjectHeader(RenderedTransform renderedTransform) { var locked = m_LockedObjects.ContainsKey(renderedTransform.Transform); var lockedPrev = locked; EditorGUI.BeginDisabledGroup(true); EditorGUILayout.ObjectField(Style.gameObjectField, renderedTransform.Transform.gameObject, typeof(GameObject), true); EditorGUI.EndDisabledGroup(); EditorGUILayout.BeginHorizontal(); var state = locked ? m_LockedObjects[renderedTransform.Transform] : VisualisationState.None; var statePrev = state; state = (VisualisationState)EditorGUILayout.EnumPopup(Style.drawGizmosFor.text, state); if (locked) { m_LockedObjects[renderedTransform.Transform] = state; renderedTransform.State = state; } else if (state != statePrev) { locked = true; lockedPrev = false; } if (state != statePrev) RepaintSceneAndGameViews(); locked = EditorGUILayout.ToggleLeft(Style.lockToggle, locked, Style.maxWidth50); EditorGUILayout.EndHorizontal(); if (locked != lockedPrev) { if (locked) m_ObjectsToAdd.AddLast(new RenderedTransform(renderedTransform.Transform, state)); else m_ObjectsToRemove.AddLast(renderedTransform.Transform); RepaintSceneAndGameViews(); } } private static bool HasBody(Transform transform) { var rb = transform.GetComponent<Rigidbody>(); if (rb != null) return true; var ab = transform.GetComponent<ArticulationBody>(); return ab != null; } #region Manage lists private RenderedTransform GetNextTransform(int index) { if (index < m_TransformsToRender.Count) return m_TransformsToRender[index]; return null; } private void AddLockedObjects() { foreach (var renderedTransform in m_ObjectsToAdd) { m_LockedObjects.Add(renderedTransform.Transform, renderedTransform.State); var existingIndex = m_TransformsToRender.IndexOf(renderedTransform); m_TransformsToRender[existingIndex].State = renderedTransform.State; } if (m_ObjectsToAdd.Count > 0) m_ObjectsToAdd.Clear(); } private void RemoveLockedObjects() { foreach (var tr in m_ObjectsToRemove) { m_LockedObjects.Remove(tr); if (!IsSelected(tr) || !HasBody(tr)) m_TransformsToRender.Remove(tr); } if (m_ObjectsToRemove.Count > 0) { UpdateSelection(); m_ObjectsToRemove.Clear(); } } private void ClearAllLockedObjects() { m_LockedObjects.Clear(); UpdateSelection(); RepaintSceneAndGameViews(); } private void SaveDictionary() { m_DictionaryKeys.Clear(); m_DictionaryValues.Clear(); foreach (var lockedObject in m_LockedObjects) { m_DictionaryKeys.Add(lockedObject.Key); m_DictionaryValues.Add(lockedObject.Value); } } private void LoadDictionary() { m_LockedObjects.Clear(); for (int i = 0; i < m_DictionaryKeys.Count; i++) { m_LockedObjects.Add(m_DictionaryKeys[i], m_DictionaryValues[i]); } m_DictionaryKeys.Clear(); m_DictionaryValues.Clear(); } private void OnSceneClose(Scene scene) { ClearInvalidInfoObjects(); PhysicsDebugDraw.UpdateFilter(); } private void OnSceneOpen(Scene scene, OpenSceneMode mode) { PhysicsDebugDraw.UpdateFilter(); } // This is usefull when Transfrom references change and they start pointing to null Transforms private void ClearInvalidInfoObjects() { foreach (var lockedObject in m_LockedObjects) if (lockedObject.Key == null) m_ObjectsToRemove.AddLast(lockedObject.Key); RemoveLockedObjects(); for(int i = 0; i < m_TransformsToRender.Count; i++) { if(m_TransformsToRender[i].Transform == null) { m_TransformsToRender.RemoveAt(i); i--; } } } private void UpdateSelection() { var selection = Selection.GetTransforms(SelectionMode.Unfiltered); m_TemporarySelection.Clear(); // Adds rendered transforms that are not part of the m_LockedObjects set foreach (var tr in m_TransformsToRender) if (!m_LockedObjects.ContainsKey(tr.Transform)) m_TemporarySelection.Add(tr.Transform); var addedTransforms = selection.Except(m_TemporarySelection); var removedTransforms = m_TemporarySelection.Except(selection); foreach (var tr in addedTransforms) { var newItem = new RenderedTransform(tr); if (!m_TransformsToRender.Contains(newItem) && newItem.HasBody) m_TransformsToRender.Add(newItem); } foreach (var tr in removedTransforms) { if (!m_LockedObjects.ContainsKey(tr)) m_TransformsToRender.Remove(tr); } Repaint(); } internal static void UpdateSelectionOnComponentAdd() { if (s_Window) s_Window.UpdateSelection(); } private bool IsSelected(Transform tr) { return Selection.GetTransforms(SelectionMode.Unfiltered).Contains(tr); } private VisualisationState ShouldDrawObject(Transform transform) { return m_LockedObjects.ContainsKey(transform) ? m_LockedObjects[transform] : VisualisationState.None; } private void RecalculateItemsPerRow(int totalItems, int rows) { m_NumberOfItemPerRow.Clear(); for (int i = 0; i < rows; i++) { if (totalItems > m_Collumns) { m_NumberOfItemPerRow.Add(m_Collumns); totalItems -= m_Collumns; } else { m_NumberOfItemPerRow.Add(totalItems); totalItems = 0; } } } #endregion #region Gizmos private void DrawComAndInertia() { foreach(var lockedObject in m_TransformsToRender) { if (lockedObject.State == VisualisationState.None) continue; lockedObject.Visualize(); } } private static void VisualizeRigidbody(Rigidbody rigidbody, bool showCenterOfMass, bool showInertiaTensor) { var centerOfMass = rigidbody.worldCenterOfMass; var rotation = rigidbody.transform.rotation * rigidbody.inertiaTensorRotation; var inertiaTensor = rigidbody.inertiaTensor; if (showCenterOfMass) { DrawCenterOfMassArrows(centerOfMass, rotation); } if (showInertiaTensor) { DrawInertiaTensorWithHandles(centerOfMass, rotation, inertiaTensor); } } private static void VisualizeArticulationBody(ArticulationBody articulationBody, bool showCenterOfMass, bool showInertiaTensor) { var centerOfMass = articulationBody.worldCenterOfMass; var rotation = articulationBody.transform.rotation * articulationBody.inertiaTensorRotation; var inertiaTensor = articulationBody.inertiaTensor; if (showCenterOfMass) { DrawCenterOfMassArrows(centerOfMass, rotation); } if (showInertiaTensor) { DrawInertiaTensorWithHandles(centerOfMass, rotation, inertiaTensor); } } private static void DrawCenterOfMassArrows(Vector3 centerOfMass, Quaternion rotation) { var size = PhysicsVisualizationSettings.centerOfMassUseScreenSize ? HandleUtility.GetHandleSize(centerOfMass) : 1f; Matrix4x4 matrix = Matrix4x4.TRS(centerOfMass, rotation, Vector3.one); using (new Handles.DrawingScope(ApplyAlphaToColor(Handles.xAxisColor), matrix)) { var thickness = 3f; Handles.DrawLine(Vector3.zero, Vector3.right * size, thickness); Handles.color = ApplyAlphaToColor(Handles.yAxisColor); Handles.DrawLine(Vector3.zero, Vector3.up * size, thickness); Handles.color = ApplyAlphaToColor(Handles.zAxisColor); Handles.DrawLine(Vector3.zero, Vector3.forward * size, thickness); } } private static void DrawInertiaTensorWithHandles(Vector3 center, Quaternion rotation, Vector3 inertiaTensor) { inertiaTensor *= PhysicsVisualizationSettings.inertiaTensorScale; Matrix4x4 matrix = Matrix4x4.TRS(center, rotation, Vector3.one); using (new Handles.DrawingScope(ApplyAlphaToColor(Handles.xAxisColor), matrix)) { float thickness = 3f; Handles.DrawLine(Vector3.zero, new Vector3(inertiaTensor.x, 0f, 0f), thickness); Handles.color = ApplyAlphaToColor(Handles.yAxisColor); Handles.DrawLine(Vector3.zero, new Vector3(0f, inertiaTensor.y, 0f), thickness); Handles.color = ApplyAlphaToColor(Handles.zAxisColor); Handles.DrawLine(Vector3.zero, new Vector3(0f, 0f, inertiaTensor.z), thickness); } } private static Color ApplyAlphaToColor(Color color) { color.a += 0.4f; color.a *= PhysicsVisualizationSettings.baseAlpha; color.a = Mathf.Clamp01(color.a); return color; } #endregion } }
UnityCsReference/Modules/PhysicsEditor/PhysicsDebugWindowInfoTab.cs/0
{ "file_path": "UnityCsReference/Modules/PhysicsEditor/PhysicsDebugWindowInfoTab.cs", "repo_id": "UnityCsReference", "token_count": 9657 }
399
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using Object = UnityEngine.Object; namespace UnityEditor.Presets { internal static class PresetEditorHelper { internal static Object[] InspectedObjects { get; set; } /// <summary> /// Internal flag set to true when the preset picker is opened. /// When an item is selected or cancelled, the flag is reset. /// </summary> internal static bool presetEditorOpen { get; set; } } }
UnityCsReference/Modules/PresetsEditor/PresetEditorHelper.cs/0
{ "file_path": "UnityCsReference/Modules/PresetsEditor/PresetEditorHelper.cs", "repo_id": "UnityCsReference", "token_count": 198 }
400
// 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 System.Runtime.InteropServices; using Unity.Collections.LowLevel.Unsafe; namespace UnityEditorInternal.Profiling.Memory.Experimental { [Obsolete("This API is outdated and will be removed. Please check out the Memory Profiler Package (https://docs.unity3d.com/Packages/com.unity.memoryprofiler@latest/)")] [NativeHeader("Runtime/Profiler/Public/MemorySnapshot/MemorySnapshotFileWriter.h")] public class MemorySnapshotFileWriter : IDisposable { private IntPtr m_Ptr; [NativeThrows] extern private void OpenFile(string filename); extern public void Close(); extern private static IntPtr Internal_Create(); extern private static void Internal_Destroy(IntPtr ptr); [NativeThrows] extern private void Internal_WriteEntryString(string data, int entryType); [NativeThrows] extern private void Internal_WriteEntryData(IntPtr data, int dataSize, int entryType); [NativeThrows] extern private void Internal_WriteEntryDataArray(IntPtr data, int dataSize, int numElements, int entryType); public void Open(string filename) { if (string.IsNullOrEmpty(filename)) { throw new ArgumentException("snapshot file path can not be null or empty."); } try { OpenFile(filename); } catch (Exception e) { throw e; } } public MemorySnapshotFileWriter(string filepath) { m_Ptr = Internal_Create(); Open(filepath); } public MemorySnapshotFileWriter() { m_Ptr = Internal_Create(); } public void Dispose() { if (m_Ptr != IntPtr.Zero) { Internal_Destroy(m_Ptr); m_Ptr = IntPtr.Zero; } GC.SuppressFinalize(this); } public void WriteEntry(FileFormat.EntryType entryType, string data) { if (data == null) { throw new NullReferenceException(); } Internal_WriteEntryString(data, (int)entryType); } public void WriteEntry<T>(FileFormat.EntryType entryType, T data) where T : struct { GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); try { IntPtr rawDataPtr = handle.AddrOfPinnedObject(); int dataSize = UnsafeUtility.SizeOf<T>(); Internal_WriteEntryData(rawDataPtr, dataSize, (int)entryType); } finally { handle.Free(); } } public void WriteEntryArray<T>(FileFormat.EntryType entryType, T[] data) where T : struct { GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); try { IntPtr rawDataPtr = handle.AddrOfPinnedObject(); int dataSize = UnsafeUtility.SizeOf<T>(); int numElements = data.Length; Internal_WriteEntryDataArray(rawDataPtr, dataSize, numElements, (int)entryType); } finally { handle.Free(); } } internal static class BindingsMarshaller { public static IntPtr ConvertToNative(MemorySnapshotFileWriter writer) => writer.m_Ptr; } } }
UnityCsReference/Modules/ProfilerEditor/MemoryProfiler/MemorySnapshotFileWriter.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/MemoryProfiler/MemorySnapshotFileWriter.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1741 }
401
// 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 UnityEditor.PackageManager.UI; using UnityEditor.Profiling.Analytics; using UnityEditorInternal; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.Experimental; namespace Unity.Profiling.Editor.UI { class BottlenecksDetailsViewController : ViewController { const string k_UxmlResourceName = "BottlenecksDetailsView.uxml"; const string k_UssClass_Dark = "bottlenecks-details-view__dark"; const string k_UssClass_Light = "bottlenecks-details-view__light"; const string k_UxmlIdentifier_CpuLabel = "bottlenecks-details-view__cpu-name-label"; const string k_UxmlIdentifier_GpuLabel = "bottlenecks-details-view__gpu-name-label"; const string k_UxmlIdentifier_CpuBar = "bottlenecks-details-view__cpu-duration-bar"; const string k_UxmlIdentifier_GpuBar = "bottlenecks-details-view__gpu-duration-bar"; const string k_UxmlIdentifier_CpuDurationLabel = "bottlenecks-details-view__cpu-duration-label"; const string k_UxmlIdentifier_GpuDurationLabel = "bottlenecks-details-view__gpu-duration-label"; const string k_UxmlIdentifier_TargetFrameDurationIndicator = "bottlenecks-details-view__target-frame-duration-indicator"; const string k_UxmlIdentifier_TargetFrameDurationIndicatorLabel = "bottlenecks-details-view__target-frame-duration-indicator__label"; const string k_UxmlIdentifier_TargetFrameDurationInstructionLabel = "bottlenecks-details-view__target-frame-duration-instruction-label"; const string k_UxmlIdentifier_DescriptionLabel = "bottlenecks-details-view__description-label"; const string k_UxmlIdentifier_NoDataLabel = "bottlenecks-details-view__no-data-label"; const string k_UssClass_DurationBarFillHighlighted = "bottlenecks-details-view__chart-bar__fill-highlighted"; const string k_UssClass_LinkCursor = "link-cursor"; const string k_LinkDescription_OpenCpuTimeline = "Open CPU Timeline"; const string k_LinkDescription_OpenProfileAnalyzer = "Open Profile Analyzer"; const string k_LinkDescription_OpenFrameDebugger = "Open Frame Debugger"; const string k_LinkDescription_OpenGpuProfilerDocumentation = "Open GPU Profiler Documentation"; static readonly string k_CpuActiveTimeTooltip = L10n.Tr("CPU Active Time is the duration within the frame that the CPU was doing work for.\n\nThis is computed by taking the longest thread duration between the main thread and the render thread, and subtracting the time that thread spent waiting, including waiting for 'present' and 'target FPS'.\n\nIt is possible for this duration to be longer than the 'CPU Time' value shown in the CPU Usage module's Timeline view when the Render Thread took longer than the Main Thread. This is because the Timeline view displays the beginning and end of the frame on the main thread."); static readonly string k_GpuTimeTooltip = L10n.Tr("GPU Time is the duration between when the GPU was sent its first command for the frame and when the GPU completed its work for that frame."); static readonly string k_TargetFrameDurationInstruction = $"The target frame time can be changed via the dropdown in the Highlights chart."; static readonly string k_NoValueText = L10n.Tr("No Value"); // Model. readonly IProfilerCaptureDataService m_DataService; readonly IProfilerPersistentSettingsService m_SettingsService; readonly ProfilerWindow m_ProfilerWindow; BottlenecksDetailsViewModel m_Model; // View. Label m_CpuLabel; Label m_GpuLabel; VisualElement m_CpuBar; VisualElement m_GpuBar; Label m_CpuDurationLabel; Label m_GpuDurationLabel; VisualElement m_TargetFrameDurationIndicator; Label m_TargetFrameDurationIndicatorLabel; Label m_TargetFrameDurationInstructionLabel; Label m_DescriptionLabel; Label m_NoDataLabel; public BottlenecksDetailsViewController( IProfilerCaptureDataService dataService, IProfilerPersistentSettingsService settingsService, ProfilerWindow profilerWindow) { m_DataService = dataService; m_SettingsService = settingsService; m_ProfilerWindow = profilerWindow; m_DataService.NewDataLoadedOrCleared += OnNewDataLoadedOrCleared; m_SettingsService.TargetFrameDurationChanged += OnTargetFrameDurationChanged; m_ProfilerWindow.SelectedFrameIndexChanged += OnNewFrameIndexSelectedInProfilerWindow; } protected override VisualElement LoadView() { var view = ViewControllerUtility.LoadVisualTreeFromBuiltInUxml(k_UxmlResourceName); if (view == null) throw new InvalidViewDefinedInUxmlException(); var themeUssClass = (EditorGUIUtility.isProSkin) ? k_UssClass_Dark : k_UssClass_Light; view.AddToClassList(themeUssClass); GatherReferencesInView(view); return view; } protected override void ViewLoaded() { base.ViewLoaded(); UpdateTargetFrameDurationIndicatorLabel(); m_CpuLabel.tooltip = k_CpuActiveTimeTooltip; m_GpuLabel.tooltip = k_GpuTimeTooltip; m_CpuBar.RegisterCallback<ClickEvent>(OnCpuBarClicked); m_CpuBar.tooltip = $"Click to inspect this frame in the CPU module's Timeline view."; m_GpuBar.RegisterCallback<ClickEvent>(OnGpuBarClicked); m_GpuBar.tooltip = $"Click to open the Frame Debugger."; m_TargetFrameDurationInstructionLabel.text = k_TargetFrameDurationInstruction; m_DescriptionLabel.RegisterCallback<PointerDownLinkTagEvent>(OnDescriptionLabelLinkSelected); m_DescriptionLabel.RegisterCallback<PointerOverLinkTagEvent>(OnLabelLinkPointerOver); m_DescriptionLabel.RegisterCallback<PointerOutLinkTagEvent>(OnLabelLinkPointerOut); m_NoDataLabel.text = L10n.Tr("There is no data available for the selected frame."); UIUtility.SetElementDisplay(m_NoDataLabel, false); View.RegisterCallback<GeometryChangedEvent>(ViewPerformedInitialLayout); } protected override void Dispose(bool disposing) { if (disposing) { m_ProfilerWindow.SelectedFrameIndexChanged -= OnNewFrameIndexSelectedInProfilerWindow; m_SettingsService.TargetFrameDurationChanged -= OnTargetFrameDurationChanged; m_DataService.NewDataLoadedOrCleared -= OnNewDataLoadedOrCleared; } base.Dispose(disposing); } void GatherReferencesInView(VisualElement view) { m_CpuLabel = view.Q<Label>(k_UxmlIdentifier_CpuLabel); m_GpuLabel = view.Q<Label>(k_UxmlIdentifier_GpuLabel); m_CpuBar = view.Q<VisualElement>(k_UxmlIdentifier_CpuBar); m_GpuBar = view.Q<VisualElement>(k_UxmlIdentifier_GpuBar); m_CpuDurationLabel = view.Q<Label>(k_UxmlIdentifier_CpuDurationLabel); m_GpuDurationLabel = view.Q<Label>(k_UxmlIdentifier_GpuDurationLabel); m_TargetFrameDurationIndicator = view.Q<VisualElement>(k_UxmlIdentifier_TargetFrameDurationIndicator); m_TargetFrameDurationIndicatorLabel = view.Q<Label>(k_UxmlIdentifier_TargetFrameDurationIndicatorLabel); m_TargetFrameDurationInstructionLabel = view.Q<Label>(k_UxmlIdentifier_TargetFrameDurationInstructionLabel); m_DescriptionLabel = view.Q<Label>(k_UxmlIdentifier_DescriptionLabel); m_NoDataLabel = view.Q<Label>(k_UxmlIdentifier_NoDataLabel); } void ViewPerformedInitialLayout(GeometryChangedEvent evt) { View.UnregisterCallback<GeometryChangedEvent>(ViewPerformedInitialLayout); ReloadData(); } void OnNewDataLoadedOrCleared() { if (!IsViewLoaded) return; ReloadData(); } void OnNewFrameIndexSelectedInProfilerWindow(long selectedFrameIndexLong) { if (!IsViewLoaded) return; ReloadData(); } void ReloadData() { // A value of -1 appears to be how the Profiler signifies 'current frame selected', so pick the last frame index. var selectedFrameIndex = Convert.ToInt32(m_ProfilerWindow.selectedFrameIndex); if (selectedFrameIndex == -1) selectedFrameIndex = m_DataService.FirstFrameIndex + m_DataService.FrameCount - 1; var targetFrameDurationNs = m_SettingsService.TargetFrameDurationNs; var modelBuilder = new BottlenecksDetailsViewModelBuilder(m_DataService); m_Model = modelBuilder.Build(selectedFrameIndex, targetFrameDurationNs); var hasInvalidModel = m_Model == null; UIUtility.SetElementDisplay(m_NoDataLabel, hasInvalidModel); if (hasInvalidModel) return; var largestDurationNs = Math.Max(m_Model.CpuDurationNs, Math.Max(m_Model.GpuDurationNs, m_Model.TargetFrameDurationNs)); var normalizedTargetFrameDuration = (float)m_Model.TargetFrameDurationNs / largestDurationNs; m_TargetFrameDurationIndicator.style.width = new Length(normalizedTargetFrameDuration * 100f, LengthUnit.Percent); ConfigureBar( m_CpuBar, m_CpuDurationLabel, m_Model.CpuDurationNs, largestDurationNs, m_Model.TargetFrameDurationNs); ConfigureBar( m_GpuBar, m_GpuDurationLabel, m_Model.GpuDurationNs, largestDurationNs, m_Model.TargetFrameDurationNs); m_DescriptionLabel.text = m_Model.LocalizedBottleneckDescription; } void OnTargetFrameDurationChanged() { UpdateTargetFrameDurationIndicatorLabel(); ReloadData(); } void UpdateTargetFrameDurationIndicatorLabel() { var targetFrameDuration = TimeFormatterUtility.FormatTimeNsToMs(m_SettingsService.TargetFrameDurationNs); var targetFramesPerSecond = Mathf.RoundToInt(1e9f / m_SettingsService.TargetFrameDurationNs); m_TargetFrameDurationIndicatorLabel.text = $"Target Frame Time\n{targetFrameDuration}\n<b>({targetFramesPerSecond} FPS)</b>"; } void ConfigureBar( VisualElement bar, Label barLabel, UInt64 barDurationNs, UInt64 largestDurationNs, UInt64 targetFrameDurationNs) { var barDurationNormalized = (float)barDurationNs / largestDurationNs; bar.style.width = new StyleLength(new Length(barDurationNormalized * 100f, LengthUnit.Percent)); barLabel.text = (barDurationNs == 0) ? k_NoValueText : TimeFormatterUtility.FormatTimeNsToMs(barDurationNs); if (barDurationNs > targetFrameDurationNs) bar.AddToClassList(k_UssClass_DurationBarFillHighlighted); else bar.RemoveFromClassList(k_UssClass_DurationBarFillHighlighted); } void OnCpuBarClicked(ClickEvent evt) { ProcessModelLink(BottlenecksDetailsViewModel.k_DescriptionLinkId_CpuTimeline); } void OnGpuBarClicked(ClickEvent evt) { ProcessModelLink(BottlenecksDetailsViewModel.k_DescriptionLinkId_FrameDebugger); } void OnDescriptionLabelLinkSelected(PointerDownLinkTagEvent evt) { var linkId = int.Parse(evt.linkID); ProcessModelLink(linkId); } void OnLabelLinkPointerOver(PointerOverLinkTagEvent evt) { ((VisualElement)evt.target).AddToClassList(k_UssClass_LinkCursor); } void OnLabelLinkPointerOut(PointerOutLinkTagEvent evt) { ((VisualElement)evt.target).RemoveFromClassList(k_UssClass_LinkCursor); } void ProcessModelLink(int linkId) { string linkDescription = string.Empty; switch (linkId) { case BottlenecksDetailsViewModel.k_DescriptionLinkId_CpuTimeline: // Open the CPU Module. var cpuModule = m_ProfilerWindow.GetProfilerModule<UnityEditorInternal.Profiling.CPUProfilerModule>(UnityEngine.Profiling.ProfilerArea.CPU); m_ProfilerWindow.selectedModule = cpuModule; cpuModule.ViewType = ProfilerViewType.Timeline; linkDescription = k_LinkDescription_OpenCpuTimeline; break; case BottlenecksDetailsViewModel.k_DescriptionLinkId_ProfileAnalyzer: // Open Profile Analyzer in the Package Manager. PackageManagerWindow.OpenPackageManager("Profile Analyzer"); linkDescription = k_LinkDescription_OpenProfileAnalyzer; break; case BottlenecksDetailsViewModel.k_DescriptionLinkId_FrameDebugger: // Open Frame Debugger. FrameDebuggerWindow.OpenWindow(); linkDescription = k_LinkDescription_OpenFrameDebugger; break; case BottlenecksDetailsViewModel.k_DescriptionLinkId_GpuProfilerDocumentation: // Open Third party profiling tools documentation page. Application.OpenURL("https://docs.unity3d.com/Manual/performance-profiling-tools.html"); linkDescription = k_LinkDescription_OpenGpuProfilerDocumentation; break; default: break; } if (!string.IsNullOrEmpty(linkDescription)) ProfilerWindowAnalytics.SendBottleneckLinkSelectedEvent(linkDescription); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/BottlenecksDetailsViewController.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/Bottlenecks/Details/BottlenecksDetailsViewController.cs", "repo_id": "UnityCsReference", "token_count": 5939 }
402
// 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.Profiling.LowLevel.Unsafe; using UnityEditor.Accessibility; using UnityEngine; using UnityEngine.Accessibility; namespace UnityEditorInternal { internal class ProfilerColors { static ProfilerColors() { s_DefaultColors = new Color[] { ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Render), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Scripts), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.BurstJobs), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Other), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Physics), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Animation), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Audio), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.AudioJob), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.AudioUpdateJob), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Lighting), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.GC), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.VSync), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Memory), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Internal), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.UI), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Build), ProfilerUnsafeUtility.GetCategoryColor(ProfilerCategoryColor.Input), }; s_DefaultColorsLuminanceValues = new float[s_DefaultColors.Length]; VisionUtility.GetLuminanceValuesForPalette(s_DefaultColors, ref s_DefaultColorsLuminanceValues); // Chart Areas are defined by stats in ProfilerStats.cpp file. // Color are driven by CPU profiler chart area colors and must be consistent with CPU timeline sample colors. ProfilerCategoryColor[] defaultChartColors = new ProfilerCategoryColor[] { ProfilerCategoryColor.Render, ProfilerCategoryColor.Scripts, ProfilerCategoryColor.Physics, ProfilerCategoryColor.Animation, ProfilerCategoryColor.GC, ProfilerCategoryColor.VSync, ProfilerCategoryColor.Lighting, ProfilerCategoryColor.UI, ProfilerCategoryColor.Other, // Colors below are currently only used in Timeline view ProfilerCategoryColor.Audio, ProfilerCategoryColor.AudioJob, ProfilerCategoryColor.AudioUpdateJob, ProfilerCategoryColor.Memory, ProfilerCategoryColor.Internal, ProfilerCategoryColor.Build, ProfilerCategoryColor.Input, }; s_DefaultChartColors = new Color[defaultChartColors.Length]; for (int i = 0; i < defaultChartColors.Length; i++) { var colorIndex = (int)defaultChartColors[i]; s_DefaultChartColors[i] = s_DefaultColors[colorIndex]; } s_ColorBlindSafeChartColors = new Color[s_DefaultChartColors.Length]; VisionUtility.GetColorBlindSafePalette(s_ColorBlindSafeChartColors, 0.3f, 1f); s_ColorBlindSafeColors = new Color[] { s_ColorBlindSafeChartColors[0], s_ColorBlindSafeChartColors[1], s_ColorBlindSafeChartColors[1], s_ColorBlindSafeChartColors[8], s_ColorBlindSafeChartColors[2], s_ColorBlindSafeChartColors[3], s_ColorBlindSafeChartColors[9], s_ColorBlindSafeChartColors[10], s_ColorBlindSafeChartColors[11], s_ColorBlindSafeChartColors[6], s_ColorBlindSafeChartColors[4], s_ColorBlindSafeChartColors[5], s_ColorBlindSafeChartColors[12], s_ColorBlindSafeChartColors[13], s_ColorBlindSafeChartColors[7], s_ColorBlindSafeChartColors[14], s_ColorBlindSafeChartColors[15], }; s_ColorBlindSafeColorsLuminanceValues = new float[s_ColorBlindSafeColors.Length]; VisionUtility.GetLuminanceValuesForPalette(s_ColorBlindSafeColors, ref s_ColorBlindSafeColorsLuminanceValues); } public static Color[] chartAreaColors { get { return UserAccessiblitySettings.colorBlindCondition == ColorBlindCondition.Default ? s_DefaultChartColors : s_ColorBlindSafeChartColors; } } public static Color[] timelineColors { get { return UserAccessiblitySettings.colorBlindCondition == ColorBlindCondition.Default ? s_DefaultColors : s_ColorBlindSafeColors; } } public static float[] timelineColorsLuminance { get { return UserAccessiblitySettings.colorBlindCondition == ColorBlindCondition.Default ? s_DefaultColorsLuminanceValues : s_ColorBlindSafeColorsLuminanceValues; } } static readonly Color[] s_DefaultColors; static readonly float[] s_DefaultColorsLuminanceValues; static readonly Color[] s_ColorBlindSafeColors; static readonly float[] s_ColorBlindSafeColorsLuminanceValues; static readonly Color[] s_DefaultChartColors; static readonly Color[] s_ColorBlindSafeChartColors; } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerColors.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerColors.cs", "repo_id": "UnityCsReference", "token_count": 2606 }
403
// 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 Unity.Profiling; using UnityEditor; using UnityEngine; namespace UnityEditorInternal.Profiling { internal class FlowLinesDrawer { const int k_EarlyNextEventArrowHorizontalPadding = 8; static readonly System.Comparison<FlowEventData> k_FlowEventStartTimeComparer = (FlowEventData x, FlowEventData y) => { var xPos = x.rect.xMin; var yPos = y.rect.xMin; // Always sort the end event using the time it was completed. if (x.flowEventType == ProfilerFlowEventType.End) { xPos = x.rect.xMax; } else if (y.flowEventType == ProfilerFlowEventType.End) { yPos = y.rect.xMax; } return xPos.CompareTo(yPos); }; static readonly System.Comparison<FlowEventData> k_FlowEventCompletionTimeComparer = (FlowEventData x, FlowEventData y) => { var xPos = x.rect.xMax; var yPos = y.rect.xMax; // Always sort the begin event using the time it was started. if (x.flowEventType == ProfilerFlowEventType.Begin) { xPos = x.rect.xMin; } else if (y.flowEventType == ProfilerFlowEventType.Begin) { yPos = y.rect.xMin; } return xPos.CompareTo(yPos); }; Dictionary<uint, List<FlowEventData>> m_Flows = new Dictionary<uint, List<FlowEventData>>(); List<Vector3> m_CachedLinePoints = new List<Vector3>(); HashSet<float> m_CachedParallelNextVerticalPositions = new HashSet<float>(); List<Vector3> m_CachedSelectionLinePoints = new List<Vector3>(); public bool hasSelectedEvent { get; private set; } public void AddFlowEvent(ProfilerTimelineGUI.ThreadInfo.FlowEventData flowEventData, Rect sampleRect, bool isSelectedSample) { var flowEvent = flowEventData.flowEvent; var flowEventId = flowEvent.FlowId; var flowEventType = flowEvent.FlowEventType; if (!m_Flows.TryGetValue(flowEventId, out var flowEvents)) { flowEvents = new List<FlowEventData>(); m_Flows[flowEventId] = flowEvents; } flowEvents.Add(new FlowEventData() { rect = sampleRect, flowEventType = flowEventType, isSelected = isSelectedSample }); if (isSelectedSample) { hasSelectedEvent = true; } } public void Draw() { Handles.BeginGUI(); foreach (var flowKvp in m_Flows) { var flowEvents = flowKvp.Value; DrawFlow(flowEvents); } Handles.EndGUI(); } void DrawFlow(List<FlowEventData> flowEvents) { m_CachedLinePoints.Clear(); m_CachedSelectionLinePoints.Clear(); ProduceLinePointsForNextFlowEventsInCollection(flowEvents, ref m_CachedLinePoints, ref m_CachedSelectionLinePoints); ProduceLinePointsForParallelNextAndEndFlowEventsInCollection(flowEvents, ref m_CachedLinePoints, ref m_CachedSelectionLinePoints); DrawLines(m_CachedLinePoints.ToArray()); DrawSelectedLineIfNecessary(m_CachedSelectionLinePoints.ToArray()); } void ProduceLinePointsForNextFlowEventsInCollection(List<FlowEventData> flowEvents, ref List<Vector3> linePoints, ref List<Vector3> selectionLinePoints) { if (flowEvents.Count == 0) { return; } // We draw next event lines in start time order. SortFlowEventsInStartTimeOrder(flowEvents); for (int i = 0; i < flowEvents.Count; i++) { var flowEvent = flowEvents[i]; var flowEventRect = flowEvent.rect; switch (flowEvent.flowEventType) { case ProfilerFlowEventType.Next: { var previousFlowEventIndex = i - 1; if (previousFlowEventIndex < 0) { continue; } var previousFlowEvent = flowEvents[previousFlowEventIndex]; var previousFlowEventRect = previousFlowEvent.rect; var previousFlowEventRectXMax = previousFlowEventRect.xMax; var flowEventRectXMin = flowEventRect.xMin; var numberOfLinePointsAdded = 0; // Draw a right angle line when the previous event is a Begin. if (previousFlowEvent.flowEventType == ProfilerFlowEventType.Begin) { var halfBeginIndicatorSize = FlowIndicatorDrawer.textureVisualSize * 0.5f; var origin = new Vector2(previousFlowEventRect.xMin + halfBeginIndicatorSize.x, previousFlowEventRect.yMax + halfBeginIndicatorSize.y); var destination = new Vector2(flowEventRect.xMin, flowEventRect.yMax); numberOfLinePointsAdded = AddRightAngleLineToPoints(origin, destination, false, ref linePoints); } else { // Verify if the previous *completed* event was a parallel next. This allows us to draw from the last parallel next that completed, rather than the last parallel next that started. var hasPreviousCompletedFlowEvent = flowEvent.TryGetPreviousCompletedFlowEventInCollection(flowEvents, out var previousCompletedFlowEvent); var previousCompletedFlowEventWasAParallelNext = (hasPreviousCompletedFlowEvent && previousCompletedFlowEvent.flowEventType == ProfilerFlowEventType.ParallelNext); if (previousCompletedFlowEventWasAParallelNext) { // Draw a step-change style line from the previous completed flow event to this Next event. var previousCompletedFlowEventRect = previousCompletedFlowEvent.rect; var origin = previousCompletedFlowEventRect.max; var destination = new Vector2(flowEventRect.xMin, flowEventRect.yMax); numberOfLinePointsAdded = AddPointsForStepChangeFlowLineBetweenPointsToCollection(origin, destination, ref linePoints); } else { // If the previous event finished after this event started, draw from earlier in the previous event. if (previousFlowEventRectXMax > flowEventRectXMin) { var availableSpaceX = flowEventRectXMin - previousFlowEventRect.xMin; var offsetX = Mathf.Min(k_EarlyNextEventArrowHorizontalPadding, availableSpaceX * 0.5f); var originY = previousFlowEventRect.yMax; var destinationY = flowEventRect.yMax; if (destinationY < originY) { // Draw from the top of the marker if drawing upwards. originY = previousFlowEventRect.yMin; } var origin = new Vector2(flowEventRect.xMin - offsetX, originY); var destination = new Vector2(flowEventRect.xMin, flowEventRect.yMax); numberOfLinePointsAdded = AddRightAngleLineToPoints(origin, destination, false, ref linePoints); } else { // Draw a step-change style line from the previous event to this Next event. var origin = previousFlowEventRect.max; var destination = new Vector2(flowEventRect.xMin, flowEventRect.yMax); numberOfLinePointsAdded = AddPointsForStepChangeFlowLineBetweenPointsToCollection(origin, destination, ref linePoints); } } } // If the next event is selected, add its line points to the selection line. if (flowEvent.isSelected) { int newPointsStartIndex = linePoints.Count - numberOfLinePointsAdded; ExtractSelectionLinePointsFromEndOfCollection(linePoints, newPointsStartIndex, ref m_CachedSelectionLinePoints); } break; } } } } void ProduceLinePointsForParallelNextAndEndFlowEventsInCollection(List<FlowEventData> flowEvents, ref List<Vector3> linePoints, ref List<Vector3> selectionLinePoints) { if (flowEvents.Count == 0) { return; } // We draw parallel next and end event lines using completion time sorting. For example, the end event line should point to last *completed* event, not the last started. We also loop backwards so we only draw one horizontal line per thread when there are multiple parallel next events on one thread. SortFlowEventsInCompletionTimeOrder(flowEvents); var halfBeginIndicatorSize = FlowIndicatorDrawer.textureVisualSize * 0.5f; m_CachedParallelNextVerticalPositions.Clear(); var hasParallelNextEvents = false; var firstFlowEvent = flowEvents[0]; var firstFlowEventRect = firstFlowEvent.rect; var firstFlowEventPosition = new Vector2(firstFlowEventRect.xMin + halfBeginIndicatorSize.x, firstFlowEventRect.yMax + halfBeginIndicatorSize.y); var parallelNextVerticalMin = firstFlowEventPosition.y; var parallelNextVerticalMax = firstFlowEventPosition.y; for (int i = flowEvents.Count - 1; i >= 0; i--) { var flowEvent = flowEvents[i]; var flowEventRect = flowEvent.rect; switch (flowEvent.flowEventType) { case ProfilerFlowEventType.ParallelNext: { var flowEventRectYMax = flowEventRect.yMax; var origin = new Vector2(firstFlowEventRect.xMin + halfBeginIndicatorSize.x, flowEventRectYMax); var destination = new Vector2(flowEventRect.xMin, flowEventRectYMax); if (!m_CachedParallelNextVerticalPositions.Contains(flowEventRectYMax)) // Only draw one horizontal line per thread. { linePoints.Add(origin); linePoints.Add(destination); m_CachedParallelNextVerticalPositions.Add(flowEventRectYMax); hasParallelNextEvents = true; if (flowEventRectYMax < parallelNextVerticalMin) { parallelNextVerticalMin = flowEventRectYMax; } else if (flowEventRectYMax > parallelNextVerticalMax) { parallelNextVerticalMax = flowEventRectYMax; } } // If the parallel next event is selected, add its line points to the selection line. if (flowEvent.isSelected) { m_CachedSelectionLinePoints.Add(firstFlowEventPosition); m_CachedSelectionLinePoints.Add(new Vector2(firstFlowEventPosition.x, origin.y)); m_CachedSelectionLinePoints.Add(destination); } break; } case ProfilerFlowEventType.End: { // Draw a right-angled line from the previous event to the completion time of the end event. var previousFlowEventIndex = i - 1; if (previousFlowEventIndex < 0) { continue; } var previousFlowEvent = flowEvents[previousFlowEventIndex]; var previousFlowEventRect = previousFlowEvent.rect; var previousFlowEventRectXMax = previousFlowEventRect.xMax; var numberOfLinePointsAdded = 0; var origin = previousFlowEventRect.max; var destination = flowEventRect.max; numberOfLinePointsAdded = AddRightAngleLineToPoints(origin, destination, true, ref linePoints); // If the end event is selected, add its line points to the selection line. if (flowEvent.isSelected) { int newPointsStartIndex = linePoints.Count - numberOfLinePointsAdded; ExtractSelectionLinePointsFromEndOfCollection(linePoints, newPointsStartIndex, ref m_CachedSelectionLinePoints); } break; } } } if (hasParallelNextEvents) { // Draw vertical lines to the highest and lowest parallel next events. if (!Mathf.Approximately(parallelNextVerticalMin, firstFlowEventPosition.y)) { linePoints.Add(firstFlowEventPosition); linePoints.Add(new Vector2(firstFlowEventPosition.x, parallelNextVerticalMin)); } if (!Mathf.Approximately(parallelNextVerticalMax, firstFlowEventPosition.y)) { linePoints.Add(firstFlowEventPosition); linePoints.Add(new Vector2(firstFlowEventPosition.x, parallelNextVerticalMax)); } } } void SortFlowEventsInStartTimeOrder(List<FlowEventData> flowEvents) { if (flowEvents.Count > 0) { flowEvents.Sort(k_FlowEventStartTimeComparer); } } void SortFlowEventsInCompletionTimeOrder(List<FlowEventData> flowEvents) { if (flowEvents.Count > 0) { flowEvents.Sort(k_FlowEventCompletionTimeComparer); } } int AddRightAngleLineToPoints(Vector2 origin, Vector2 destination, bool horizontalFirst, ref List<Vector3> linePoints) { int previousLinePointsCount = linePoints.Count; Vector2 destinationMidpoint = (horizontalFirst) ? new Vector2(destination.x, origin.y) : new Vector2(origin.x, destination.y); linePoints.Add(origin); linePoints.Add(destinationMidpoint); linePoints.Add(destinationMidpoint); linePoints.Add(destination); return linePoints.Count - previousLinePointsCount; } int AddPointsForStepChangeFlowLineBetweenPointsToCollection(Vector2 origin, Vector2 destination, ref List<Vector3> linePoints) { int previousLinePointsCount = linePoints.Count; if (!Mathf.Approximately(destination.y, origin.y)) { var horizontalADestination = new Vector2(Mathf.Lerp(origin.x, destination.x, 0.5f), origin.y); linePoints.Add(origin); linePoints.Add(horizontalADestination); var verticalOrigin = horizontalADestination; var verticalDestination = new Vector2(horizontalADestination.x, destination.y); linePoints.Add(verticalOrigin); linePoints.Add(verticalDestination); linePoints.Add(verticalDestination); linePoints.Add(destination); } else { // If the destination is at the same height as the origin, just create a single line. linePoints.Add(origin); linePoints.Add(destination); } return linePoints.Count - previousLinePointsCount; } void ExtractSelectionLinePointsFromEndOfCollection(List<Vector3> linePoints, int pointsStartIndex, ref List<Vector3> selectionLinePoints) { // The selection line is drawn as one continuous line, as opposed to the flow lines which are many individual lines. Therefore, remove all duplicate overlapping points by taking each line's starting point. for (int j = pointsStartIndex; j < linePoints.Count; j += 2) { selectionLinePoints.Add(linePoints[j]); } // Add the last point, as there is no subsequent line beginning from here to capture this point. selectionLinePoints.Add(linePoints[linePoints.Count - 1]); } void DrawLines(Vector3[] points) { var color = Handles.color; Handles.color = Styles.color; Handles.DrawLines(points); Handles.color = color; } void DrawSelectedLineIfNecessary(Vector3[] selectedLinePositions) { if (m_CachedSelectionLinePoints.Count > 0) { Handles.DrawAAPolyLine(EditorGUIUtility.whiteTexture, Styles.selectedWidth, selectedLinePositions); } } struct FlowEventData { public Rect rect; public ProfilerFlowEventType flowEventType; public bool isSelected; // Find the last flow event that completed prior to this flow event starting. public bool TryGetPreviousCompletedFlowEventInCollection(List<FlowEventData> collection, out FlowEventData previousCompletedFlowEvent) { var hasPreviousCompletedFlowEvent = false; previousCompletedFlowEvent = default; foreach (var flowEvent in collection) { var flowEventRect = flowEvent.rect; // Did it complete before we started? if (flowEventRect.xMax < rect.xMin) { hasPreviousCompletedFlowEvent = true; // Is it later than the previously stored value? if (flowEventRect.xMax > previousCompletedFlowEvent.rect.xMax) { previousCompletedFlowEvent = flowEvent; } } } return hasPreviousCompletedFlowEvent; } } static class Styles { public static readonly Color color = new Color(220f, 220f, 220f, 1f); public static readonly Color selectedColor = new Color(255f, 255f, 255f); public static readonly float selectedWidth = 2f; } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPU/FlowLinesDrawer.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/CPU/FlowLinesDrawer.cs", "repo_id": "UnityCsReference", "token_count": 9962 }
404
// 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 UnityEditorInternal; using UnityEngine; namespace UnityEditor { internal class ObjectInfo { public int instanceId; public long memorySize; public int reason; public List<ObjectInfo> referencedBy; public string name; public string className; } [System.Serializable] internal class MemoryElement { public List<MemoryElement> children = null; public MemoryElement parent = null; public ObjectInfo memoryInfo; public long totalMemory; public int totalChildCount; public string name; public bool expanded; public string description; public MemoryElement() { children = new List<MemoryElement>(); } public MemoryElement(string n) { expanded = false; name = n; children = new List<MemoryElement>(); description = ""; } public MemoryElement(ObjectInfo memInfo, bool finalize) { expanded = false; memoryInfo = memInfo; name = memoryInfo.name; totalMemory = memInfo != null ? memInfo.memorySize : 0; totalChildCount = 1; if (finalize) children = new List<MemoryElement>(); } public MemoryElement(string n, List<MemoryElement> groups) { name = n; expanded = false; description = ""; totalMemory = 0; totalChildCount = 0; children = new List<MemoryElement>(); foreach (MemoryElement group in groups) { AddChild(group); } } public void ExpandChildren() { if (children != null) return; children = new List<MemoryElement>(); for (int i = 0; i < ReferenceCount(); i++) AddChild(new MemoryElement(memoryInfo.referencedBy[i], false)); } public int AccumulatedChildCount() { return totalChildCount; } public int ChildCount() { if (children != null) return children.Count; return ReferenceCount(); } public int ReferenceCount() { return memoryInfo != null && memoryInfo.referencedBy != null ? memoryInfo.referencedBy.Count : 0; } public void AddChild(MemoryElement node) { if (node == this) { throw new System.Exception("Should not AddChild to itself"); } children.Add(node); node.parent = this; totalMemory += node.totalMemory; totalChildCount += node.totalChildCount; } public int GetChildIndexInList() { for (int i = 0; i < parent.children.Count; i++) { if (parent.children[i] == this) return i; } return parent.children.Count; } public MemoryElement GetPrevNode() { int siblingindex = GetChildIndexInList() - 1; if (siblingindex >= 0) { MemoryElement prev = parent.children[siblingindex]; while (prev.expanded) { prev = prev.children[prev.children.Count - 1]; } return prev; } else return parent; } public MemoryElement GetNextNode() { if (expanded && children.Count > 0) return children[0]; int nextsiblingindex = GetChildIndexInList() + 1; if (nextsiblingindex < parent.children.Count) return parent.children[nextsiblingindex]; MemoryElement p = parent; while (p.parent != null) { int parentsiblingindex = p.GetChildIndexInList() + 1; if (parentsiblingindex < p.parent.children.Count) return p.parent.children[parentsiblingindex]; p = p.parent; } return null; } public MemoryElement GetRoot() { if (parent != null) return parent.GetRoot(); return this; } public MemoryElement FirstChild() { return children[0]; } public MemoryElement LastChild() { if (!expanded) return this; return children[children.Count - 1].LastChild(); } } [System.Serializable] class MemoryElementSelection { private MemoryElement m_Selected = null; public void SetSelection(MemoryElement node) { m_Selected = node; MemoryElement parent = node.parent; while (parent != null) { parent.expanded = true; parent = parent.parent; } } public void ClearSelection() { m_Selected = null; } public bool isSelected(MemoryElement node) { return (m_Selected == node); } public MemoryElement Selected { get { return m_Selected; } } public void MoveUp() { if (m_Selected == null) return; if (m_Selected.parent == null) return; MemoryElement prev = m_Selected.GetPrevNode(); if (prev.parent != null) SetSelection(prev); else SetSelection(prev.FirstChild()); } public void MoveDown() { if (m_Selected == null) return; if (m_Selected.parent == null) return; MemoryElement next = m_Selected.GetNextNode(); if (next != null) SetSelection(next); } public void MoveFirst() { if (m_Selected == null) return; if (m_Selected.parent == null) return; SetSelection(m_Selected.GetRoot().FirstChild()); } public void MoveLast() { if (m_Selected == null) return; if (m_Selected.parent == null) return; SetSelection(m_Selected.GetRoot().LastChild()); } public void MoveParent() { if (m_Selected == null) return; if (m_Selected.parent == null) return; if (m_Selected.parent.parent == null) return; SetSelection(m_Selected.parent); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryElement.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Memory/MemoryElement.cs", "repo_id": "UnityCsReference", "token_count": 3632 }
405
// 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.Editor; using UnityEngine; using UnityEngine.Profiling; namespace UnityEditorInternal.Profiling { [Serializable] [ProfilerModuleMetadata("Video", typeof(LocalizationResource), IconPath = "Profiler.Video")] internal class VideoProfilerModule : ProfilerModuleBase { const int k_DefaultOrderIndex = 5; internal override ProfilerArea area => ProfilerArea.Video; public override bool usesCounters => false; private protected override int defaultOrderIndex => k_DefaultOrderIndex; private protected override string legacyPreferenceKey => "ProfilerChartVideo"; public override void DrawToolbar(Rect position) { DrawEmptyToolbar(); } public override void DrawDetailsView(Rect position) { DrawDetailsViewText(position); } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Video/VideoProfilerModule.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ProfilerModules/Video/VideoProfilerModule.cs", "repo_id": "UnityCsReference", "token_count": 357 }
406
// 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 Unity.Profiling.Editor.UI { class InvalidViewDefinedInUxmlException : Exception { const string k_Message = "Unable to create view from Uxml. Uxml must contain at least one child element."; public InvalidViewDefinedInUxmlException() : base(k_Message) { } } }
UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ViewControllerSystem/InvalidViewDefinedInUxmlException.cs/0
{ "file_path": "UnityCsReference/Modules/ProfilerEditor/ProfilerWindow/ViewControllerSystem/InvalidViewDefinedInUxmlException.cs", "repo_id": "UnityCsReference", "token_count": 152 }
407
// 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 Unity.Properties { public static partial class PropertyContainer { class GetPropertyVisitor : PathVisitor { public static readonly UnityEngine.Pool.ObjectPool<GetPropertyVisitor> Pool = new UnityEngine.Pool.ObjectPool<GetPropertyVisitor>(() => new GetPropertyVisitor(), null, v => v.Reset()); public IProperty Property; public override void Reset() { base.Reset(); Property = default; ReadonlyVisit = true; } protected override void VisitPath<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value) { Property = property; } } /// <summary> /// Gets an <see cref="IProperty"/> on the specified container for the given <see cref="PropertyPath"/>. /// </summary> /// <remarks> /// While the container data is not actually read from or written to. The container itself is needed to resolve polymorphic fields and list elements. /// </remarks> /// <param name="container">The container tree to search.</param> /// <param name="path">The property path to resolve.</param> /// <typeparam name="TContainer">The strongly typed container.</typeparam> /// <returns>The <see cref="IProperty"/> for the given path.</returns> /// <exception cref="ArgumentNullException">The specified container or path is null.</exception> /// <exception cref="InvalidContainerTypeException">The specified container type is not valid for visitation.</exception> /// <exception cref="MissingPropertyBagException">The specified container type has no property bag associated with it.</exception> /// <exception cref="InvalidPathException">The specified <paramref name="path"/> was not found or could not be resolved.</exception> public static IProperty GetProperty<TContainer>(TContainer container, in PropertyPath path) => GetProperty(ref container, path); /// <summary> /// Gets an <see cref="IProperty"/> on the specified container for the given <see cref="PropertyPath"/>. /// </summary> /// <remarks> /// While the container data is not actually read from or written to. The container itself is needed to resolve polymorphic fields and list elements. /// </remarks> /// <param name="container">The container whose property will be returned.</param> /// <param name="path">The property path to resolve.</param> /// <typeparam name="TContainer">The strongly typed container.</typeparam> /// <returns>The <see cref="IProperty"/> for the given path.</returns> /// <exception cref="ArgumentNullException">The specified container or path is null.</exception> /// <exception cref="InvalidContainerTypeException">The specified container type is not valid for visitation.</exception> /// <exception cref="MissingPropertyBagException">The specified container type has no property bag associated with it.</exception> /// <exception cref="InvalidPathException">The specified <paramref name="path"/> was not found or could not be resolved.</exception> public static IProperty GetProperty<TContainer>(ref TContainer container, in PropertyPath path) { if (TryGetProperty(ref container, path, out var property, out var returnCode)) { return property; } switch (returnCode) { case VisitReturnCode.NullContainer: throw new ArgumentNullException(nameof(container)); case VisitReturnCode.InvalidContainerType: throw new InvalidContainerTypeException(container.GetType()); case VisitReturnCode.MissingPropertyBag: throw new MissingPropertyBagException(container.GetType()); case VisitReturnCode.InvalidPath: throw new ArgumentException($"Failed to get property for path=[{path}]"); default: throw new Exception($"Unexpected {nameof(VisitReturnCode)}=[{returnCode}]"); } } /// <summary> /// Gets an <see cref="IProperty"/> on the specified container for the given <see cref="PropertyPath"/>. /// </summary> /// <remarks> /// While the container data is not actually read from or written to. The container itself is needed to resolve polymorphic fields and list elements. /// </remarks> /// <param name="container">The container tree to search.</param> /// <param name="path">The property path to resolve.</param> /// <param name="property">When this method returns, contains the property associated with the specified path, if the property is found; otherwise, null.</param> /// <typeparam name="TContainer">The strongly typed container.</typeparam> /// <returns><see langword="true"/> if the property was found at the specified path; otherwise, <see langword="false"/>.</returns> public static bool TryGetProperty<TContainer>(TContainer container, in PropertyPath path, out IProperty property) => TryGetProperty(ref container, path, out property, out _); /// <summary> /// Gets an <see cref="IProperty"/> on the specified container for the given <see cref="PropertyPath"/>. /// </summary> /// <remarks> /// While the container data is not actually read from or written to. The container itself is needed to resolve polymorphic fields and list elements. /// </remarks> /// <param name="container">The container tree to search.</param> /// <param name="path">The property path to resolve.</param> /// <param name="property">When this method returns, contains the property associated with the specified path, if the property is found; otherwise, null.</param> /// <typeparam name="TContainer">The strongly typed container.</typeparam> /// <returns><see langword="true"/> if the property was found at the specified path; otherwise, <see langword="false"/>.</returns> public static bool TryGetProperty<TContainer>(ref TContainer container, in PropertyPath path, out IProperty property) => TryGetProperty(ref container, path, out property, out _); /// <summary> /// Gets an <see cref="IProperty"/> on the specified container for the given <see cref="PropertyPath"/>. /// </summary> /// <remarks> /// While the container data is not actually read from or written to. The container itself is needed to resolve polymorphic fields and list elements. /// </remarks> /// <param name="container">The container tree to search.</param> /// <param name="path">The property path to resolve.</param> /// <param name="property">When this method returns, contains the property associated with the specified path, if the property is found; otherwise, null.</param> /// <param name="returnCode">When this method returns, contains the return code.</param> /// <typeparam name="TContainer">The strongly typed container.</typeparam> /// <returns><see langword="true"/> if the property was found at the specified path; otherwise, <see langword="false"/>.</returns> public static bool TryGetProperty<TContainer>(ref TContainer container, in PropertyPath path, out IProperty property, out VisitReturnCode returnCode) { var getPropertyVisitor = GetPropertyVisitor.Pool.Get(); try { getPropertyVisitor.Path = path; if (!TryAccept(getPropertyVisitor, ref container, out returnCode)) { property = default; return false; } returnCode = getPropertyVisitor.ReturnCode; property = getPropertyVisitor.Property; return returnCode == VisitReturnCode.Ok; } finally { GetPropertyVisitor.Pool.Release(getPropertyVisitor); } } } }
UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+GetProperty.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/Algorithms/PropertyContainer+GetProperty.cs", "repo_id": "UnityCsReference", "token_count": 3028 }
408
// 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 Unity.Properties { /// <summary> /// An <see cref="IPropertyBag{T}"/> implementation for a built in array of <typeparamref name="TElement"/>. /// </summary> /// <typeparam name="TElement">The element type.</typeparam> public sealed class ArrayPropertyBag<TElement> : IndexedCollectionPropertyBag<TElement[], TElement> { /// <inheritdoc/> protected override InstantiationKind InstantiationKind => InstantiationKind.PropertyBagOverride; /// <inheritdoc/> protected override TElement[] InstantiateWithCount(int count) => new TElement[count]; /// <inheritdoc/> protected override TElement[] Instantiate() => Array.Empty<TElement>(); } }
UnityCsReference/Modules/Properties/Runtime/PropertyBags/ArrayPropertyBag.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/ArrayPropertyBag.cs", "repo_id": "UnityCsReference", "token_count": 297 }
409
// 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 Unity.Properties { /// <summary> /// A <see cref="IPropertyBag{T}"/> implementation for a generic set of elements using the <see cref="ISet{TElement}"/> interface. /// </summary> /// <typeparam name="TSet">The collection type.</typeparam> /// <typeparam name="TElement">The element type.</typeparam> public class SetPropertyBagBase<TSet, TElement> : PropertyBag<TSet>, ISetPropertyBag<TSet, TElement> where TSet : ISet<TElement> { class SetElementProperty : Property<TSet, TElement>, ISetElementProperty<TElement> { internal TElement m_Value; public override string Name => m_Value.ToString(); public override bool IsReadOnly => true; public override TElement GetValue(ref TSet container) => m_Value; public override void SetValue(ref TSet container, TElement value) => throw new InvalidOperationException("Property is ReadOnly."); public TElement Key => m_Value; public object ObjectKey => m_Value; } /// <summary> /// Shared instance of a set element property. We re-use the same instance to avoid allocations. /// </summary> readonly SetElementProperty m_Property = new SetElementProperty(); public override PropertyCollection<TSet> GetProperties() { return PropertyCollection<TSet>.Empty; } public override PropertyCollection<TSet> GetProperties(ref TSet container) { return new PropertyCollection<TSet>(GetPropertiesEnumerable(container)); } IEnumerable<IProperty<TSet>> GetPropertiesEnumerable(TSet container) { foreach (var element in container) { m_Property.m_Value = element; yield return m_Property; } } void ICollectionPropertyBagAccept<TSet>.Accept(ICollectionPropertyBagVisitor visitor, ref TSet container) { visitor.Visit(this, ref container); } void ISetPropertyBagAccept<TSet>.Accept(ISetPropertyBagVisitor visitor, ref TSet container) { visitor.Visit(this, ref container); } void ISetPropertyAccept<TSet>.Accept<TContainer>(ISetPropertyVisitor visitor, Property<TContainer, TSet> property, ref TContainer container, ref TSet dictionary) { using (new AttributesScope(m_Property, property)) { visitor.Visit<TContainer, TSet, TElement>(property, ref container, ref dictionary); } } /// <summary> /// Gets the property associated with the specified name. /// </summary> /// <param name="container">The container hosting the data.</param> /// <param name="key">The key to lookup.</param> /// <param name="property">When this method returns, contains the property associated with the specified name, if the name is found; otherwise, null.</param> /// <returns><see langword="true"/> if the <see cref="INamedProperties{TContainer}"/> contains a property with the specified name; otherwise, <see langword="false"/>.</returns> public bool TryGetProperty(ref TSet container, object key, out IProperty<TSet> property) { if (container.Contains((TElement) key)) { property = new SetElementProperty {m_Value = (TElement) key}; return true; } property = default; return false; } } }
UnityCsReference/Modules/Properties/Runtime/PropertyBags/SetPropertyBag.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/PropertyBags/SetPropertyBag.cs", "repo_id": "UnityCsReference", "token_count": 1469 }
410
// 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.Concurrent; using System.Collections.Generic; using System.Text; using UnityEngine.Scripting; namespace Unity.Properties { /// <summary> /// Describes how a new instance is created. /// </summary> public enum InstantiationKind { /// <summary> /// The type instantiation will be done using <see cref="Activator"/>. /// </summary> Activator, /// <summary> /// The type instantiation will be done via a method override in <see cref="PropertyBag{TContainer}"/> /// </summary> PropertyBagOverride, /// <summary> /// Not type instantiation should be performed for this type. /// </summary> NotInstantiatable } interface IConstructor { /// <summary> /// Returns <see langword="true"/> if the type can be instantiated. /// </summary> InstantiationKind InstantiationKind { get; } } /// <summary> /// The <see cref="IConstructor{T}"/> provides a type instantiation implementation for a given <typeparamref name="T"/> type. This is an internal interface. /// </summary> /// <typeparam name="T">The type to be instantiated.</typeparam> interface IConstructor<out T> : IConstructor { /// <summary> /// Construct an instance of <typeparamref name="T"/> and returns it. /// </summary> /// <returns>A new instance of type <typeparamref name="T"/>.</returns> T Instantiate(); } /// <summary> /// The <see cref="IConstructorWithCount{T}"/> provides type instantiation for a collection <typeparamref name="T"/> type with a count. This is an internal interface. /// </summary> /// <typeparam name="T">The type to be instantiated.</typeparam> interface IConstructorWithCount<out T> : IConstructor { /// <summary> /// Construct an instance of <typeparamref name="T"/> and returns it. /// </summary> /// <returns>A new instance of type <typeparamref name="T"/>.</returns> T InstantiateWithCount(int count); } /// <summary> /// Utility class around <see cref="System.Type"/>. /// </summary> public static class TypeUtility { interface ITypeConstructor { /// <summary> /// Returns <see langword="true"/> if the type can be instantiated. /// </summary> bool CanBeInstantiated { get; } /// <summary> /// Construct an instance of the underlying type. /// </summary> /// <returns>A new instance of concrete type.</returns> object Instantiate(); } interface ITypeConstructor<T> : ITypeConstructor { /// <summary> /// Construct an instance of <typeparamref name="T"/> and returns it. /// </summary> /// <returns>A new instance of type <typeparamref name="T"/>.</returns> new T Instantiate(); /// <summary> /// Sets an explicit instantiation method for the <see cref="T"/> type. /// </summary> /// <param name="constructor">The instantiation method.</param> /// <typeparam name="T">The type to set the explicit instantiation method.</typeparam> void SetExplicitConstructor(Func<T> constructor); } class TypeConstructor<T> : ITypeConstructor<T> { /// <summary> /// An explicit user defined constructor for <typeparamref name="T"/>. /// </summary> Func<T> m_ExplicitConstructor; /// <summary> /// An implicit constructor relying on <see cref="Activator.CreateInstance{T}"/> /// </summary> Func<T> m_ImplicitConstructor; /// <summary> /// An explicit constructor provided by an interface implementation. This is used to provide type construction through property bags. /// </summary> IConstructor<T> m_OverrideConstructor; /// <inheritdoc/> bool ITypeConstructor.CanBeInstantiated { get { if (null != m_ExplicitConstructor) return true; if (null != m_OverrideConstructor) { if (m_OverrideConstructor.InstantiationKind == InstantiationKind.NotInstantiatable) return false; if (m_OverrideConstructor.InstantiationKind == InstantiationKind.PropertyBagOverride) return true; } return null != m_ImplicitConstructor; } } public TypeConstructor() { // Try to get a construction provider through the property bag. m_OverrideConstructor = Internal.PropertyBagStore.GetPropertyBag<T>() as IConstructor<T>; SetImplicitConstructor(); } void SetImplicitConstructor() { var type = typeof(T); if (type.IsValueType) { m_ImplicitConstructor = CreateValueTypeInstance; return; } if (type.IsAbstract) { return; } if (typeof(UnityEngine.ScriptableObject).IsAssignableFrom(type)) { m_ImplicitConstructor = CreateScriptableObjectInstance; return; } if (null != type.GetConstructor(Array.Empty<Type>())) { m_ImplicitConstructor = CreateClassInstance; } } static T CreateValueTypeInstance() { return default; } static T CreateScriptableObjectInstance() { return (T) (object) UnityEngine.ScriptableObject.CreateInstance(typeof(T)); } static T CreateClassInstance() { return Activator.CreateInstance<T>(); } /// <inheritdoc/> public void SetExplicitConstructor(Func<T> constructor) { m_ExplicitConstructor = constructor; } /// <inheritdoc/> T ITypeConstructor<T>.Instantiate() { // First try an explicit constructor set by users. if (null != m_ExplicitConstructor) return m_ExplicitConstructor.Invoke(); // Try custom constructor provided by the property bag. if (null != m_OverrideConstructor) { if (m_OverrideConstructor.InstantiationKind == InstantiationKind.NotInstantiatable) throw new InvalidOperationException($"The type '{typeof(T).Name}' is not constructable."); if (m_OverrideConstructor.InstantiationKind == InstantiationKind.PropertyBagOverride) { return m_OverrideConstructor.Instantiate(); } } // Use the implicit construction provided by Activator. if (null != m_ImplicitConstructor) return m_ImplicitConstructor.Invoke(); throw new InvalidOperationException($"The type '{typeof(T).Name}' is not constructable."); } /// <inheritdoc/> object ITypeConstructor.Instantiate() => ((ITypeConstructor<T>) this).Instantiate(); } /// <summary> /// The <see cref="NonConstructable"/> class can be used when we can't fully resolve a <see cref="TypeConstructor{T}"/> for a given type. /// This can happen if a given type has no property bag and we don't have a strong type to work with. /// </summary> class NonConstructable : ITypeConstructor { bool ITypeConstructor.CanBeInstantiated => false; public object Instantiate() => throw new InvalidOperationException($"The type is not instantiatable."); } /// <summary> /// The <see cref="Cache{T}"/> represents a strongly typed reference to a type constructor. /// </summary> /// <typeparam name="T">The type the constructor can initialize.</typeparam> /// <remarks> /// Any types in this set are also present in the <see cref="TypeUtility.s_TypeConstructors"/> set. /// </remarks> struct Cache<T> { /// <summary> /// Reference to the strongly typed <see cref="ITypeConstructor{TType}"/> for this type. This allows direct access without any dictionary lookups. /// </summary> public static ITypeConstructor<T> TypeConstructor; } /// <summary> /// The <see cref="TypeConstructorVisitor"/> is used to /// </summary> class TypeConstructorVisitor : ITypeVisitor { public ITypeConstructor TypeConstructor; public void Visit<TContainer>() => TypeConstructor = CreateTypeConstructor<TContainer>(); } /// <summary> /// Provides untyped references to the <see cref="ITypeConstructor{TType}"/> implementations. /// </summary> /// <remarks> /// Any types in this set are also present in the <see cref="Cache{T}"/>. /// </remarks> static readonly ConcurrentDictionary<Type, ITypeConstructor> s_TypeConstructors = new ConcurrentDictionary<Type, ITypeConstructor>(); static readonly System.Reflection.MethodInfo s_CreateTypeConstructor; static readonly ConcurrentDictionary<Type, string> s_CachedResolvedName; static readonly UnityEngine.Pool.ObjectPool<StringBuilder> s_Builders; private static readonly object syncedPoolObject = new object(); static TypeUtility() { s_CachedResolvedName = new ConcurrentDictionary<Type, string>(); s_Builders = new UnityEngine.Pool.ObjectPool<StringBuilder>(()=> new StringBuilder(), null, sb => sb.Clear()); SetExplicitInstantiationMethod(() => string.Empty); foreach (var method in typeof(TypeUtility).GetMethods(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)) { if (method.Name != nameof(CreateTypeConstructor) || !method.IsGenericMethod) continue; s_CreateTypeConstructor = method; break; } if (null == s_CreateTypeConstructor) throw new InvalidProgramException(); } /// <summary> /// Utility method to get the name of a type which includes the parent type(s). /// </summary> /// <param name="type">The <see cref="System.Type"/> we want the name of.</param> /// <returns>The display name of the type.</returns> public static string GetTypeDisplayName(Type type) { if (s_CachedResolvedName.TryGetValue(type, out var name)) return name; var index = 0; name = GetTypeDisplayName(type, type.GetGenericArguments(), ref index); s_CachedResolvedName[type] = name; return name; } static string GetTypeDisplayName(Type type, IReadOnlyList<Type> args, ref int argIndex) { if (type == typeof(int)) return "int"; if (type == typeof(uint)) return "uint"; if (type == typeof(short)) return "short"; if (type == typeof(ushort)) return "ushort"; if (type == typeof(byte)) return "byte"; if (type == typeof(char)) return "char"; if (type == typeof(bool)) return "bool"; if (type == typeof(long)) return "long"; if (type == typeof(ulong)) return "ulong"; if (type == typeof(float)) return "float"; if (type == typeof(double)) return "double"; if (type == typeof(string)) return "string"; var name = type.Name; if (type.IsGenericParameter) { return name; } if (type.IsNested) { name = $"{GetTypeDisplayName(type.DeclaringType, args, ref argIndex)}.{name}"; } if (!type.IsGenericType) return name; var tickIndex = name.IndexOf('`'); var count = type.GetGenericArguments().Length; if (tickIndex > -1) { count = int.Parse(name.Substring(tickIndex + 1)); name = name.Remove(tickIndex); } var genericTypeNames = default(StringBuilder); lock (syncedPoolObject) { genericTypeNames = s_Builders.Get(); } try { for (var i = 0; i < count && argIndex < args.Count; i++, argIndex++) { if (i != 0) genericTypeNames.Append(", "); genericTypeNames.Append(GetTypeDisplayName(args[argIndex])); } if (genericTypeNames.Length > 0) { name = $"{name}<{genericTypeNames}>"; } } finally { lock (syncedPoolObject) { s_Builders.Release(genericTypeNames); } } return name; } /// <summary> /// Utility method to return the base type. /// </summary> /// <param name="type">The <see cref="System.Type"/> for which we want the base type.</param> /// <returns>The base type.</returns> public static Type GetRootType(this Type type) { if (type.IsInterface) return null; var baseType = type.IsValueType ? typeof(ValueType) : typeof(object); while (baseType != type.BaseType) { type = type.BaseType; } return type; } /// <summary> /// Creates a new strongly typed <see cref="TypeConstructor{TType}"/> for the specified <paramref name="type"/>. /// </summary> /// <remarks> /// This method will attempt to use properties to get the strongly typed reference. If no property bag exists it will fallback to a reflection based approach. /// </remarks> /// <param name="type">The type to create a constructor for.</param> /// <returns>A <see cref="TypeConstructor{TType}"/> for the specified type.</returns> [Preserve] static ITypeConstructor CreateTypeConstructor(Type type) { var properties = Internal.PropertyBagStore.GetPropertyBag(type); // Attempt to use properties double dispatch to call the strongly typed create method. This avoids expensive reflection calls. if (null != properties) { var visitor = new TypeConstructorVisitor(); properties.Accept(visitor); return visitor.TypeConstructor; } if (type.ContainsGenericParameters) { var constructor = new NonConstructable(); s_TypeConstructors[type] = constructor; return constructor; } // This type has no property bag associated with it. Fallback to reflection to create our type constructor. return s_CreateTypeConstructor .MakeGenericMethod(type) .Invoke(null, null) as ITypeConstructor; } /// <summary> /// Creates a new strongly typed <see cref="TypeConstructor{TType}"/> for the specified <typeparamref name="T"/>. /// </summary> /// <typeparam name="T">The type to create a constructor for.</typeparam> /// <returns>A <see cref="TypeConstructor{TType}"/> for the specified type.</returns> static ITypeConstructor<T> CreateTypeConstructor<T>() { var constructor = new TypeConstructor<T>(); Cache<T>.TypeConstructor = constructor; s_TypeConstructors[typeof(T)] = constructor; return constructor; } /// <summary> /// Gets the internal <see cref="ITypeConstructor"/> for the specified <paramref name="type"/>. /// </summary> /// <remarks> /// This method will return null if the type is not constructable on the current platform. /// </remarks> /// <param name="type">The type to get a constructor for.</param> /// <returns>A <see cref="ITypeConstructor"/> for the specified type.</returns> static ITypeConstructor GetTypeConstructor(Type type) { return s_TypeConstructors.TryGetValue(type, out var constructor) ? constructor : CreateTypeConstructor(type); } /// <summary> /// Gets the internal <see cref="ITypeConstructor"/> for the specified <typeparamref name="T"/>. /// </summary> /// <remarks> /// This method will return null if the type is not constructable on the current platform. /// </remarks> /// <typeparam name="T">The type to create a constructor for.</typeparam> /// <returns>A <see cref="ITypeConstructor{TType}"/> for the specified type.</returns> static ITypeConstructor<T> GetTypeConstructor<T>() { return null != Cache<T>.TypeConstructor ? Cache<T>.TypeConstructor : CreateTypeConstructor<T>(); } /// <summary> /// Returns <see langword="true"/> if the specified type is instantiatable. /// </summary> /// <remarks> /// Instantiatable is defined as either having a default or implicit constructor or having a registered instantiation method. /// </remarks> /// <param name="type">The type to query.</param> /// <returns><see langword="true"/> if the given type is instantiatable.</returns> public static bool CanBeInstantiated(Type type) => GetTypeConstructor(type).CanBeInstantiated; /// <summary> /// Returns <see langword="true"/> if type <see cref="T"/> is instantiatable. /// </summary> /// <remarks> /// Instantiatable is defined as either having a default or implicit constructor or having a registered instantiation method. /// </remarks> /// <typeparam name="T">The type to query.</typeparam> /// <returns><see langword="true"/> if type <see cref="T"/> is instantiatable.</returns> public static bool CanBeInstantiated<T>() => GetTypeConstructor<T>().CanBeInstantiated; /// <summary> /// Sets an explicit instantiation method for the <see cref="T"/> type. /// </summary> /// <param name="constructor">The instantiation method.</param> /// <typeparam name="T">The type to set the explicit instantiation method.</typeparam> public static void SetExplicitInstantiationMethod<T>(Func<T> constructor) => GetTypeConstructor<T>().SetExplicitConstructor(constructor); /// <summary> /// Creates a new instance of the specified <see cref="T"/>. /// </summary> /// <typeparam name="T">The type we want to create a new instance of.</typeparam> /// <returns>A new instance of the <see cref="T"/>.</returns> /// <exception cref="InvalidOperationException">The specified <see cref="T"/> has no available instantiation method.</exception> public static T Instantiate<T>() { var constructor = GetTypeConstructor<T>(); CheckCanBeInstantiated(constructor); return constructor.Instantiate(); } /// <summary> /// Creates a new instance of the specified <see cref="T"/>. /// </summary> /// <param name="instance">When this method returns, contains the created instance, if type instantiation succeeded; otherwise, the default value for <typeparamref name="T"/>.</param> /// <typeparam name="T">The type to create an instance of.</typeparam> /// <returns><see langword="true"/> if a new instance of type <see cref="T"/> was created; otherwise, <see langword="false"/>.</returns> public static bool TryInstantiate<T>(out T instance) { var constructor = GetTypeConstructor<T>(); if (constructor.CanBeInstantiated) { instance = constructor.Instantiate(); return true; } instance = default; return false; } /// <summary> /// Creates a new instance of the given type type and returns it as <see cref="T"/>. /// </summary> /// <param name="derivedType">The type we want to create a new instance of.</param> /// <typeparam name="T">The type we want to create a new instance of.</typeparam> /// <returns>a new instance of the <see cref="T"/> type.</returns> /// <exception cref="ArgumentException">Thrown when the given type is not assignable to <see cref="T"/>.</exception> public static T Instantiate<T>(Type derivedType) { var constructor = GetTypeConstructor(derivedType); CheckIsAssignableFrom(typeof(T), derivedType); CheckCanBeInstantiated(constructor, derivedType); return (T) constructor.Instantiate(); } /// <summary> /// Tries to create a new instance of the given type type and returns it as <see cref="T"/>. /// </summary> /// <param name="derivedType">The type we want to create a new instance of.</param> /// <param name="value">When this method returns, contains the created instance, if type instantiation succeeded; otherwise, the default value for <typeparamref name="T"/>.</param> /// <typeparam name="T">The type we want to create a new instance of.</typeparam> /// <returns><see langword="true"/> if a new instance of the given type could be created.</returns> public static bool TryInstantiate<T>(Type derivedType, out T value) { if (!typeof(T).IsAssignableFrom(derivedType)) { value = default; value = default; return false; } var constructor = GetTypeConstructor(derivedType); if (!constructor.CanBeInstantiated) { value = default; return false; } value = (T) constructor.Instantiate(); return true; } /// <summary> /// Creates a new instance of an array with the given count. /// </summary> /// <param name="count">The size of the array to instantiate.</param> /// <typeparam name="TArray">The array type to instantiate.</typeparam> /// <returns>The array newly created array.</returns> /// <exception cref="ArgumentException">Thrown is count is negative or if <see cref="TArray"/> is not an array type.</exception> public static TArray InstantiateArray<TArray>(int count = 0) { if (count < 0) { throw new ArgumentException($"{nameof(TypeUtility)}: Cannot construct an array with {nameof(count)}={count}"); } var properties = Internal.PropertyBagStore.GetPropertyBag<TArray>(); if (properties is IConstructorWithCount<TArray> constructor) { return constructor.InstantiateWithCount(count); } var type = typeof(TArray); if (!type.IsArray) { throw new ArgumentException($"{nameof(TypeUtility)}: Cannot construct an array, since {typeof(TArray).Name} is not an array type."); } var elementType = type.GetElementType(); if (null == elementType) { throw new ArgumentException($"{nameof(TypeUtility)}: Cannot construct an array, since {typeof(TArray).Name}.{nameof(Type.GetElementType)}() returned null."); } return (TArray) (object) Array.CreateInstance(elementType, count); } /// <summary> /// Tries to create a new instance of an array with the given count. /// </summary> /// <param name="count">The count the array should have.</param> /// <param name="instance">When this method returns, contains the created instance, if type instantiation succeeded; otherwise, the default value for <typeparamref name="TArray"/>.</param> /// <typeparam name="TArray">The array type.</typeparam> /// <returns><see langword="true"/> if the type was instantiated; otherwise, <see langword="false"/>.</returns> /// <exception cref="ArgumentException">Thrown is count is negative or if <see cref="TArray"/> is not an array type.</exception> public static bool TryInstantiateArray<TArray>(int count, out TArray instance) { if (count < 0) { instance = default; return false; } var properties = Internal.PropertyBagStore.GetPropertyBag<TArray>(); if (properties is IConstructorWithCount<TArray> constructor) { try { instance = constructor.InstantiateWithCount(count); return true; } catch { // continue } } var type = typeof(TArray); if (!type.IsArray) { instance = default; return false; } var elementType = type.GetElementType(); if (null == elementType) { instance = default; return false; } instance = (TArray) (object) Array.CreateInstance(elementType, count); return true; } /// <summary> /// Creates a new instance of an array with the given type and given count. /// </summary> /// <param name="derivedType">The type we want to create a new instance of.</param> /// <param name="count">The size of the array to instantiate.</param> /// <typeparam name="TArray">The array type to instantiate.</typeparam> /// <returns>The array newly created array.</returns> /// <exception cref="ArgumentException">Thrown is count is negative or if <see cref="TArray"/> is not an array type.</exception> public static TArray InstantiateArray<TArray>(Type derivedType, int count = 0) { if (count < 0) { throw new ArgumentException($"{nameof(TypeUtility)}: Cannot instantiate an array with {nameof(count)}={count}"); } var properties = Internal.PropertyBagStore.GetPropertyBag(derivedType); if (properties is IConstructorWithCount<TArray> constructor) { return constructor.InstantiateWithCount(count); } var type = typeof(TArray); if (!type.IsArray) { throw new ArgumentException($"{nameof(TypeUtility)}: Cannot instantiate an array, since {typeof(TArray).Name} is not an array type."); } var elementType = type.GetElementType(); if (null == elementType) { throw new ArgumentException($"{nameof(TypeUtility)}: Cannot instantiate an array, since {typeof(TArray).Name}.{nameof(Type.GetElementType)}() returned null."); } return (TArray) (object) Array.CreateInstance(elementType, count); } static void CheckIsAssignableFrom(Type type, Type derivedType) { if (!type.IsAssignableFrom(derivedType)) throw new ArgumentException($"Could not create instance of type `{derivedType.Name}` and convert to `{type.Name}`: The given type is not assignable to target type."); } static void CheckCanBeInstantiated<T>(ITypeConstructor<T> constructor) { if (!constructor.CanBeInstantiated) throw new InvalidOperationException($"Type `{typeof(T).Name}` could not be instantiated. A parameter-less constructor or an explicit construction method is required."); } static void CheckCanBeInstantiated(ITypeConstructor constructor, Type type) { if (!constructor.CanBeInstantiated) { throw new InvalidOperationException($"Type `{type.Name}` could not be instantiated. A parameter-less constructor or an explicit construction method is required."); } } } }
UnityCsReference/Modules/Properties/Runtime/Utility/TypeUtility.cs/0
{ "file_path": "UnityCsReference/Modules/Properties/Runtime/Utility/TypeUtility.cs", "repo_id": "UnityCsReference", "token_count": 13041 }
411
// 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 UnityEngine.Assertions; namespace UnityEditor.Search { enum Combine { None, Intersection, Union } class SearchIndexerQueryFactory : SearchQueryEvaluatorFactory<SearchResult> { public SearchIndexerQueryFactory(SearchQueryEvaluator<SearchResult>.EvalHandler handler) : base(handler) {} } class SearchQueryEvaluatorFactory<T> : IQueryHandlerFactory<T, SearchQueryEvaluator<T>, object> { SearchQueryEvaluator<T>.EvalHandler m_Handler; public SearchQueryEvaluatorFactory(SearchQueryEvaluator<T>.EvalHandler handler) { m_Handler = handler; } public SearchQueryEvaluator<T> Create(QueryGraph graph, ICollection<QueryError> errors) { ValidateGraph(graph.root, errors); return new SearchQueryEvaluator<T>(graph, m_Handler); } private static void ValidateGraph(IQueryNode root, ICollection<QueryError> errors) { if (root == null) return; ValidateNode(root, errors); if (root.leaf || root.children == null) return; foreach (var child in root.children) { ValidateGraph(child, errors); } } private static void ValidateNode(IQueryNode node, ICollection<QueryError> errors) { switch (node.type) { case QueryNodeType.Aggregator: case QueryNodeType.FilterIn: case QueryNodeType.Intersection: case QueryNodeType.Union: case QueryNodeType.NestedQuery: { errors.Add(new QueryError(node.token.position, node.token.length, "Nested queries are not supported.", SearchQueryErrorType.Warning)); break; } } } } class SearchQueryEvaluator<T> : IQueryHandler<T, object> { private QueryGraph graph { get; set; } private EvalHandler m_Handler; public delegate EvalResult EvalHandler(EvalHandlerArgs args); public readonly struct EvalHandlerArgs { public readonly string name; public readonly object value; public readonly bool exclude; public readonly SearchIndexOperator op; public readonly IEnumerable<T> andSet; public readonly IEnumerable<T> orSet; public readonly object payload; public EvalHandlerArgs(string name, object value, SearchIndexOperator op, bool exclude, IEnumerable<T> andSet, IEnumerable<T> orSet, object payload) { this.name = name; this.value = value; this.op = op; this.exclude = exclude; this.andSet = andSet; this.orSet = orSet; this.payload = payload; } } public readonly struct EvalResult { public readonly bool combined; public readonly IEnumerable<T> results; public static EvalResult None = new EvalResult(false, null); public EvalResult(bool combined, IEnumerable<T> results = null) { this.combined = combined; this.results = results; } public static EvalResult Combined(IEnumerable<T> results) { return new EvalResult(true, results); } public static void Print(EvalHandlerArgs args, IEnumerable<T> results = null, SearchResultCollection subset = null, double elapsedTime = -1) { var combineString = GetCombineString(args.andSet, args.orSet); var elapsedTimeString = ""; if (elapsedTime > 0) elapsedTimeString = $"{elapsedTime:F2} ms"; UnityEngine.Debug.LogFormat(UnityEngine.LogType.Log, UnityEngine.LogOption.None, null, $"Eval -> {combineString} | op:{args.op,14} | exclude:{args.exclude,7} | " + $"[{args.name,4}, {args.value,8}] | i:{GetAddress(args.andSet)} | a:{GetAddress(args.orSet)} | " + $"h:{GetAddress(subset)} | results:{GetAddress(results)} | " + elapsedTimeString); } private static string GetCombineString(object inputSet, object addedSet) { var combineString = " - "; if (addedSet != null && inputSet != null) combineString = "\u2229\u222A"; else if (addedSet != null) combineString = " \u2229 "; else if (inputSet != null) combineString = " \u222A "; return combineString; } private static int GetHandle(object obj) { return obj.GetHashCode(); } private static string GetAddress(object obj) { if (obj == null) return "0x00000000"; var addr = GetHandle(obj); return $"0x{addr.ToString("X8")}"; } private static string GetAddress(ICollection<T> list) { if (list == null) return "0x00000000"; var addr = GetHandle(list); return $"({list.Count}) 0x{addr.ToString("X8")}"; } } public SearchQueryEvaluator(QueryGraph graph, EvalHandler handler) { this.graph = graph; graph.Optimize(true, true); m_Handler = handler; } public IEnumerable<T> Eval(object payload) { if (graph.empty) return new List<T>(); var root = BuildInstruction(graph.root, m_Handler, payload, false); root.Execute(Combine.None); if (root.results == null) return new List<T>(); else return root.results.Distinct(); } public bool Eval(T element) { throw new System.NotSupportedException(); } internal static Instruction BuildInstruction(IQueryNode node, EvalHandler eval, object payload, bool not) { switch (node.type) { case QueryNodeType.And: { Assert.IsFalse(node.leaf, "And node cannot be leaf."); if (!not) return new AndInstruction(node, eval, payload, not); else return new OrInstruction(node, eval, payload, not); } case QueryNodeType.Or: { Assert.IsFalse(node.leaf, "Or node cannot be leaf."); if (!not) return new OrInstruction(node, eval, payload, not); else return new AndInstruction(node, eval, payload, not); } case QueryNodeType.Not: { Assert.IsFalse(node.leaf, "Not node cannot be leaf."); Instruction instruction = BuildInstruction(node.children[0], eval, payload, !not); return instruction; } case QueryNodeType.Filter: case QueryNodeType.Search: { Assert.IsNotNull(node); return new ResultInstruction(node, eval, payload, not); } case QueryNodeType.Where: { Assert.IsFalse(node.leaf, "Where node cannot be leaf."); return BuildInstruction(node.children[0], eval, payload, not); } } return null; } private static SearchIndexOperator ParseOperatorToken(string token) { switch (token) { case ":": return SearchIndexOperator.Contains; case "=": return SearchIndexOperator.Equal; case ">": return SearchIndexOperator.Greater; case ">=": return SearchIndexOperator.GreaterOrEqual; case "<": return SearchIndexOperator.Less; case "<=": return SearchIndexOperator.LessOrEqual; case "!=": return SearchIndexOperator.NotEqual; } return SearchIndexOperator.None; } internal abstract class Instruction : IInstruction<T> { public object payload; public IEnumerable<T> andSet; //not null for a AND public IEnumerable<T> orSet; //not null for a OR public IEnumerable<T> results; protected EvalHandler eval; public long estimatedCost { get; protected set; } public IQueryNode node { get; protected set; } public abstract bool Execute(Combine combine); } internal abstract class OperandInstruction : Instruction, IOperandInstruction<T> { public Instruction leftInstruction; public Instruction rightInstruction; public IInstruction<T> LeftInstruction => leftInstruction; public IInstruction<T> RightInstruction => rightInstruction; protected Combine combine; public OperandInstruction(IQueryNode node, EvalHandler eval, object payload, bool not) { leftInstruction = BuildInstruction(node.children[0], eval, payload, not); rightInstruction = BuildInstruction(node.children[1], eval, payload, not); this.eval = eval; this.payload = payload; } public override bool Execute(Combine combine) { // Pass the inputSet from the parent if (andSet != null) { leftInstruction.andSet = andSet; } // Pass the addedSet from the parent (only added by the right instruction) if (orSet != null) { rightInstruction.orSet = orSet; } bool combinedLeft = leftInstruction.Execute(combine); UpdateRightInstruction(leftInstruction.results); bool combinedRight = rightInstruction.Execute(this.combine); UpdateOutputSet(combinedLeft, combinedRight, leftInstruction.results, rightInstruction.results); return IsCombineHandled(combinedLeft, combinedRight); } internal abstract bool IsCombineHandled(bool combinedLeft, bool combinedRight); internal abstract void UpdateOutputSet(bool combinedLeft, bool combinedRight, IEnumerable<T> leftReturn, IEnumerable<T> rightReturn); internal abstract void UpdateRightInstruction(IEnumerable<T> leftReturn); } internal class AndInstruction : OperandInstruction, IAndInstruction<T> { public AndInstruction(IQueryNode node, EvalHandler eval, object dataSet, bool not) : base(node, eval, dataSet, not) { combine = Combine.Intersection; } internal override bool IsCombineHandled(bool combinedLeft, bool combinedRight) { return combinedLeft; // For a AND the inputSet is used by the left } internal override void UpdateOutputSet(bool combinedLeft, bool combinedRight, IEnumerable<T> leftReturn, IEnumerable<T> rightReturn) { if (!combinedRight) { var result = eval(new EvalHandlerArgs(null, null, SearchIndexOperator.None, false, leftReturn, rightReturn, payload)); results = result.results; if (!result.combined) { results = leftReturn.Intersect(rightReturn).ToList(); } } else results = rightReturn; } internal override void UpdateRightInstruction(IEnumerable<T> leftReturn) { rightInstruction.andSet = leftReturn; } } internal class OrInstruction : OperandInstruction, IOrInstruction<T> { public OrInstruction(IQueryNode node, EvalHandler eval, object payload, bool not) : base(node, eval, payload, not) { combine = Combine.Union; } internal override bool IsCombineHandled(bool combinedLeft, bool combinedRight) { return combinedRight; // For a OR the addedSet is used by the right } internal override void UpdateOutputSet(bool combinedLeft, bool combinedRight, IEnumerable<T> leftReturn, IEnumerable<T> rightReturn) { if (!combinedRight) { int rightReturnOriginalCount = rightReturn.Count(); int leftReturnOriginalCount = leftReturn.Count(); var result = eval(new EvalHandlerArgs(null, null, SearchIndexOperator.None, false, leftReturn, rightReturn, payload)); results = result.results; if (!result.combined) { results = leftReturn.Union(rightReturn); } } else results = rightReturn; } internal override void UpdateRightInstruction(IEnumerable<T> leftReturn) { // Pass the input Set from the parent if (andSet != null) rightInstruction.andSet = andSet; // might be wrong to modify that list because it's used somewhere else if (rightInstruction.orSet == null) rightInstruction.orSet = leftReturn; else { rightInstruction.orSet = rightInstruction.orSet.Union(leftReturn); } } } internal class ResultInstruction : Instruction, IResultInstruction<T> { public readonly bool exclude; public ResultInstruction(IQueryNode node, EvalHandler eval, object payload, bool exclude) { this.node = node; this.eval = eval; this.payload = payload; this.exclude = exclude; } public override bool Execute(Combine combine) { string searchName = null; object searchValue = null; var searchOperator = SearchIndexOperator.None; if (node is FilterNode filterNode) { searchName = filterNode.filter.token; searchValue = filterNode.filterValue; searchOperator = ParseOperatorToken(filterNode.op.token); } else if (node is SearchNode searchNode) { searchName = null; searchValue = searchNode.searchValue; searchOperator = searchNode.exact ? SearchIndexOperator.Equal : SearchIndexOperator.Contains; } var result = eval(new EvalHandlerArgs(searchName, searchValue, searchOperator, exclude, andSet, orSet, payload)); results = result.results; return result.combined; } } } }
UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchIndexerQuery.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Indexing/SearchIndexerQuery.cs", "repo_id": "UnityCsReference", "token_count": 7905 }
412
// 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.ShortcutManagement; using UnityEngine; namespace UnityEditor.Search.Providers { static class MenuProvider { struct MenuData { public string path; public string[] words; } internal const string type = "menu"; private const string displayName = "Menus"; private const string disabledMenuExecutionWarning = "The menu you are trying to execute is disabled. It will not be executed."; private static string[] shortcutIds; private static readonly QueryValidationOptions k_QueryEngineOptions = new QueryValidationOptions { validateFilters = true, skipNestedQueries = true }; private static QueryEngine<MenuData> queryEngine = null; private static List<MenuData> menus; private static Delayer debounce; [SearchItemProvider] internal static SearchProvider CreateProvider() { List<string> itemNames = new List<string>(); List<string> shortcuts = new List<string>(); GetMenuInfo(itemNames, shortcuts); System.Threading.Tasks.Task.Run(() => BuildMenus(itemNames)); queryEngine = new QueryEngine<MenuData>(k_QueryEngineOptions); queryEngine.SetFilter("id", m => m.path) .AddOrUpdatePropositionData(label: "Menu Path", replacement: "id:create/", help: "Filter by menu path.", priority: 9999); queryEngine.SetSearchDataCallback(m => m.words, s => Utils.FastToLower(s), StringComparison.Ordinal); debounce = Delayer.Debounce(_ => TriggerBackgroundUpdate(itemNames, shortcuts)); Menu.menuChanged -= OnMenuChanged; Menu.menuChanged += OnMenuChanged; return new SearchProvider(type, displayName) { priority = 80, filterId = "m:", showDetailsOptions = ShowDetailsOptions.ListView | ShowDetailsOptions.Actions, onEnable = () => shortcutIds = ShortcutManager.instance.GetAvailableShortcutIds().ToArray(), onDisable = () => shortcutIds = new string[0], fetchItems = FetchItems, fetchLabel = (item, context) => { if (item.label == null) { var menuName = Utils.GetNameFromPath(item.id); var enabled = Menu.GetEnabled(item.id); var @checked = Menu.GetChecked(item.id); item.label = $"{menuName}{(enabled ? "" : " (disabled)")} {(@checked ? "\u2611" : "")}"; } return item.label; }, fetchDescription = (item, context) => { if (string.IsNullOrEmpty(item.description)) item.description = GetMenuDescription(item.id); return item.description; }, fetchThumbnail = (item, context) => Icons.shortcut, fetchPropositions = (context, options) => FetchPropositions(context, options) }; } private static void OnMenuChanged() { debounce.Execute(); } private static void TriggerBackgroundUpdate(List<string> itemNames, List<string> shortcuts) { GetMenuInfo(itemNames, shortcuts); menus = null; System.Threading.Tasks.Task.Run(() => BuildMenus(itemNames)); } private static void BuildMenus(List<string> itemNames) { var localMenus = new List<MenuData>(); for (int i = 0; i < itemNames.Count; ++i) { var menuItem = itemNames[i]; localMenus.Add(new MenuData { path = menuItem, words = SplitMenuPath(menuItem).Select(w => Utils.FastToLower(w)).ToArray() }); } menus = localMenus; } private static IEnumerable<SearchItem> FetchItems(SearchContext context, List<SearchItem> items, SearchProvider provider) { var query = (string.IsNullOrEmpty(context.searchQuery) && context.providers.Count() == 1) ? null : queryEngine.ParseQuery(context.searchQuery); if (query != null && !query.valid) { context.AddSearchQueryErrors(query.errors.Select(e => new SearchQueryError(e, context, provider))); yield break; } while (menus == null) yield return null; var results = query == null ? menus : query.Apply(menus, false); foreach (var m in results) yield return provider.CreateItem(context, m.path); } private static IEnumerable<string> SplitMenuPath(string menuPath) { yield return menuPath; foreach (var m in menuPath.Split(new char[] { '/', ' ' }, StringSplitOptions.RemoveEmptyEntries).Reverse()) yield return m; } private static string GetMenuDescription(string menuName) { var sm = ShortcutManager.instance; if (sm == null) return menuName; var shortcutId = menuName; if (!shortcutIds.Contains(shortcutId)) { shortcutId = "Main Menu/" + menuName; if (!shortcutIds.Contains(shortcutId)) return menuName; } var shortcutBinding = ShortcutManager.instance.GetShortcutBinding(shortcutId); if (!shortcutBinding.keyCombinationSequence.Any()) return menuName; return $"{menuName} ({shortcutBinding})"; } static IEnumerable<SearchProposition> FetchPropositions(SearchContext context, SearchPropositionOptions options) { if (!options.flags.HasAny(SearchPropositionFlags.QueryBuilder)) yield break; foreach (var p in QueryAndOrBlock.BuiltInQueryBuilderPropositions()) yield return p; foreach (var proposition in queryEngine.GetPropositions()) yield return proposition; } [SearchActionsProvider] internal static IEnumerable<SearchAction> ActionHandlers() { return new[] { new SearchAction("menu", "select", null, "Execute shortcut") { handler = (item) => { var menuId = item.id; if (!Menu.GetEnabled(menuId)) { Debug.LogFormat(LogType.Warning, LogOption.NoStacktrace, null, disabledMenuExecutionWarning); return; } EditorApplication.delayCall += () => EditorApplication.ExecuteMenuItem(menuId); } } }; } [Shortcut("Help/Search/Menu")] internal static void OpenQuickSearch() { var qs = SearchUtils.OpenWithContextualProvider(type, Settings.type); qs.itemIconSize = 1; // Open in list view by default. } private static void GetMenuInfo(List<string> outItemNames, List<string> outItemDefaultShortcuts) { Utils.GetMenuItemDefaultShortcuts(outItemNames, outItemDefaultShortcuts); } } }
UnityCsReference/Modules/QuickSearch/Editor/Providers/MenuProvider.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Providers/MenuProvider.cs", "repo_id": "UnityCsReference", "token_count": 3630 }
413
// 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 UnityEngine; namespace UnityEditor.Search { [AttributeUsage(AttributeTargets.Class)] public class QueryListBlockAttribute : Attribute { static List<QueryListBlockAttribute> s_Attributes; public QueryListBlockAttribute(string category, string name, string id, string op = "=") : this(category, name, new []{id}, op, 0) {} public QueryListBlockAttribute(string category, string name, string[] ids, string op = "=") : this(category, name, ids, op, 0) {} internal QueryListBlockAttribute(string category, string name, string id, string op, int priority = 0) : this(category, name, new[] { id }, op, priority) {} internal QueryListBlockAttribute(string category, string name, string[] ids, string op, int priority = 0) { this.ids = ids ?? new string[] { }; this.category = category; this.name = name; this.op = op; this.priority = priority; } public string[] ids { get; set; } public string name { get; set; } public string category { get; set; } public string op { get; set; } public Type type { get; set; } internal int priority { get; private set; } public string id => ids.Length > 0 ? ids[0] : string.Empty; internal static QueryListBlock CreateBlock(Type type, IQuerySource source, string value) { var attr = FindBlock(type); if (attr != null) return (QueryListBlock)Activator.CreateInstance(type, new object[] { source, attr.id, value, attr }); return null; } internal static QueryListBlock CreateBlock(string id, string op, IQuerySource source, string value) { var attr = FindBlock(id); QueryMarker.TryParse(value, out var marker); var isValidMarker = marker.valid && marker.type == "list"; if (attr != null) { if (isValidMarker) { return new QueryListMarkerBlock(source, id, marker, attr); } return (QueryListBlock)Activator.CreateInstance(attr.type, new object[] { source, id, value, attr }); } else if (isValidMarker) { return new QueryListMarkerBlock(source, id, id, op, marker); } return null; } internal static IEnumerable<SearchProposition> GetPropositions(Type type) { var block = CreateBlock(type, null, null); if (block != null) return block.GetPropositions(); return new SearchProposition[0]; } internal static QueryListBlockAttribute FindBlock(Type t) { if (s_Attributes == null) RefreshQueryListBlock(); return s_Attributes?.FirstOrDefault(a => a.type == t); } internal static QueryListBlockAttribute FindBlock(string id) { if (s_Attributes == null) RefreshQueryListBlock(); return s_Attributes? .Where(a => a.ids.Any(matchedId => matchedId.Equals(id, StringComparison.Ordinal))) .OrderBy(a => a.priority) .ThenBy(a => a.name) .FirstOrDefault(); } internal static void RefreshQueryListBlock() { s_Attributes = new List<QueryListBlockAttribute>(); var types = TypeCache.GetTypesWithAttribute<QueryListBlockAttribute>(); foreach (var ti in types) { try { var attr = ti.GetCustomAttributes(typeof(QueryListBlockAttribute), false).Cast<QueryListBlockAttribute>().First(); attr.type = ti; if (!typeof(QueryListBlock).IsAssignableFrom(ti)) continue; s_Attributes.Add(attr); } catch (Exception e) { Debug.LogWarning($"Cannot register QueryListBlock provider: {ti.Name}\n{e}"); } } } internal static bool TryGetReplacement(string id, string type, ref Type blockType, out string replacement) { var block = CreateBlock(id, null, null, null); if (block != null) return block.TryGetReplacement(id, type, ref blockType, out replacement); replacement = string.Empty; return false; } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryListBlockAttribute.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryBuilder/Blocks/QueryListBlockAttribute.cs", "repo_id": "UnityCsReference", "token_count": 2234 }
414
// 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 System.Linq; namespace UnityEditor.Search { class IntersectionEnumerable<T> : IQueryEnumerable<T> { IEnumerable<T> m_First; IEnumerable<T> m_Second; public bool fastYielding { get; } public IntersectionEnumerable(IEnumerable<T> first, IEnumerable<T> second, bool fastYielding) { m_First = first; m_Second = second; this.fastYielding = fastYielding; } public void SetPayload(IEnumerable<T> payload) {} public IEnumerator<T> GetEnumerator() { if (fastYielding) return FastYieldingEnumerator(); return m_First.Intersect(m_Second).GetEnumerator(); } public IEnumerator<T> FastYieldingEnumerator() { var distinctFirstElements = new HashSet<T>(); var distinctSecondElements = new HashSet<T>(m_Second); foreach (var firstElement in m_First) { if (distinctFirstElements.Contains(firstElement)) { yield return default; continue; } distinctFirstElements.Add(firstElement); if (distinctSecondElements.Contains(firstElement)) yield return firstElement; else yield return default; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [EnumerableCreator(QueryNodeType.Intersection)] class IntersectionEnumerableFactory : IQueryEnumerableFactory { public IQueryEnumerable<T> Create<T>(IQueryNode root, QueryEngine<T> engine, ICollection<QueryError> errors, bool fastYield) { if (root.leaf || root.children == null || root.children.Count != 2) { errors.Add(new QueryError(root.token.position, root.token.length, "Intersection node must have two children.")); return null; } var firstEnumerable = EnumerableCreator.Create(root.children[0], engine, errors, fastYield); var secondEnumerable = EnumerableCreator.Create(root.children[1], engine, errors, fastYield); if (firstEnumerable == null || secondEnumerable == null) { errors.Add(new QueryError(root.token.position, root.token.length, "Could not create enumerables from Intersection node's children.")); } return new IntersectionEnumerable<T>(firstEnumerable, secondEnumerable, fastYield); } } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/IntersectionEnumerable.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/IntersectionEnumerable.cs", "repo_id": "UnityCsReference", "token_count": 1287 }
415
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.Search { /// <summary> /// Represents a token of a query string. /// </summary> public readonly struct QueryToken { /// <summary> /// The text representing the token. /// </summary> public string text { get; } /// <summary> /// The position of the token in the entire query string. /// </summary> public int position { get; } /// <summary> /// The length of the token. Can be different than the length of the text. /// </summary> public int length { get; } internal readonly StringView stringView; /// <summary> /// Creates a token from a string and a position. /// </summary> /// <param name="text">The value of the token.</param> /// <param name="position">The position of the token in the entire query string.</param> public QueryToken(string text, int position) : this(text, position, text?.Length ?? 0) {} /// <summary> /// Creates a token from a string, a position and a length. /// </summary> /// <param name="text">The value of the token.</param> /// <param name="position">The position of the token in the entire query string.</param> /// <param name="length">The length of the token.</param> public QueryToken(string text, int position, int length) { this.position = position; this.length = length; this.stringView = new StringView(text); this.text = text; } internal QueryToken(in StringView stringView, int position) : this(stringView, position, stringView.length) {} internal QueryToken(in StringView stringView, int position, int length) { this.stringView = stringView; this.text = stringView.ToString(); this.position = position; this.length = length; } internal QueryToken(int position, int length) : this(StringView.empty, position, length) {} } }
UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryToken.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/QueryEngine/QueryToken.cs", "repo_id": "UnityCsReference", "token_count": 910 }
416
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System.Linq; using System.Collections.Generic; using System.ComponentModel; namespace UnityEditor.Search { static partial class ConverterEvaluators { [Description("Convert arguments to a number."), Category("Converters")] [SearchExpressionEvaluator(SearchExpressionType.Iterable | SearchExpressionType.Literal | SearchExpressionType.Variadic)] public static IEnumerable<SearchItem> ToNumber(SearchExpressionContext c) { return c.args.SelectMany(e => e.Execute(c)).Select(item => { SearchExpression.TryConvertToDouble(item, out var value); return SearchExpression.CreateItem(value); }); } [Description("Convert arguments to a string allowing you to format the result."), Category("Converters")] [SearchExpressionEvaluator(SearchExpressionType.Selector | SearchExpressionType.Text, SearchExpressionType.Iterable | SearchExpressionType.Literal | SearchExpressionType.Variadic)] [SearchExpressionEvaluatorSignatureOverload(SearchExpressionType.Iterable | SearchExpressionType.Literal | SearchExpressionType.Variadic)] public static IEnumerable<SearchItem> Format(SearchExpressionContext c) { var skipCount = 0; if (SearchExpression.GetFormatString(c.args[0], out var formatStr)) skipCount++; var items = c.args.Skip(skipCount).SelectMany(e => e.Execute(c)); var dataSet = SearchExpression.ProcessValues(items, null, item => SearchExpression.FormatItem(c.search, item, formatStr)); return dataSet; } [Description("Convert arguments to booleans."), Category("Converters")] [SearchExpressionEvaluator(SearchExpressionType.Iterable | SearchExpressionType.Literal | SearchExpressionType.Variadic)] public static IEnumerable<SearchItem> ToBoolean(SearchExpressionContext c) { return c.args.SelectMany(e => e.Execute(c)).Select(item => SearchExpression.CreateItem(SearchExpression.IsTrue(item))); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/ConverterEvaluators.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Evaluators/ConverterEvaluators.cs", "repo_id": "UnityCsReference", "token_count": 841 }
417
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License namespace UnityEditor.Search { static partial class Parsers { [SearchExpressionParser("expand", BuiltinParserPriority.Expand)] internal static SearchExpression ExpandParser(SearchExpressionParserArgs args) { var outerText = args.text; var text = ParserUtils.SimplifyExpression(outerText); if (!text.StartsWith("...", System.StringComparison.Ordinal)) return null; var expression = ParserManager.Parse(args.With(text.Substring(3))); return new SearchExpression(expression, expression.types | SearchExpressionType.Expandable, outerText, expression.innerText); } } }
UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/ExpandExpressionParser.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchExpression/Parsers/ExpandExpressionParser.cs", "repo_id": "UnityCsReference", "token_count": 316 }
418
// 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.Search { /// <summary> /// Various search options used to fetch items. /// </summary> [Flags] public enum SearchFlags { /// <summary> /// No specific search options. /// </summary> None = 0, /// <summary> /// Search items are fetch synchronously. /// </summary> Synchronous = 1 << 0, /// <summary> /// Fetch items will be sorted by the search service. /// </summary> Sorted = 1 << 1, /// <summary> /// Send the first items asynchronously /// </summary> FirstBatchAsync = 1 << 2, /// <summary> /// Sets the search to search for all results. /// </summary> WantsMore = 1 << 3, /// <summary> /// Adding debugging info while looking for results, /// </summary> Debug = 1 << 4, /// <summary> /// Prevent the search to use any indexing /// </summary> NoIndexing = 1 << 5, /// <summary> /// Process the current query as an expression /// </summary> Expression = 1 << 6, /// <summary> /// Evaluate the search text as a pure query string (do not evaluate the text as a search expression). /// </summary> QueryString = 1 << 7, /// <summary> /// Indicates that the query should consider package assets to fetch results. If not set, then package assets will most likely be ignored. /// </summary> Packages = 1 << 8, /// <summary> /// Default Search Flag /// </summary> Default = Sorted, /// <summary> /// Always show query errors even when there are results available. /// </summary> ShowErrorsWithResults = 1 << 24, /// <summary> /// Search View Flags /// </summary> SaveFilters = 1 << 25, /// <summary> /// Open QuickSearch reusing an existing window if any. /// </summary> ReuseExistingWindow = 1 << 26, /// <summary> /// Specify that a QuickSearch window list view supports multi-selection. /// </summary> Multiselect = 1 << 27, /// <summary> /// Specify that a QuickSearch window is dockable instead of being a modal popup window. /// </summary> Dockable = 1 << 28, /// <summary> /// Focus the search query when opening QuickSearch. /// </summary> FocusContext = 1 << 29, /// <summary> /// Hide all QuickSearch side panels. /// </summary> HidePanels = 1 << 30, /// <summary> /// Default options when opening a QuickSearch window. /// </summary> OpenDefault = SaveFilters | Multiselect | Dockable, /// <summary> /// Default options when opening a QuickSearch using the global shortcut. /// </summary> OpenGlobal = OpenDefault | ReuseExistingWindow, /// <summary> /// Options when opening QuickSearch in contextual mode (with only a few selected providers enabled). /// </summary> OpenContextual = Multiselect | Dockable | FocusContext, /// <summary> /// Options when opening QuickSearch as an Object Picker. /// </summary> OpenPicker = FocusContext | HidePanels } static class SearchFlagsExtensions { public static bool HasAny(this SearchFlags flags, SearchFlags f) => (flags & f) != 0; public static bool HasAll(this SearchFlags flags, SearchFlags all) => (flags & all) == all; public static bool HasAny(this ShowDetailsOptions flags, ShowDetailsOptions f) => (flags & f) != 0; public static bool HasAll(this ShowDetailsOptions flags, ShowDetailsOptions all) => (flags & all) == all; public static bool HasAny(this SearchItemOptions flags, SearchItemOptions f) => (flags & f) != 0; public static bool HasAll(this SearchItemOptions flags, SearchItemOptions all) => (flags & all) == all; public static bool HasAny(this FetchPreviewOptions flags, FetchPreviewOptions f) => (flags & f) != 0; public static bool HasAll(this FetchPreviewOptions flags, FetchPreviewOptions all) => (flags & all) == all; public static bool HasAny(this RefreshFlags flags, RefreshFlags f) => (flags & f) != 0; public static bool HasAll(this RefreshFlags flags, RefreshFlags all) => (flags & all) == all; } }
UnityCsReference/Modules/QuickSearch/Editor/SearchFlags.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/SearchFlags.cs", "repo_id": "UnityCsReference", "token_count": 1791 }
419
// 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.Linq; using System.Collections.Generic; using UnityEngine; using static UnityEditor.Search.Providers.AssetProvider; namespace UnityEditor.Search { class AssetSelectors { [SearchSelector("name", provider: type, priority: 99)] static object GetAssetName(SearchItem item) { var obj = item.ToObject(); return obj?.name; } [SearchSelector("filename", provider: type, priority: 99)] static object GetAssetFilename(SearchItem item) { return Path.GetFileName(GetAssetPath(item)); } [SearchSelector("type", priority: 99, cacheable = false)] static string GetAssetType(SearchItem item) { var itemType = item.provider?.toType?.Invoke(item, null); if (itemType == typeof(GameObject)) return "Prefab"; return itemType?.Name; } [SearchSelector("extension", provider: type, priority: 99)] static string GetAssetExtension(SearchItem item) { if (GetAssetPath(item) is string assetPath) return Path.GetExtension(assetPath).Substring(1); return null; } [SearchSelector("size", priority: 99)] static object GetAssetFileSize(SearchItem item) { if (SearchUtils.GetAssetPath(item) is string assetPath && !string.IsNullOrEmpty(assetPath)) { var fi = new FileInfo(assetPath); return fi.Exists ? fi.Length : 0; } return null; } public static IEnumerable<SearchColumn> Enumerate(IEnumerable<SearchItem> items) { return PropertySelectors.Enumerate(FilterItems(items, 5)) .Concat(MaterialSelectors.Enumerate(FilterItems(items, 20))); } static IEnumerable<SearchItem> FilterItems(IEnumerable<SearchItem> items, int count) { return items.Where(e => e.provider.type == type).Take(count); } } }
UnityCsReference/Modules/QuickSearch/Editor/Selectors/AssetSelectors.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Selectors/AssetSelectors.cs", "repo_id": "UnityCsReference", "token_count": 972 }
420
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License // #define USE_TRANSACTION_VIEWER using System; using System.Collections.Generic; using UnityEditor; using UnityEditor.UIElements; using UnityEngine.UIElements; namespace UnityEditor.Search { class TransactionViewer : EditorWindow { const int k_TransactionRowHeight = 16; const string k_DateLabelName = "date_label"; const string k_PathLabelName = "path_label"; const string k_StateLabelName = "state_label"; ReadOnlyTransactionManager m_TransactionManager; ObjectField m_TransactionAssetField; UnityEngine.UIElements.ListView m_TransactionListView; public List<Transaction> Transactions { get; } = new List<Transaction>(); // Add menu named "My Window" to the Window menu static void Init() { // Get existing open window or if none, make a new one: var window = (TransactionViewer)GetWindow(typeof(TransactionViewer)); window.Show(); } public static TransactionViewer OpenOnRange(string filePath, TimeRange timeRange, bool listenToChanges) { var window = (TransactionViewer)GetWindow(typeof(TransactionViewer)); window.Show(); window.LoadDatabase(filePath, timeRange, listenToChanges); return window; } void OnEnable() { m_TransactionManager = new ReadOnlyTransactionManager(); m_TransactionAssetField = new ObjectField("Transaction Database"); m_TransactionAssetField.objectType = typeof(DefaultAsset); m_TransactionAssetField.RegisterValueChangedCallback(evt => { var assetPath = AssetDatabase.GetAssetPath(evt.newValue); LoadDatabase(assetPath, TimeRange.All(), true); }); rootVisualElement.Add(m_TransactionAssetField); m_TransactionListView = new UnityEngine.UIElements.ListView(); m_TransactionListView.itemsSource = Transactions; m_TransactionListView.fixedItemHeight = k_TransactionRowHeight; m_TransactionListView.makeItem = MakeRowItem; m_TransactionListView.bindItem = BindRowItem; m_TransactionListView.style.flexGrow = 1.0f; rootVisualElement.Add(m_TransactionListView); } void HandleTransactionsAdded(DateTime newDateTime) { var timeRange = TimeRange.From(newDateTime, false); UpdateListView(m_TransactionListView, timeRange); } void OnDisable() { m_TransactionManager.Shutdown(); } void LoadDatabase(string path, TimeRange timeRange, bool listenToChanges) { m_TransactionManager.Shutdown(); Transactions.Clear(); if (string.IsNullOrEmpty(path)) { m_TransactionAssetField.SetValueWithoutNotify(null); } else { var asset = AssetDatabase.LoadMainAssetAtPath(path); m_TransactionAssetField.SetValueWithoutNotify(asset); m_TransactionManager.SetFilePath(path); m_TransactionManager.Init(); if (listenToChanges) m_TransactionManager.transactionsAdded += HandleTransactionsAdded; } UpdateListView(m_TransactionListView, timeRange); } void UpdateListView(UnityEngine.UIElements.ListView listViewElement, TimeRange timeRange) { if (m_TransactionManager.Initialized) { var transactions = m_TransactionManager.Read(timeRange); Transactions.AddRange(transactions); } EditorApplication.delayCall += listViewElement.Rebuild; } static VisualElement MakeRowItem() { var row = new VisualElement(); row.style.flexDirection = FlexDirection.Row; var dateLabel = new Label(); dateLabel.name = k_DateLabelName; row.Add(dateLabel); var pathLabel = new Label(); pathLabel.name = k_PathLabelName; row.Add(pathLabel); var stateLabel = new Label(); stateLabel.name = k_StateLabelName; row.Add(stateLabel); return row; } void BindRowItem(VisualElement element, int index) { if (index < 0 || index >= Transactions.Count) return; var transaction = Transactions[index]; var date = DateTime.FromBinary(transaction.timestamp).ToUniversalTime(); var assetPath = AssetDatabase.GUIDToAssetPath(transaction.guid.ToString()); var dateLabel = element.Q<Label>(k_DateLabelName); dateLabel.text = $"{date:u}"; var pathLabel = element.Q<Label>(k_PathLabelName); pathLabel.text = assetPath; var stateLabel = element.Q<Label>(k_StateLabelName); stateLabel.text = transaction.GetState().ToString(); } } }
UnityCsReference/Modules/QuickSearch/Editor/Transactions/TransactionViewer.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/Transactions/TransactionViewer.cs", "repo_id": "UnityCsReference", "token_count": 2275 }
421
// 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 UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.Search { class SearchDetailView : SearchElement, ISearchPanel { /// <summary> /// The elements that can be made visible or invisible on the panel. /// </summary> private List<VisualElement> m_ActiveElements; private Button[] m_ActionButtons; private Button m_MoreButton; private Image m_PreviewImage; private IMGUIContainer m_InteractivePreviewElement; private Label m_SelectionLabel; private Label m_DescriptionLabel; private VisualElement m_EditorContainer; private Editor[] m_Editors; private int m_EditorsHash = 0; private Action m_RefreshOff; private IVisualElementScheduledItem m_PreviewImageRefreshCallback; private IVisualElementScheduledItem m_ActionsRefreshCallback; private ScrollView m_ScrollView; public static readonly string ussClassName = "search-details-view"; public static readonly string inspectorLabelContainerClassName = ussClassName.WithUssElement("header"); public static readonly string selectionLabelClassName = ussClassName.WithUssElement("selection-label"); public static readonly string itemPreviewImageClassName = ussClassName.WithUssElement("item-preview-image"); public static readonly string itemPreviewClassName = ussClassName.WithUssElement("item-preview"); public static readonly string itemDescriptionClassName = ussClassName.WithUssElement("item-description"); public static readonly string itemEditorClassName = ussClassName.WithUssElement("item-editor"); public static readonly string actionButtonContainerClassName = ussClassName.WithUssElement("action-button-container"); public static readonly string fixedActionButtonContainerClassName = ussClassName.WithUssElement("fixed-action-button-container"); public static readonly string extraActionButtonContainerClassName = ussClassName.WithUssElement("extra-action-button-container"); public static readonly string actionButtonClassName = ussClassName.WithUssElement("action-button"); public static readonly string actionButtonMoreClassName = ussClassName.WithUssElement("action-button-more"); public static readonly GUIContent previewInspectorContent = EditorGUIUtility.TrTextContentWithIcon("Inspector", "Open Inspector (F4)", EditorGUIUtility.FindTexture("UnityEditor.InspectorWindow")); public static readonly GUIContent moreActionsContent = EditorGUIUtility.TrTextContentWithIcon(string.Empty, "Open actions menu", Icons.more); public SearchDetailView(string name, ISearchView viewModel, params string[] classes) : base(name, viewModel, classes) { AddToClassList(ussClassName); m_ActiveElements = new List<VisualElement>(); m_ScrollView = new ScrollView(ScrollViewMode.Vertical); m_ScrollView.horizontalScrollerVisibility = ScrollerVisibility.Hidden; var labelWithIcon = Create<VisualElement>(null, inspectorLabelContainerClassName); labelWithIcon.Add(new Image() { image = previewInspectorContent.image }); labelWithIcon.Add(new Label { text = previewInspectorContent.text, tooltip = previewInspectorContent.tooltip }); var actionsContainer = CreateActionButtons(); m_SelectionLabel = Create<Label>(null, selectionLabelClassName); m_PreviewImage = Create<Image>("SearchItemPreviewImage", itemPreviewImageClassName); m_InteractivePreviewElement = Create<IMGUIContainer>("ItemPreview", itemPreviewClassName); m_DescriptionLabel = Create<Label>(null, itemDescriptionClassName); m_EditorContainer = Create<VisualElement>(null, itemEditorClassName); m_ActiveElements.Add(m_SelectionLabel); m_ActiveElements.Add(m_PreviewImage); m_ActiveElements.Add(m_InteractivePreviewElement); m_ActiveElements.Add(m_DescriptionLabel); m_ActiveElements.Add(m_EditorContainer); m_ScrollView.Add(labelWithIcon); m_ScrollView.Add(actionsContainer); m_ScrollView.Add(m_SelectionLabel); m_ScrollView.Add(m_PreviewImage); m_ScrollView.Add(m_InteractivePreviewElement); m_ScrollView.Add(m_DescriptionLabel); m_ScrollView.Add(m_EditorContainer); Add(m_ScrollView); HideElements(m_ActiveElements); Refresh(); } protected override void OnAttachToPanel(AttachToPanelEvent evt) { base.OnAttachToPanel(evt); On(SearchEvent.RefreshContent, OnRefreshed); On(SearchEvent.SelectionHasChanged, OnSelectionChanged); RegisterCallback<GeometryChangedEvent>(OnPreviewSizeChanged); } protected override void OnDetachFromPanel(DetachFromPanelEvent evt) { UnregisterCallback<GeometryChangedEvent>(OnPreviewSizeChanged); Off(SearchEvent.RefreshContent, OnRefreshed); Off(SearchEvent.SelectionHasChanged, OnSelectionChanged); ResetEditors(); m_PreviewImageRefreshCallback?.Pause(); m_ActionsRefreshCallback?.Pause(); base.OnDetachFromPanel(evt); } private void OnPreviewSizeChanged(GeometryChangedEvent evt) { // when the carousel is active for the store provider, // the preview image will update on a timer and there is no need to act on the geometry event if (m_PreviewImageRefreshCallback?.isActive == true) return; var selection = context.selection; var lastItem = selection.Last(); if (lastItem != null) DrawPreview(context, lastItem); } private void OnSelectionChanged(ISearchEvent evt) { int selectionCount; if (evt.argumentCount == 1) { selectionCount = evt.GetArgument<IEnumerable<int>>(0).ToList().Count; if (selectionCount == 0) { SetVisibleDetail(false); ResetEditors(); m_EditorContainer.Clear(); return; } } Refresh(); } VisualElement CreateActionButtons() { var actionsContainer = Create(null, actionButtonContainerClassName); var fixedActionsContainer = Create(null, fixedActionButtonContainerClassName); var fixedAction1 = Create<Button>(null, actionButtonClassName, "fixed-action-button1"); var fixedAction2 = Create<Button>(null, actionButtonClassName, "fixed-action-button2"); m_MoreButton = Create<Button>("MoreButton", actionButtonMoreClassName); m_MoreButton.text = moreActionsContent.text; m_MoreButton.tooltip = moreActionsContent.tooltip; m_MoreButton.Insert(0, new Image() { image = moreActionsContent.image }); fixedActionsContainer.Add(fixedAction1); fixedActionsContainer.Add(fixedAction2); fixedActionsContainer.Add(m_MoreButton); var extraActionsContainer = Create(null, extraActionButtonContainerClassName); var extraAction1 = Create<Button>(null, actionButtonClassName, "action-button1"); var extraAction2 = Create<Button>(null, actionButtonClassName, "action-button2"); var extraAction3 = Create<Button>(null, actionButtonClassName, "action-button3"); var extraAction4 = Create<Button>(null, actionButtonClassName, "action-button4"); extraActionsContainer.Add(extraAction1); extraActionsContainer.Add(extraAction2); extraActionsContainer.Add(extraAction3); extraActionsContainer.Add(extraAction4); m_ActionButtons = new[] { fixedAction1, fixedAction2, extraAction1, extraAction2, extraAction3, extraAction4 }; m_ActiveElements.AddRange(m_ActionButtons); m_ActiveElements.Add(m_MoreButton); actionsContainer.Add(fixedActionsContainer); actionsContainer.Add(extraActionsContainer); return actionsContainer; } private void OnRefreshed(ISearchEvent evt) { m_RefreshOff?.Invoke(); m_RefreshOff = Utils.CallDelayed(Refresh, 0.05d); } private void Refresh() { var selection = context.selection; var lastItem = selection.Last(); var showOptions = lastItem?.provider.showDetailsOptions ?? ShowDetailsOptions.None; var selectionCount = selection.Count; SetVisibleDetail(false); SetupEditors(selection, showOptions); if (selectionCount == 0) { m_EditorContainer?.Clear(); return; } SetVisibleDetail(true); if (selectionCount > 1) { ShowElements(m_SelectionLabel); // Do not render anything else if the selection is composed of items with different providers if (selection.GroupBy(item => item.provider.id).Count() > 1) { m_SelectionLabel.text = $"Selected {selectionCount} items from different types."; return; } else { m_SelectionLabel.text = $"Selected {selectionCount} items"; } } m_ActionsRefreshCallback?.Pause(); if (showOptions.HasAny(ShowDetailsOptions.Actions) && !m_ViewModel.IsPicker()) { RefreshActions(context); m_ActionsRefreshCallback = schedule.Execute(() => RefreshActions(context)).StartingIn(100).Every(100); } if (selectionCount >= 1) { if (showOptions.HasAny(ShowDetailsOptions.Preview) && lastItem != null) DrawPreview(context, lastItem); if (showOptions.HasAny(ShowDetailsOptions.Description) && lastItem != null) DrawDescription(context, lastItem); } if (showOptions.HasAny(ShowDetailsOptions.Inspector)) DrawInspector(selection, showOptions); else m_EditorContainer.Clear(); m_RefreshOff?.Invoke(); m_RefreshOff = null; } private void SetVisibleDetail(bool visible) { if (visible) { m_ScrollView.verticalScrollerVisibility = ScrollerVisibility.Auto; } else { HideElements(m_ActiveElements); m_ScrollView.verticalScrollerVisibility = ScrollerVisibility.Hidden; } } private void RefreshActions(SearchContext context) { if (context == null || context.selection == null) return; HideElements(m_ActionButtons); HideElements(m_MoreButton); var selection = context.selection; var firstItem = selection.First(); if (firstItem == null) return; var fixedActions = new string[] { "select", "open" }; var actions = firstItem.provider.actions.Where(a => a.enabled(selection)); var remainingActions = actions.Where(a => !fixedActions.Contains(a.id)).ToArray(); if (remainingActions.Length <= 3) { RefreshActions(selection, actions, m_ActionButtons); } else if (remainingActions.Length > 3) { RefreshActions(selection, actions.Where(a => fixedActions.Contains(a.id)), m_ActionButtons); RefreshMoreMenu(selection, remainingActions); } } struct ActionButtonData { public SearchSelection selection; public SearchAction action; } private void RefreshActions(SearchSelection selection, IEnumerable<SearchAction> actions, Button[] buttonElements) { if (actions.Count() > buttonElements.Length) throw new ArgumentException($"The size of {nameof(actions)} = {actions.Count()} is greater than the number of {nameof(buttonElements)} = {buttonElements.Length}"); int i = 0; foreach (var action in actions) { if (action == null || action.content == null) continue; if (selection.Count > 1 && action.execute == null) continue; var button = buttonElements[i++]; button.text = action.content.text; button.tooltip = action.content.tooltip; // We are testing for userData to make sure the clickable is only set once. // If not, because we keep refreshing the actions every 100 ms, the click event seems // to get stuck and the whole search window freezes. if (button.userData == null) { button.clickable = new Clickable(() => { var data = (ActionButtonData)button.userData; m_ViewModel.ExecuteAction(data.action, data.selection.ToArray(), false); }); } button.userData = new ActionButtonData() { action = action, selection = selection }; ShowElements(button); } } struct MoreButtonData { public SearchSelection selection; public IEnumerable<SearchAction> actions; } private void RefreshMoreMenu(SearchSelection selection, IEnumerable<SearchAction> actions) { if (!actions.Any()) { return; } // We are testing for userData to make sure the clickable is only set once. // If not, because we keep refreshing the actions every 100 ms, the click event seems // to get stuck and the whole search window freezes. if (m_MoreButton.userData == null) { m_MoreButton.clickable = new Clickable(() => { var menu = new GenericMenu(); var data = (MoreButtonData)m_MoreButton.userData; foreach (var action in data.actions) { if (action == null || action.content == null) continue; if (data.selection.Count > 1 && action.execute == null) continue; var itemName = !string.IsNullOrWhiteSpace(action.content.text) ? action.content.text : action.content.tooltip; menu.AddItem(new GUIContent(itemName, action.content.image), false, () => m_ViewModel.ExecuteAction(action, data.selection.ToArray(), false)); } menu.ShowAsContext(); }); } m_MoreButton.userData = new MoreButtonData() { actions = actions, selection = selection }; ShowElements(m_MoreButton); } private void DrawDescription(SearchContext ctx, SearchItem item) { item.options |= SearchItemOptions.FullDescription; var description = item.GetDescription(ctx, false); item.options &= ~SearchItemOptions.FullDescription; m_DescriptionLabel.text = description; ShowElements(m_DescriptionLabel); } private void DrawPreview(SearchContext ctx, SearchItem item) { if (m_PreviewImageRefreshCallback?.isActive == true) m_PreviewImageRefreshCallback.Pause(); var editorWithPreview = m_Editors?.FirstOrDefault(x => x.HasPreviewGUI()); if (editorWithPreview != null) { m_InteractivePreviewElement.style.height = 256; m_InteractivePreviewElement.onGUIHandler = () => { if (editorWithPreview.targets.All(t => t)) editorWithPreview.DrawPreview(m_InteractivePreviewElement.contentRect); }; ShowElements(m_InteractivePreviewElement); } else { UpdatePreviewImage(ctx, item, resolvedStyle.width, this); if (item.provider?.id.Equals("store", StringComparison.Ordinal) == true) { m_PreviewImageRefreshCallback = m_PreviewImage.schedule.Execute(() => UpdatePreviewImage(ctx, item, resolvedStyle.width, this)); m_PreviewImageRefreshCallback .StartingIn(500) .Every(500) .Until(() => m_PreviewImage?.style.display == DisplayStyle.None || context.selection?.Any() == false); } } } static void UpdatePreviewImage(SearchContext ctx, SearchItem item, float width, SearchDetailView view) { if (view.context.selection.Count == 0) return; var previewImage = view.m_PreviewImage; Texture2D thumbnail = null; if (SearchSettings.fetchPreview && width >= 32) { // TODO: Use SearchPreviewManager thumbnail = item.GetPreview(ctx, new Vector2(width, 256f), FetchPreviewOptions.Large | FetchPreviewOptions.Preview2D, cacheThumbnail: false); } if (thumbnail == null) thumbnail = item.GetThumbnail(ctx, cacheThumbnail: false); if (!IsBuiltInIcon(thumbnail)) { previewImage.image = thumbnail; ShowElements(previewImage); } } private static bool IsBuiltInIcon(Texture icon) { return Utils.IsBuiltInResource(icon); } private void DrawInspector(SearchSelection selection, ShowDetailsOptions showOptions) { m_EditorContainer.Clear(); if (m_Editors == null) return; bool hasValidEditor = false; for (int i = 0; i < m_Editors.Length; ++i) { var e = m_Editors[i]; if (!Utils.IsEditorValid(e)) continue; var editorElement = new SearchItemEditorElement(null, e); editorElement.HideHeader(showOptions.HasFlag(ShowDetailsOptions.InspectorWithoutHeader)); m_EditorContainer.Add(editorElement); hasValidEditor = true; } if (hasValidEditor) { ShowElements(m_EditorContainer); } } private bool SetupEditors(SearchSelection selection, ShowDetailsOptions showOptions) { int selectionHash = 0; foreach (var s in selection) selectionHash ^= s.id.GetHashCode(); if (selectionHash == m_EditorsHash) return false; ResetEditors(); if (!showOptions.HasAny(ShowDetailsOptions.Inspector)) return true; var targets = new List<UnityEngine.Object>(); foreach (var s in selection) { var item = s; GetTargetsFromSearchItem(item, targets); if (item.GetFieldCount() > 0) { var targetItem = ScriptableObject.CreateInstance<SearchServiceItem>(); targetItem.hideFlags |= HideFlags.DontSaveInEditor; targetItem.name = item.label ?? item.value.ToString(); targetItem.item = item; targets.Add(targetItem); } } if (targets.Count > 0) { int maxGroupCount = targets.GroupBy(t => t.GetType()).Max(g => g.Count()); m_Editors = targets.GroupBy(t => t.GetType()).Where(g => g.Count() == maxGroupCount).Select(g => { var editor = Editor.CreateEditor(g.ToArray()); Utils.SetFirstInspectedEditor(editor); return editor; }).ToArray(); } m_EditorsHash = selectionHash; return true; } private void ResetEditors() { if (m_Editors != null) { foreach (var e in m_Editors) UnityEngine.Object.DestroyImmediate(e); } m_Editors = null; m_EditorsHash = 0; } private bool GetTargetsFromSearchItem(SearchItem item, List<UnityEngine.Object> targets) { item.options |= SearchItemOptions.FullDescription; var itemObject = item.ToObject(); item.options &= ~SearchItemOptions.FullDescription; if (!itemObject) return false; if (itemObject is GameObject go) { var components = go.GetComponents<Component>(); foreach (var c in components) { if (!c || (c.hideFlags & HideFlags.HideInInspector) == HideFlags.HideInInspector) continue; targets.Add(c); } } else { targets.Add(itemObject); if (item.provider.id == "asset") { var importer = AssetImporter.GetAtPath(item.id); if (importer && importer.GetType() != typeof(AssetImporter)) targets.Add(importer); } } return true; } } }
UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchDetailView.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchDetailView.cs", "repo_id": "UnityCsReference", "token_count": 10515 }
422
// 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.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine.UIElements; namespace UnityEditor.Search { abstract class BaseSearchListComparer : ISearchListComparer { protected virtual bool UseProviderPriority => true; public virtual int Compare(SearchItem x, SearchItem y) { if (x == null && y == null) return 0; if (x == null) return 2; if (y == null) return -2; var compareFavoriteStateResult = CompareFavoriteState(x, y); if (compareFavoriteStateResult != 0) return compareFavoriteStateResult; var xa = x.options.HasAny(SearchItemOptions.CustomAction); var ya = y.options.HasAny(SearchItemOptions.CustomAction); var p = UseProviderPriority ? CompareByProviderPriority(x, y) : 0; if (xa && ya) { if (UseProviderPriority && p != 0) return p; return BaseCompare(x, y); } if (xa) return -3; if (ya) return 3; if (UseProviderPriority && p != 0) return p; return CompareItems(x, y); } public int CompareFavoriteState(SearchItem x, SearchItem y) { var xIsFavorite = SearchSettings.searchItemFavorites.Contains(x.id); var yIsFavorite = SearchSettings.searchItemFavorites.Contains(y.id); if (xIsFavorite && yIsFavorite) return 0; if (!xIsFavorite && !yIsFavorite) return 0; if (xIsFavorite) return -1; return 1; } public override int GetHashCode() { return GetType().Name.GetHashCode(); } public static int BaseCompare(in SearchItem x, in SearchItem y) { int c = x.score.CompareTo(y.score); if (c != 0) return c; return string.CompareOrdinal(x.id, y.id); } public static int CompareByProviderPriority(in SearchItem x, in SearchItem y) { var px = x.provider; var py = y.provider; if (px == null && py == null) return 0; if (px == null) return 1; if (py == null) return -1; return px.priority.CompareTo(py.priority); } public virtual int CompareItems(in SearchItem x, in SearchItem y) { return BaseCompare(x, y); } protected static int DefaultCompare(object lhsv, object rhsv, bool sortAscending = true) { var sortOrder = sortAscending ? 1 : -1; if (lhsv is string s) return string.Compare(s, rhsv?.ToString(), StringComparison.OrdinalIgnoreCase) * sortOrder; if (lhsv is IComparable c) return Comparer.Default.Compare(c, rhsv) * sortOrder; return Comparer.Default.Compare(lhsv?.GetHashCode() ?? 0, rhsv?.GetHashCode() ?? 0) * sortOrder; } } class SortByScoreComparer : BaseSearchListComparer { } class SortByLabelComparer : BaseSearchListComparer { public override int CompareItems(in SearchItem x, in SearchItem y) { var compareFavoriteStateResult = CompareFavoriteState(x, y); if (compareFavoriteStateResult != 0) return compareFavoriteStateResult; var xl = x.GetLabel(x.context); var yl = y.GetLabel(y.context); int c = string.Compare(xl, yl, StringComparison.OrdinalIgnoreCase); if (c != 0) return c; return base.CompareItems(x, y); } } class SortByNameComparer : SortBySelector { public SortByNameComparer() : base(new SearchSelector(new Regex("name"), 0, null, true, SelectName, "Name", cacheable: true)) { } private static object SelectName(SearchSelectorArgs args) { var item = args.current; if (string.CompareOrdinal(item.provider.id, "asset") == 0) { if (item.data is Providers.AssetProvider.AssetMetaInfo info) { if (!string.IsNullOrEmpty(info.path)) return System.IO.Path.GetFileName(info.path); return info.obj?.name; } } else if (string.CompareOrdinal(item.provider.id, "scene") == 0) { var go = item.ToObject<UnityEngine.GameObject>(); if (!go) return null; return go.name; } return item.GetLabel(item.context); } } class SortByDescriptionComparer : BaseSearchListComparer { public override int CompareItems(in SearchItem x, in SearchItem y) { var compareFavoriteStateResult = CompareFavoriteState(x, y); if (compareFavoriteStateResult != 0) return compareFavoriteStateResult; var xl = x.GetDescription(x.context); var yl = y.GetDescription(y.context); int c = string.Compare(xl, yl, StringComparison.OrdinalIgnoreCase); if (c != 0) return c; return base.CompareItems(x, y); } } class SortBySelector : BaseSearchListComparer { private readonly SearchSelector selector; public SortBySelector(SearchSelector selector) { this.selector = selector; } public override int CompareItems(in SearchItem x, in SearchItem y) { var compareFavoriteStateResult = CompareFavoriteState(x, y); if (compareFavoriteStateResult != 0) return compareFavoriteStateResult; var xs = selector.select(new SearchSelectorArgs(default, x)); var ys = selector.select(new SearchSelectorArgs(default, y)); if (xs == null && ys == null) return 0; if (xs == null) return 2; if (ys == null) return -2; var c = DefaultCompare(xs, ys, sortAscending: true); if (c != 0) return c; return base.CompareItems(x, y); } public override int GetHashCode() { return HashCode.Combine(selector.label, base.GetHashCode()); } } class SearchTableViewColumnSorter : BaseSearchListComparer { readonly struct CD { public readonly SortDirection direction; public readonly SearchColumn.CompareEntry comparer; public readonly SearchColumn column; public CD(SearchColumn column, SortDirection direction) { this.direction = direction; this.column = column; this.comparer = column.comparer; } } readonly struct ValueKey : IEquatable<ValueKey> { public readonly ulong itemKey; public readonly int columnKey; public ValueKey(ulong itemKey, int columnKey) { this.itemKey = itemKey; this.columnKey = columnKey; } public override string ToString() => $"{columnKey} > {itemKey}"; public override int GetHashCode() => HashCode.Combine(itemKey, columnKey); public override bool Equals(object other) => other is ValueKey l && Equals(l); public bool Equals(ValueKey other) => columnKey == other.columnKey && itemKey == other.itemKey; } protected override bool UseProviderPriority => m_Comparers.Count == 0; private readonly List<CD> m_Comparers = new List<CD>(); private readonly Dictionary<ValueKey, object> m_ValueCache = new Dictionary<ValueKey, object>(); public override int GetHashCode() { int hash = 17; foreach (var comp in m_Comparers) hash = HashCode.Combine(hash, comp.column.path, comp.direction); return hash; } public override int CompareItems(in SearchItem x, in SearchItem y) { if (m_Comparers.Count == 0) return BaseCompare(x, y); foreach (var comp in m_Comparers) { var lhs = new SearchColumnEventArgs(x, x.context, comp.column); var rhs = new SearchColumnEventArgs(y, y.context, comp.column); lhs.value = GetValue(lhs); rhs.value = GetValue(rhs); if (lhs.value == null && rhs.value == null) continue; if (lhs.value == null) return 2; if (rhs.value == null) return -2; var compareArgs = new SearchColumnCompareArgs(lhs, rhs, comp.direction == SortDirection.Ascending); var cc = (comp.comparer ?? DefaultCompare)(compareArgs); if (cc != 0) return cc; } // We come here if, for all comparers, both values were null or equal. // So try one more time with BaseCompare. var p = CompareByProviderPriority(x, y); if (p != 0) return p; return BaseCompare(x, y); } object GetValue(in SearchColumnEventArgs args) { var key = new ValueKey(args.item.id.GetHashCode64(), args.column.path.GetHashCode()); if (m_ValueCache.TryGetValue(key, out var value)) return value; value = args.column.getter(args); m_ValueCache[key] = value; return value; } int DefaultCompare(SearchColumnCompareArgs args) { var lhsv = args.lhs.value; var rhsv = args.rhs.value; return DefaultCompare(lhsv, rhsv, args.sortAscending); } public void Add(SearchColumn column, SortDirection direction) { m_Comparers.Add(new CD(column, direction)); } } }
UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchTableViewColumnSorter.cs/0
{ "file_path": "UnityCsReference/Modules/QuickSearch/Editor/UITK/SearchTableViewColumnSorter.cs", "repo_id": "UnityCsReference", "token_count": 4950 }
423
// 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.UIElements; using UnityEngine; using UnityEngine.UIElements; namespace UnityEditor.SceneTemplate { internal class GridView : VisualElement { List<Item> m_PinnedItems; List<Item> m_UnpinnedItems; List<Item> m_SelectedItems; List<Item> m_Items; Dictionary<int, VisualElement> m_IdToElements; VisualElement m_Header; VisualElement m_Footer; VisualElement m_ItemsContainer; Slider m_TileSizeSlider; ScrollView m_ItemsScrollView; bool m_ShowHeader; bool m_ShowFooter; public class Item { private int m_Id; private string m_Label; private Texture2D m_Icon; private Texture2D m_Badge; private object m_UserData; public Item(int id, string label, Texture2D icon = null, Texture2D badge = null, object userData = null, int priority = -1) { m_Id = id; m_Label = label; m_Icon = icon; m_Badge = badge; m_UserData = userData; this.priority = priority; } public int id => m_Id; public Texture2D icon => m_Icon; public Texture2D badge => m_Badge; public string label => m_Label; public object userData => m_UserData; public int priority { get; internal set; } } private float m_SizeLevel; public float sizeLevel { get => m_SizeLevel; set { var listViewChange = isListView; m_SizeLevel = value; if (listViewChange != isListView) { if (isListView) { m_ItemsContainer.RemoveFromClassList(Styles.gridViewItemsContainerGrid); m_ItemsContainer.AddToClassList(Styles.gridViewItemsContainerList); } else { m_ItemsContainer.RemoveFromClassList(Styles.gridViewItemsContainerList); m_ItemsContainer.AddToClassList(Styles.gridViewItemsContainerGrid); } } LayoutItems(); m_TileSizeSlider.SetValueWithoutNotify(value); sizeLevelChanged?.Invoke(m_SizeLevel, isListView); } } public bool isListView => sizeLevel < minTileSize; string m_FilterString; public string filterString { get => m_FilterString; set { m_FilterString = value.Trim(); foreach (var element in m_IdToElements.Values) { var isFiltered = IsFiltered(element.userData as Item, m_FilterString); if (isFiltered && element.style.display == DisplayStyle.None) { element.style.display = DisplayStyle.Flex; } else if (!isFiltered && element.style.display != DisplayStyle.None) { element.style.display = DisplayStyle.None; } } } } public bool multiSelection { get; set; } public bool wrapAroundKeyboardNavigation { get; set; } public bool showHeader { get => m_ShowHeader; set { m_ShowHeader = value; m_Header.visible = value; } } public bool showFooter { get => m_ShowFooter; set { m_ShowFooter = value; m_Footer.visible = value; } } public bool thumbnailVisible => sizeLevel >= showThumbnailTileSizeThreshold; public float minTileSize { get; private set; } public float maxTileSize { get; private set; } public float showThumbnailTileSizeThreshold { get; } public float listItemHeight { get; private set; } public float aspectRatio { get; private set; } public Texture2D defaultThumbnail { get; } public IEnumerable<Item> items => m_Items; public IEnumerable<Item> pinnedItems => m_PinnedItems; public IEnumerable<Item> unpinnedItems => m_UnpinnedItems; public IEnumerable<Item> selectedItems => m_SelectedItems; public event Action<float, bool> sizeLevelChanged; public event Action<IEnumerable<Item>, IEnumerable<Item>> onSelectionChanged; public event Action<Item, bool> onPinnedChanged; public event Action<IEnumerable<Item>> onItemsActivated; public GridView(IEnumerable<Item> items, string title, float listItemHeight, float minTileSize, float maxTileSize, float showThumbnailTileSizeThreshold, Texture2D defaultThumbnail, float aspectRatio) { AddToClassList(Styles.gridView); this.aspectRatio = aspectRatio; this.listItemHeight = listItemHeight; this.minTileSize = minTileSize; this.maxTileSize = maxTileSize; this.showThumbnailTileSizeThreshold = showThumbnailTileSizeThreshold; this.defaultThumbnail = defaultThumbnail; m_Header = new VisualElement(); m_Header.AddToClassList(Styles.gridViewHeader); { var headerLabel = new Label(title); headerLabel.AddToClassList(Styles.gridViewHeaderLabel); m_Header.Add(headerLabel); var searchField = new ToolbarSearchField(); searchField.AddToClassList(Styles.gridViewHeaderSearchField); searchField.RegisterValueChangedCallback(evt => filterString = evt.newValue); m_Header.Add(searchField); } Add(m_Header); m_ItemsScrollView = new ScrollView(); m_ItemsScrollView.AddToClassList(Styles.gridViewItemsScrollView); m_ItemsScrollView.RegisterCallback<MouseDownEvent>(evt => HandleSelect(evt, null)); m_ItemsScrollView.focusable = true; m_ItemsScrollView.RegisterCallback<KeyDownEvent>(OnKeyDown); Add(m_ItemsScrollView); m_ItemsContainer = new VisualElement(); m_ItemsContainer.AddToClassList(Styles.gridViewItems); m_ItemsScrollView.Add(m_ItemsContainer); m_Footer = new VisualElement(); m_Footer.AddToClassList(Styles.gridViewFooter); { m_TileSizeSlider = new Slider(); m_TileSizeSlider.lowValue = minTileSize - 1; m_TileSizeSlider.highValue = maxTileSize; m_TileSizeSlider.RegisterValueChangedCallback(evt => { sizeLevel = evt.newValue; }); m_TileSizeSlider.AddToClassList(Styles.gridViewFooterTileSize); m_Footer.Add(m_TileSizeSlider); } Add(m_Footer); showHeader = true; showFooter = true; SetItems(items); sizeLevel = maxTileSize; } public void SetItems(IEnumerable<Item> items) { m_UnpinnedItems = items.ToList(); m_Items = items.ToList(); for (var i = 0; i < m_Items.Count; i++) { var item = m_Items[i]; if (item.priority == -1) { item.priority = i; } } m_Items.Sort((a, b) => a.priority - b.priority); m_IdToElements = new Dictionary<int, VisualElement>(); m_PinnedItems = new List<Item>(); m_SelectedItems = new List<Item>(); RefreshItemElements(); } public void SetFocus() { m_ItemsScrollView.tabIndex = 0; m_ItemsScrollView.Focus(); } public bool IsPinned(Item item) { return m_PinnedItems.Contains(item); } public bool IsSelected(Item item) { return m_SelectedItems.Contains(item); } public void SetSelection(Item itemToSelect) { SetSelection(new[] { itemToSelect }); } public void SetSelection(IEnumerable<Item> itemToSelect) { if (m_SelectedItems.Count > 0) { // Unselect currently selected item: foreach (var toUnselectElement in m_SelectedItems.Select(item => m_IdToElements[item.id])) { toUnselectElement.RemoveFromClassList(Styles.selected); } } var oldSelection = m_SelectedItems.ToList(); m_SelectedItems = itemToSelect.ToList(); if (itemToSelect.Any()) { // Select new item var toSelectElements = itemToSelect.Select(item => m_IdToElements[item.id]); foreach (var toSelectElement in toSelectElements) { toSelectElement.AddToClassList(Styles.selected); } } onSelectionChanged?.Invoke(oldSelection, itemToSelect); } public void ClearSelection() { SetSelection(new Item[0]); } public void SelectAll() { SetSelection(m_Items); } public void SetSelection(int idToSelect) { SetSelection(IdToItem(idToSelect)); } public void SetSelection(IEnumerable<int> idToSelect) { SetSelection(idToSelect.Select(IdToItem)); } public void SetPinned(IEnumerable<int> idToPinned) { SetPinned(idToPinned.Select(IdToItem)); } public void SetPinned(IEnumerable<Item> idToPinned) { m_PinnedItems.Clear(); foreach (var item in idToPinned) { TogglePinned(item); } } public void TogglePinned(Item item) { bool toggleToPin = !IsPinned(item); var element = m_IdToElements[item.id]; if (toggleToPin) { element.AddToClassList(Styles.pinned); m_PinnedItems.Add(item); element.RemoveFromHierarchy(); var insertionPoint = 0; for (; insertionPoint < m_ItemsContainer.childCount; ++insertionPoint) { var e = m_ItemsContainer.ElementAt(insertionPoint); if (!e.ClassListContains(Styles.pinned)) { break; } if ((e.userData as Item).priority >= item.priority) { break; } } m_ItemsContainer.Insert(insertionPoint, element); } else { element.RemoveFromClassList(Styles.pinned); m_PinnedItems.Remove(item); element.RemoveFromHierarchy(); var insertionPoint = m_PinnedItems.Count; for (; insertionPoint < m_ItemsContainer.childCount; ++insertionPoint) { var e = m_ItemsContainer.ElementAt(insertionPoint); if ((e.userData as Item).priority >= item.priority) { break; } } m_ItemsContainer.Insert(insertionPoint, element); } onPinnedChanged?.Invoke(item, toggleToPin); } public void OnKeyDown(KeyDownEvent evt) { if (evt == null) return; var shouldStopPropagation = true; VisualElement elementSelected = null; switch (evt.keyCode) { case KeyCode.UpArrow: elementSelected = NavigateToPreviousItem(); break; case KeyCode.DownArrow: elementSelected = NavigateToNextItem(); break; case KeyCode.RightArrow: if (!isListView) elementSelected = NavigateToNextItem(); break; case KeyCode.LeftArrow: if (!isListView) elementSelected = NavigateToPreviousItem(); break; case KeyCode.Tab: elementSelected = NavigateToNextItem(); break; case KeyCode.Home: elementSelected = SetSelectedVisibleIndex(0, true); break; case KeyCode.End: elementSelected = SetSelectedVisibleIndex(m_Items.Count - 1, false); break; case KeyCode.Return: onItemsActivated?.Invoke(m_SelectedItems); break; case KeyCode.A: if (evt.actionKey && multiSelection) { SelectAll(); } break; case KeyCode.Escape: ClearSelection(); break; default: shouldStopPropagation = false; break; } if (shouldStopPropagation) evt.StopPropagation(); if (elementSelected != null) { m_ItemsScrollView.ScrollTo(elementSelected); } } public Item IdToItem(int id) { return m_IdToElements[id].userData as Item; } public void RefreshItemElements() { m_ItemsContainer.Clear(); foreach (var item in m_Items) { var element = CreateItemElement(item); m_IdToElements[item.id] = element; m_ItemsContainer.Add(element); } LayoutItems(); } private int GetSelectedVisibleIndex() { var lastSelectedItem = m_SelectedItems.LastOrDefault(); var lastSelectedElement = lastSelectedItem == null ? null : m_IdToElements[lastSelectedItem.id]; var selectedIndex = lastSelectedElement == null || lastSelectedElement.style.display == DisplayStyle.None ? -1 : m_ItemsContainer.IndexOf(lastSelectedElement); return selectedIndex; } private VisualElement SetSelectedVisibleIndex(int index, bool forward) { if (index >= m_ItemsContainer.childCount) { index = m_ItemsContainer.childCount; } if (index == -1) { ClearSelection(); return null; } var elementToSelect = m_ItemsContainer.ElementAt(index); if (forward) { while (m_ItemsContainer.ElementAt(index).style.display == DisplayStyle.None && ++index < m_ItemsContainer.childCount) { elementToSelect = m_ItemsContainer.ElementAt(index); } } else { while (elementToSelect.style.display == DisplayStyle.None && --index >= 0) { elementToSelect = m_ItemsContainer.ElementAt(index); } } if (elementToSelect.style.display == DisplayStyle.None) { return null; } var itemToSelect = elementToSelect.userData as Item; if (IsSelected(itemToSelect) && m_SelectedItems.Count == 1) return elementToSelect; SetSelection(itemToSelect); return elementToSelect; } private void AddToSelection(Item item) { var oldSelection = m_SelectedItems.ToList(); m_SelectedItems.Add(item); m_IdToElements[item.id].AddToClassList(Styles.selected); onSelectionChanged?.Invoke(oldSelection, m_SelectedItems); } private void RemoveFromSelection(Item item) { var oldSelection = m_SelectedItems.ToList(); m_SelectedItems.Remove(item); m_IdToElements[item.id].RemoveFromClassList(Styles.selected); onSelectionChanged?.Invoke(oldSelection, m_SelectedItems); } private VisualElement NavigateToNextItem() { var selectedIndex = GetSelectedVisibleIndex(); if (selectedIndex == -1) selectedIndex = 0; else if (selectedIndex + 1 < m_Items.Count) selectedIndex = selectedIndex + 1; else if (wrapAroundKeyboardNavigation) selectedIndex = 0; return SetSelectedVisibleIndex(selectedIndex, true); } private VisualElement NavigateToPreviousItem() { var selectedIndex = GetSelectedVisibleIndex(); if (selectedIndex == -1) selectedIndex = 0; else if (selectedIndex > 0) selectedIndex = selectedIndex - 1; else if (wrapAroundKeyboardNavigation) selectedIndex = m_Items.Count - 1; return SetSelectedVisibleIndex(selectedIndex, false); } private static bool IsFiltered(Item item, string filter) { if (string.IsNullOrEmpty(filter)) return true; return item.label.IndexOf(filter, StringComparison.InvariantCultureIgnoreCase) != -1; } private VisualElement CreateItemElement(Item item) { var element = new VisualElement(); element.AddToClassList(Styles.gridViewItemElement); element.userData = item; var icon = new VisualElement(); icon.AddToClassList(Styles.gridViewItemIcon); if (item.icon != null) { icon.style.backgroundImage = item.icon; } element.Add(icon); var pinBtn = new Button(() => { TogglePinned(item); }); pinBtn.AddToClassList(Styles.gridViewItemPin); icon.Add(pinBtn); if (item.badge != null) { var badge = new VisualElement(); badge.AddToClassList(Styles.gridViewItemBadge); badge.style.backgroundImage = item.badge; icon.Add(badge); } var label = new Label(item.label); label.AddToClassList(Styles.gridViewItemLabel); element.Add(label); element.RegisterCallback<MouseDownEvent>(evt => HandleSelect(evt, element)); return element; } private void HandleSelect(MouseDownEvent evt, VisualElement clicked) { if (clicked == null) { ClearSelection(); return; } if (evt.button != 0) return; var item = clicked.userData as Item; if (evt.clickCount == 1) { if (multiSelection) { if (evt.ctrlKey) { if (IsSelected(item)) { RemoveFromSelection(item); } else { AddToSelection(item); } } else if (!IsSelected(item)) { SetSelection(new[] { item }); } } else { if (IsSelected(item)) { if (evt.ctrlKey) { ClearSelection(); } } else { SetSelection(new[] { item }); } } } else if (evt.clickCount == 2 && m_SelectedItems.Count > 0) { onItemsActivated?.Invoke(m_SelectedItems); } evt.StopPropagation(); } private void LayoutItems() { // Because I can't figure out how to get the resolved style values coming from uss on the first pass. const float badgeMaxHeight = 32; var allItemElements = m_ItemsContainer.Children(); foreach (var element in allItemElements) { var item = element.userData as Item; if (item == null) continue; var pin = element.Q(null, Styles.gridViewItemPin); var icon = element.Q(null, Styles.gridViewItemIcon); var badge = element.Q(null, Styles.gridViewItemBadge); if (isListView) { element.style.height = listItemHeight; element.style.width = Length.Percent(100); icon.style.width = listItemHeight; icon.style.minWidth = listItemHeight; pin.RemoveFromHierarchy(); element.Insert(0, pin); } else { element.style.width = sizeLevel * aspectRatio; element.style.height = sizeLevel; icon.style.width = StyleKeyword.Auto; pin.RemoveFromHierarchy(); icon.Add(pin); } if (thumbnailVisible) { if (badge != null) { badge.visible = true; badge.style.height = Mathf.Min(badgeMaxHeight, element.style.height.value.value * 0.3f); var badgeWidth = badge.style.backgroundImage.value.texture.width; var badgeHeight = badge.style.backgroundImage.value.texture.height; var ratio = (float)badgeWidth / badgeHeight; badge.style.width = badge.style.height.value.value * ratio; } icon.style.backgroundImage = item.icon ? item.icon : defaultThumbnail; } else { if (badge != null) badge.visible = false; icon.style.backgroundImage = item.badge ? item.badge : defaultThumbnail; } } } } }
UnityCsReference/Modules/SceneTemplateEditor/GridView.cs/0
{ "file_path": "UnityCsReference/Modules/SceneTemplateEditor/GridView.cs", "repo_id": "UnityCsReference", "token_count": 12567 }
424
// 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.SceneTemplate { class VisualSplitter : VisualElement { const float k_SplitterSize = 7f; private readonly VisualElement m_Dragger; private readonly Resizer m_Resizer; public VisualElement fixedPane { get; private set; } public VisualElement flexedPane { get; private set; } public VisualSplitter(VisualElement fixedPane, VisualElement flexedPane, FlexDirection direction) { this.fixedPane = fixedPane; this.flexedPane = flexedPane; m_Resizer = new Resizer(this, 1, direction); flexedPane.style.flexGrow = 1; m_Dragger = new VisualElement(); m_Dragger.style.position = Position.Absolute; m_Dragger.AddManipulator(m_Resizer); if (direction == FlexDirection.Column) { m_Dragger.style.height = k_SplitterSize; m_Dragger.style.top = -Mathf.RoundToInt(k_SplitterSize / 2f); m_Dragger.style.left = 0f; m_Dragger.style.right = 0f; m_Dragger.style.cursor = LoadCursor(MouseCursor.ResizeVertical); } else if (direction == FlexDirection.Row) { m_Dragger.style.width = k_SplitterSize; m_Dragger.style.left = -Mathf.RoundToInt(k_SplitterSize / 2f); m_Dragger.style.top = 0f; m_Dragger.style.bottom = 0f; m_Dragger.style.cursor = LoadCursor(MouseCursor.ResizeHorizontal); } Add(fixedPane); Add(flexedPane); Add(m_Dragger); RegisterCallback<GeometryChangedEvent>(OnSizeChange); style.flexGrow = 1; style.flexDirection = direction; } private UnityEngine.UIElements.Cursor LoadCursor(MouseCursor cursorStyle) { var boxed = new UnityEngine.UIElements.Cursor(); boxed.defaultCursorId = (int)cursorStyle; return boxed; } private void OnSizeChange(GeometryChangedEvent evt) { if (style.flexDirection.value == FlexDirection.Row) m_Dragger.style.left = fixedPane.resolvedStyle.width; else m_Dragger.style.top = fixedPane.resolvedStyle.height; } class Resizer : MouseManipulator { private bool m_Active; private Vector2 m_Start; private readonly int m_Direction; private readonly FlexDirection m_Orientation; private readonly VisualSplitter m_Splitter; private VisualElement fixedPane => m_Splitter.fixedPane; private VisualElement flexedPane => m_Splitter.flexedPane; private float fixedPaneMinDimension => m_Orientation == FlexDirection.Row ? fixedPane.resolvedStyle.minWidth.value : fixedPane.resolvedStyle.minHeight.value; private float flexedPaneMinDimension => m_Orientation == FlexDirection.Row ? flexedPane.resolvedStyle.minWidth.value : flexedPane.resolvedStyle.minHeight.value; public Resizer(VisualSplitter splitView, int dir, FlexDirection orientation) { m_Orientation = orientation; m_Splitter = splitView; m_Direction = dir; activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse }); m_Active = false; } protected override void RegisterCallbacksOnTarget() { target.RegisterCallback<MouseDownEvent>(OnMouseDown); target.RegisterCallback<MouseMoveEvent>(OnMouseMove); target.RegisterCallback<MouseUpEvent>(OnMouseUp); } protected override void UnregisterCallbacksFromTarget() { target.UnregisterCallback<MouseDownEvent>(OnMouseDown); target.UnregisterCallback<MouseMoveEvent>(OnMouseMove); target.UnregisterCallback<MouseUpEvent>(OnMouseUp); } public void ApplyDelta(float delta) { float oldDimension = m_Orientation == FlexDirection.Row ? fixedPane.resolvedStyle.width : fixedPane.resolvedStyle.height; float newDimension = oldDimension + delta; if (newDimension < oldDimension && newDimension < fixedPaneMinDimension) newDimension = fixedPaneMinDimension; float maxDimension = m_Orientation == FlexDirection.Row ? m_Splitter.resolvedStyle.width : m_Splitter.resolvedStyle.height; maxDimension -= flexedPaneMinDimension; if (newDimension > oldDimension && newDimension > maxDimension) newDimension = maxDimension; if (m_Orientation == FlexDirection.Row) { fixedPane.style.width = newDimension; target.style.left = newDimension; } else { fixedPane.style.height = newDimension; target.style.top = newDimension; } } protected void OnMouseDown(MouseDownEvent e) { if (m_Active) { e.StopImmediatePropagation(); } else if (CanStartManipulation(e)) { m_Start = e.localMousePosition; m_Active = true; target.CaptureMouse(); e.StopPropagation(); } } protected void OnMouseMove(MouseMoveEvent e) { if (!m_Active || !target.HasMouseCapture()) return; Vector2 diff = e.localMousePosition - m_Start; float mouseDiff = m_Orientation == FlexDirection.Row ? diff.x : diff.y; float delta = m_Direction * mouseDiff; ApplyDelta(delta); e.StopPropagation(); } protected void OnMouseUp(MouseUpEvent e) { if (!m_Active || !target.HasMouseCapture() || !CanStopManipulation(e)) return; m_Active = false; target.ReleaseMouse(); e.StopPropagation(); } } } }
UnityCsReference/Modules/SceneTemplateEditor/VisualSplitter.cs/0
{ "file_path": "UnityCsReference/Modules/SceneTemplateEditor/VisualSplitter.cs", "repo_id": "UnityCsReference", "token_count": 3302 }
425
// 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/CustomizationPoint.h")] internal struct CustomizationPointInternal : IInternalType<CustomizationPointInternal> { internal FoundryHandle m_NameHandle; internal FoundryHandle m_AttributeListHandle; internal FoundryHandle m_ContainingNamespaceHandle; internal FoundryHandle m_InterfaceFieldListHandle; internal FoundryHandle m_DefaultBlockSequenceElementListHandle; internal extern static CustomizationPointInternal Invalid(); internal extern bool IsValid(); // IInternalType CustomizationPointInternal IInternalType<CustomizationPointInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct CustomizationPoint : IEquatable<CustomizationPoint>, IPublicType<CustomizationPoint> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly CustomizationPointInternal customizationPoint; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; CustomizationPoint IPublicType<CustomizationPoint>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new CustomizationPoint(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid); public string Name => container?.GetString(customizationPoint.m_NameHandle) ?? string.Empty; public IEnumerable<ShaderAttribute> Attributes => HandleListInternal.Enumerate<ShaderAttribute>(container, customizationPoint.m_AttributeListHandle); public Namespace ContainingNamespace => new Namespace(container, customizationPoint.m_ContainingNamespaceHandle); public IEnumerable<BlockVariable> InterfaceFields => GetVariableEnumerable(customizationPoint.m_InterfaceFieldListHandle); public IEnumerable<BlockVariable> Inputs => InterfaceFields.Select(BlockVariableInternal.Flags.kInput); public IEnumerable<BlockVariable> Outputs => InterfaceFields.Select(BlockVariableInternal.Flags.kOutput); // TODO @ SHADERS: Delete this once we don't rely on it in the prototype internal IEnumerable<BlockSequenceElement> DefaultBlockSequenceElements { get { return customizationPoint.m_DefaultBlockSequenceElementListHandle.AsListEnumerable(container, (container, handle) => new BlockSequenceElement(container, handle)); } } IEnumerable<BlockVariable> GetVariableEnumerable(FoundryHandle listHandle) { var localContainer = Container; var list = new HandleListInternal(listHandle); return list.Select<BlockVariable>(localContainer, (handle) => (new BlockVariable(localContainer, handle))); } // private internal CustomizationPoint(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out customizationPoint); } public static CustomizationPoint Invalid => new CustomizationPoint(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 CustomizationPoint other && this.Equals(other); public bool Equals(CustomizationPoint other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(CustomizationPoint lhs, CustomizationPoint rhs) => lhs.Equals(rhs); public static bool operator!=(CustomizationPoint lhs, CustomizationPoint rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; internal string name; public List<ShaderAttribute> attributes; public Namespace containingNamespace = Namespace.Invalid; public List<BlockVariable> interfaceFields { get; set; } = new List<BlockVariable>(); public List<BlockVariable> properties { get; set; } = new List<BlockVariable>(); public List<BlockSequenceElement> defaultBlockSequenceElements; public ShaderContainer Container => container; public Builder(ShaderContainer container, string name) { this.container = container; this.name = name; } public void AddAttribute(ShaderAttribute attribute) => Utilities.AddToList(ref attributes, attribute); public void AddInterfaceField(BlockVariable field) { interfaceFields.Add(field); } // TODO @ SHADERS: Delete this once we don't rely on it in the prototype internal void AddDefaultBlockSequenceElement(BlockSequenceElement blockSequenceElement) => Utilities.AddToList(ref defaultBlockSequenceElements, blockSequenceElement); public CustomizationPoint Build() { var customizationPointInternal = new CustomizationPointInternal { m_NameHandle = container.AddString(name), }; customizationPointInternal.m_AttributeListHandle = HandleListInternal.Build(container, attributes); customizationPointInternal.m_ContainingNamespaceHandle = containingNamespace.handle; customizationPointInternal.m_InterfaceFieldListHandle = HandleListInternal.Build(container, interfaceFields, (v) => (v.handle)); customizationPointInternal.m_DefaultBlockSequenceElementListHandle = HandleListInternal.Build(container, defaultBlockSequenceElements, (v) => (v.handle)); var returnTypeHandle = container.Add(customizationPointInternal); return new CustomizationPoint(container, returnTypeHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/CustomizationPoint.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/CustomizationPoint.bindings.cs", "repo_id": "UnityCsReference", "token_count": 2263 }
426
// 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/KeywordDescriptor.h")] internal struct KeywordDescriptorInternal : IInternalType<KeywordDescriptorInternal> { internal FoundryHandle m_ListHandle; internal extern static KeywordDescriptorInternal Invalid(); internal extern void Setup(ShaderContainer container, string definition, string scope, string stage, string[] ops); internal extern string GetDefinition(ShaderContainer container); internal extern string GetScope(ShaderContainer container); internal extern string GetStage(ShaderContainer container); internal extern int GetOpCount(ShaderContainer container); internal extern string GetOp(ShaderContainer container, int index); // IInternalType KeywordDescriptorInternal IInternalType<KeywordDescriptorInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct KeywordDescriptor : IEquatable<KeywordDescriptor>, IPublicType<KeywordDescriptor> { // data members readonly ShaderContainer container; readonly KeywordDescriptorInternal descriptor; internal readonly FoundryHandle handle; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; KeywordDescriptor IPublicType<KeywordDescriptor>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new KeywordDescriptor(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && descriptor.m_ListHandle.IsValid); public string Definition => descriptor.GetDefinition(container); public string Scope => descriptor.GetScope(container); public string Stage => descriptor.GetStage(container); public IEnumerable<string> Ops { get { var opCount = descriptor.GetOpCount(container); for (var i = 0; i < opCount; ++i) yield return descriptor.GetOp(container, i); } } // private internal KeywordDescriptor(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out descriptor); } public static KeywordDescriptor Invalid => new KeywordDescriptor(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 KeywordDescriptor other && this.Equals(other); public bool Equals(KeywordDescriptor other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(KeywordDescriptor lhs, KeywordDescriptor rhs) => lhs.Equals(rhs); public static bool operator!=(KeywordDescriptor lhs, KeywordDescriptor rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; string definition; string scope; string stage; List<string> ops = new List<string>(); public ShaderContainer Container => container; public Builder(ShaderContainer container, string definition, string scope, string stage, IEnumerable<string> ops) { this.container = container; this.definition = definition; this.scope = scope; this.stage = stage; this.ops.AddRange(ops); } public KeywordDescriptor Build() { var descriptor = new KeywordDescriptorInternal(); descriptor.Setup(container, definition, scope, stage, ops.ToArray()); var resultHandle = container.Add(descriptor); return new KeywordDescriptor(container, resultHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/KeywordDescriptor.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/KeywordDescriptor.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1701 }
427
// 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/StageDescription.h")] internal struct StageDescriptionInternal : IInternalType<StageDescriptionInternal> { internal PassStageType m_StageType; internal FoundryHandle m_SetupVariablesListHandle; internal FoundryHandle m_ElementListHandle; internal extern static StageDescriptionInternal Invalid(); internal extern bool IsValid(); // IInternalType StageDescriptionInternal IInternalType<StageDescriptionInternal>.ConstructInvalid() => Invalid(); } [FoundryAPI] internal readonly struct StageDescription : IEquatable<StageDescription>, IPublicType<StageDescription> { // data members readonly ShaderContainer container; readonly internal FoundryHandle handle; readonly StageDescriptionInternal stageDescription; // IPublicType ShaderContainer IPublicType.Container => Container; bool IPublicType.IsValid => IsValid; FoundryHandle IPublicType.Handle => handle; StageDescription IPublicType<StageDescription>.ConstructFromHandle(ShaderContainer container, FoundryHandle handle) => new StageDescription(container, handle); // public API public ShaderContainer Container => container; public bool IsValid => (container != null && handle.IsValid && stageDescription.IsValid()); public PassStageType StageType => stageDescription.m_StageType; public IEnumerable<FunctionParameter> SetupVariables => stageDescription.m_SetupVariablesListHandle.AsListEnumerable<FunctionParameter>(Container, (container, handle) => (new FunctionParameter(container, handle))); public IEnumerable<FunctionParameter> InputSetupVariables => SetupVariables.Select(FunctionParameterInternal.Flags.kFlagsInput); public IEnumerable<FunctionParameter> OutputSetupVariables => SetupVariables.Select(FunctionParameterInternal.Flags.kFlagsOutput); public IEnumerable<BlockSequenceElement> Elements { get { return stageDescription.m_ElementListHandle.AsListEnumerable<BlockSequenceElement>(Container, (container, handle) => (new BlockSequenceElement(container, handle))); } } // private internal StageDescription(ShaderContainer container, FoundryHandle handle) { this.container = container; this.handle = handle; ShaderContainer.Get(container, handle, out stageDescription); } public static StageDescription Invalid => new StageDescription(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 StageDescription other && this.Equals(other); public bool Equals(StageDescription other) => EqualityChecks.ReferenceEquals(this.handle, this.container, other.handle, other.container); public override int GetHashCode() => (container, handle).GetHashCode(); public static bool operator==(StageDescription lhs, StageDescription rhs) => lhs.Equals(rhs); public static bool operator!=(StageDescription lhs, StageDescription rhs) => !lhs.Equals(rhs); public class Builder { ShaderContainer container; public PassStageType stageType; public List<FunctionParameter> setupVariables; public List<BlockSequenceElement> elements; public ShaderContainer Container => container; public Builder(ShaderContainer container, PassStageType stageType) { this.container = container; this.stageType = stageType; } public void AddElement(BlockSequenceElement element) { if (elements == null) elements = new List<BlockSequenceElement>(); elements.Add(element); } public void AddSetupVariable(FunctionParameter param) { if (setupVariables == null) setupVariables = new List<FunctionParameter>(); setupVariables.Add(param); } public StageDescription Build() { var stageDescriptionInternal = new StageDescriptionInternal() { m_StageType = stageType, }; stageDescriptionInternal.m_SetupVariablesListHandle = HandleListInternal.Build(container, setupVariables, (e) => (e.handle)); stageDescriptionInternal.m_ElementListHandle = HandleListInternal.Build(container, elements, (e) => (e.handle)); var returnTypeHandle = container.Add(stageDescriptionInternal); return new StageDescription(container, returnTypeHandle); } } } }
UnityCsReference/Modules/ShaderFoundry/ScriptBindings/StageDescription.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/ShaderFoundry/ScriptBindings/StageDescription.bindings.cs", "repo_id": "UnityCsReference", "token_count": 1927 }
428
// 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 UnityEngine; namespace UnityEditor.ShortcutManagement { class Directory : IDirectory { List<ShortcutEntry>[] m_IndexedShortcutEntries; List<ShortcutEntry> m_ShortcutEntries; public const int MaxIndexedEntries = (int)KeyCode.Mouse6 + 1; public Directory(IEnumerable<ShortcutEntry> entries) { Initialize(entries); } public void Initialize(IEnumerable<ShortcutEntry> entries) { m_ShortcutEntries = new List<ShortcutEntry>(entries.Count()); m_IndexedShortcutEntries = new List<ShortcutEntry>[MaxIndexedEntries]; foreach (ShortcutEntry entry in entries) { m_ShortcutEntries.Add(entry); if (entry.combinations.Any()) AddEntry(entry.combinations.First().keyCode, entry); // TODO: Index unbound entries? } } public void GetAllShortcuts(List<ShortcutEntry> output) { output.AddRange(m_ShortcutEntries); } private List<ShortcutEntry> GetShortcutEntriesForPrimaryKey(List<KeyCombination> combinationSequence) { if (combinationSequence == null || combinationSequence.Count < 1) return null; return m_IndexedShortcutEntries[(int)combinationSequence[0].keyCode]; } // These two overloads have some duplication to avoid creating predicates etc. public void FindShortcutEntries(List<KeyCombination> combinationSequence, Type[] context, string[] tags, List<ShortcutEntry> outputShortcuts) { outputShortcuts.Clear(); List<ShortcutEntry> entries = GetShortcutEntriesForPrimaryKey(combinationSequence); if (entries == null) return; foreach (var entry in entries) if (entry.StartsWith(combinationSequence) && ShortcutEntryMatchesAnyContext(entry.context, context) && entry.context != typeof(ContextManager.GlobalContext)) outputShortcuts.Add(entry); if (outputShortcuts.Count == 0) { foreach (var entry in entries) if (entry.StartsWith(combinationSequence) && ShortcutEntryMatchesAnyContext(entry.context, context) && entry.context == typeof(ContextManager.GlobalContext)) outputShortcuts.Add(entry); } if (tags == null) return; bool tagMatch = false; foreach (var entry in outputShortcuts) tagMatch |= tags.Contains(entry.tag); if (tagMatch) { for (int i = outputShortcuts.Count - 1; i >= 0; i--) { if (tags.Contains(outputShortcuts[i].tag)) continue; outputShortcuts.RemoveAt(i); } } else { for (int i = outputShortcuts.Count - 1; i >= 0; i--) { if (outputShortcuts[i].tag == null) continue; outputShortcuts.RemoveAt(i); } } } public void FindShortcutEntries(List<KeyCombination> combinationSequence, IContextManager contextManager, List<ShortcutEntry> outputShortcuts) { outputShortcuts.Clear(); List<ShortcutEntry> entries = GetShortcutEntriesForPrimaryKey(combinationSequence); if (entries == null) return; foreach (var entry in entries) if (entry.StartsWith(combinationSequence) && ShortcutEntrySatisfiesContextManager(contextManager, entry) && entry.context != typeof(ContextManager.GlobalContext)) outputShortcuts.Add(entry); if (outputShortcuts.Count == 0) { foreach (var entry in entries) if (entry.StartsWith(combinationSequence) && ShortcutEntrySatisfiesContextManager(contextManager, entry) && entry.context == typeof(ContextManager.GlobalContext)) outputShortcuts.Add(entry); } bool tagMatch = false; foreach (var entry in outputShortcuts) tagMatch |= contextManager.HasTag(entry.tag); if (tagMatch) { for (int i = outputShortcuts.Count - 1; i >= 0; i--) { if (contextManager.HasTag(outputShortcuts[i].tag)) continue; outputShortcuts.RemoveAt(i); } } else { for (int i = outputShortcuts.Count - 1; i >= 0; i--) { if (outputShortcuts[i].tag == null) continue; outputShortcuts.RemoveAt(i); } } } public void FindShortcutEntries(List<KeyCombination> combinationSequence, List<ShortcutEntry> outputShortcuts) { FindShortcutEntries(combinationSequence, (Type[])null, null, outputShortcuts); } public void FindPotentialShortcutEntries(IContextManager contextManager, List<ShortcutEntry> outputShortcuts) { outputShortcuts.Clear(); List<ShortcutEntry> entries = new List<ShortcutEntry>(); GetAllShortcuts(entries); if (entries == null) return; foreach (var entry in entries) if (ShortcutEntrySatisfiesContextManager(contextManager, entry) && (string.IsNullOrWhiteSpace(entry.tag) || contextManager.HasTag(entry.tag))) outputShortcuts.Add(entry); } public ShortcutEntry FindShortcutEntry(Identifier identifier) { return m_ShortcutEntries.FirstOrDefault(s => s.identifier.Equals(identifier)); } public ShortcutEntry FindShortcutEntry(string shortcutId) { var id = new Identifier(); id.path = shortcutId; return FindShortcutEntry(id); } public void FindPotentialConflicts(Type context, string tag, IList<KeyCombination> binding, IList<ShortcutEntry> output, IContextManager contextManager) { if (!binding.Any()) return; var tempCombinations = new List<KeyCombination>(binding.Count); output.Clear(); List<ShortcutEntry> entries = m_IndexedShortcutEntries[(int)binding[0].keyCode]; if (entries == null || !entries.Any()) return; foreach (var shortcutEntry in entries) { if (!contextManager.DoContextsConflict(shortcutEntry.context, context) || !string.Equals(tag, shortcutEntry.tag)) continue; bool entryConflicts = false; tempCombinations.Clear(); foreach (var keyCombination in binding) { tempCombinations.Add(keyCombination); if (shortcutEntry.FullyMatches(tempCombinations)) { entryConflicts = true; break; } } if (entryConflicts || shortcutEntry.StartsWith(tempCombinations)) output.Add(shortcutEntry); } } public void FindShortcutsWithConflicts(List<ShortcutEntry> output, IContextManager contextManager) { var conflictingEntries = new HashSet<int>(); foreach (List<ShortcutEntry> entries in m_IndexedShortcutEntries) { if (entries == null || entries.Count < 2) continue; for (int i = 0; i < entries.Count; ++i) { var firstEntryHashCode = entries[i].GetHashCode(); for (int j = i + 1; j < entries.Count; ++j) { var secondEntryHashCode = entries[j].GetHashCode(); if (DoShortcutEntriesConflict(entries[i], entries[j], contextManager)) { if (!conflictingEntries.Contains(firstEntryHashCode)) { output.Add(entries[i]); conflictingEntries.Add(firstEntryHashCode); } if (!conflictingEntries.Contains(secondEntryHashCode)) { output.Add(entries[j]); conflictingEntries.Add(secondEntryHashCode); } } } } } } void AddEntry(KeyCode keyCode, ShortcutEntry entry) { int keyCodeValue = (int)keyCode; List<ShortcutEntry> entriesForKeyCode = m_IndexedShortcutEntries[keyCodeValue]; if (entriesForKeyCode == null) m_IndexedShortcutEntries[keyCodeValue] = entriesForKeyCode = new List<ShortcutEntry>(); entriesForKeyCode.Add(entry); } bool DoShortcutEntriesConflict(ShortcutEntry shortcutEntry1, ShortcutEntry shortcutEntry2, IContextManager contextManager) { var contextConflict = contextManager.DoContextsConflict(shortcutEntry1.context, shortcutEntry2.context); if (!contextConflict) return false; var tagConflict = string.Equals(shortcutEntry1.tag, shortcutEntry2.tag); if (!tagConflict) return false; var mouseConflict = shortcutEntry1.StartsWith(shortcutEntry2.combinations, KeyCombination.k_MouseKeyCodes) || shortcutEntry2.StartsWith(shortcutEntry1.combinations, KeyCombination.k_MouseKeyCodes); var shortcutsHaveDifferentType = (shortcutEntry1.type == ShortcutType.Action && shortcutEntry2.type == ShortcutType.Clutch) || (shortcutEntry1.type == ShortcutType.Clutch && shortcutEntry2.type == ShortcutType.Action); if (shortcutsHaveDifferentType && mouseConflict) return false; var combinationsConflict = shortcutEntry1.StartsWith(shortcutEntry2.combinations) || shortcutEntry2.StartsWith(shortcutEntry1.combinations); return combinationsConflict; } ////////////////////////////// // Lambda elimination helpers ////////////////////////////// static bool ShortcutEntryMatchesAnyContext(Type shortcutEntryContext, Type[] contextList) { if (contextList == null) return true; foreach (var type in contextList) if (ShortcutEntryMatchesContext(shortcutEntryContext, type)) return true; return false; } static bool ShortcutEntryMatchesContext(Type shortcutEntryContext, Type context) { return context == shortcutEntryContext || (shortcutEntryContext != null && shortcutEntryContext.IsAssignableFrom(context)); } static bool ShortcutEntrySatisfiesContextManager(IContextManager contextManager, ShortcutEntry entry) { return contextManager.HasActiveContextOfType(entry.context) && // Emulate old play mode shortcut behavior // * Non-menu shortcuts do NOT apply only when the Game View is focused, the editor is playing, and is NOT paused // * Menu shortcuts are always active (!contextManager.playModeContextIsActive || entry.type == ShortcutType.Menu); } } }
UnityCsReference/Modules/ShortcutManagerEditor/Directory.cs/0
{ "file_path": "UnityCsReference/Modules/ShortcutManagerEditor/Directory.cs", "repo_id": "UnityCsReference", "token_count": 5775 }
429
// 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 UnityEngine; using UnityEngine.Bindings; using UnityEngine.Scripting; using Attribute = System.Attribute; using Event = UnityEngine.Event; namespace UnityEditor.ShortcutManagement { interface ILastUsedProfileIdProvider { string lastUsedProfileId { get; set; } } interface IAvailableShortcutsChangedNotifier { event Action availableShortcutsChanged; } [InitializeOnLoad] [VisibleToOtherModules("UnityEditor.UIBuilderModule")] static class ShortcutIntegration { const string k_DeleteID = "Main Menu/Edit/Delete"; const string k_IgnoreWhenPlayModeFocused = "GameView.IgnoreWhenPlayModeFocused"; class LastUsedProfileIdProvider : ILastUsedProfileIdProvider { static string lastUsedProfileIdEditorPrefKey => $"ShortcutManagement_LastUsedShortcutProfileId_{ModeService.currentId}"; public string lastUsedProfileId { get { var profileId = EditorPrefs.GetString(lastUsedProfileIdEditorPrefKey); return profileId == "" ? null : profileId; } set { EditorPrefs.SetString(lastUsedProfileIdEditorPrefKey, value ?? ""); } } } private static ShortcutController s_Instance; public static ShortcutController instance { get { EnsureShortcutControllerCreated(); return s_Instance; } } private static bool s_Enabled; internal static bool enabled { get { return s_Enabled; } set { if (value == s_Enabled) return; if (value) { EditorApplication.globalEventHandler += EventHandler; GUIUtility.beforeEventProcessed += BeforeEventProcessedHandler; } else { EditorApplication.globalEventHandler -= EventHandler; GUIUtility.beforeEventProcessed -= BeforeEventProcessedHandler; } s_Enabled = value; } } public static bool ignoreWhenPlayModeFocused { get { return s_IgnoreWhenPlayModeFocused; } set { if (s_IgnoreWhenPlayModeFocused == value) return; EditorPrefs.SetBool(k_IgnoreWhenPlayModeFocused, value); s_IgnoreWhenPlayModeFocused = value; } } internal static bool s_IgnoreWhenPlayModeFocused; [RequiredByNativeCode] static void SetShortcutIntegrationEnabled(bool enable) => enabled = enable; [RequiredByNativeCode] static bool HasModifiers(EventModifiers modifiers) => Event.current?.modifiers == modifiers; static ShortcutIntegration() { // There is cases where the ShortcutIntegration was not requested even after the project was initialized, such as running tests. EditorApplication.delayCall += EnsureShortcutsAreInitialized; } static void EnsureShortcutControllerCreated() { if (s_Instance == null) InitializeController(); Debug.Assert(s_Instance != null); } static void EnsureShortcutsAreInitialized() { EnsureShortcutControllerCreated(); // If the ShortcutController instance was created before the menus are created, // for example if accessed in an InitializeOnLoad method, // the list of shortcuts is incomplete. // This delayed call ensures that the shortcuts are always up to date when the editor becomes usable. s_Instance.RebuildShortcuts(); } static bool HasAnyEntriesHandler() { return instance.HasAnyEntries(Event.current); } static void EventHandler() { if (s_IgnoreWhenPlayModeFocused && EditorWindow.focusedWindow is GameView && Application.isPlaying) return; instance.contextManager.SetFocusedWindow(EditorWindow.focusedWindow); instance.HandleKeyEvent(Event.current); } static void BeforeEventProcessedHandler(EventType type, KeyCode keyCode) { if (s_IgnoreWhenPlayModeFocused && EditorWindow.focusedWindow is GameView && Application.isPlaying) return; instance.ResetShortcutState(type, keyCode); } static void OnInvokingAction(ShortcutEntry shortcutEntry, ShortcutArguments shortcutArguments) { // Separate shortcut actions into different undo groups Undo.IncrementCurrentGroup(); } static void OnFocusChanged(bool isFocused) { instance.trigger.ResetActiveClutches(); } static void InitializeController() { var shortcutProviders = new IDiscoveryShortcutProvider[] { new ShortcutAttributeDiscoveryProvider(), new ShortcutMenuItemDiscoveryProvider() }; var bindingValidator = new BindingValidator(); var invalidContextReporter = new DiscoveryInvalidShortcutReporter(); var discovery = new Discovery(shortcutProviders, bindingValidator, invalidContextReporter); IContextManager contextManager = new ContextManager(); s_Instance = new ShortcutController(discovery, contextManager, bindingValidator, new ShortcutProfileStore(), new LastUsedProfileIdProvider()); s_Instance.trigger.beforeShortcutInvoked += OnInvokingAction; enabled = true; ignoreWhenPlayModeFocused = EditorPrefs.GetBool(k_IgnoreWhenPlayModeFocused, false); EditorApplication.doPressedKeysTriggerAnyShortcut += HasAnyEntriesHandler; EditorApplication.focusChanged += OnFocusChanged; } } [VisibleToOtherModules("UnityEditor.UIBuilderModule")] class ShortcutController : IAvailableShortcutsChangedNotifier { const string k_MigratedProfileId = "UserProfile"; const string k_ProfileMigratedEditorPrefKey = "ShortcutManager_ProfileMigrated"; Directory m_Directory; IDiscovery m_Discovery; public IShortcutProfileManager profileManager { get; } public IDirectory directory => m_Directory; public IBindingValidator bindingValidator { get; } public Trigger trigger { get; } public IContextManager contextManager { get; } ILastUsedProfileIdProvider m_LastUsedProfileIdProvider; public event Action availableShortcutsChanged; public ShortcutController(IDiscovery discovery, IContextManager contextManager, IBindingValidator bindingValidator, IShortcutProfileStore profileStore, ILastUsedProfileIdProvider lastUsedProfileIdProvider) { m_Discovery = discovery; this.bindingValidator = bindingValidator; m_LastUsedProfileIdProvider = lastUsedProfileIdProvider; profileManager = new ShortcutProfileManager(m_Discovery.GetAllShortcuts(), bindingValidator, profileStore); profileManager.shortcutBindingChanged += OnShortcutBindingChanged; profileManager.activeProfileChanged += OnActiveProfileChanged; profileManager.ReloadProfiles(); var conflictResolverView = new ConflictResolverView(); var conflictResolver = new ConflictResolver(profileManager, contextManager, conflictResolverView); this.contextManager = contextManager; m_Directory = new Directory(profileManager.GetAllShortcuts()); trigger = new Trigger(m_Directory, conflictResolver); ActivateLastUsedProfile(); MigrateUserSpecifiedPrefKeys(); ModeService.modeChanged += HandleModeChanged; } internal void RebuildShortcuts() { profileManager.UpdateBaseProfile(m_Discovery.GetAllShortcuts()); Initialize(); } void Initialize() { m_Directory.Initialize(profileManager.GetAllShortcuts()); availableShortcutsChanged?.Invoke(); } void HandleModeChanged(ModeService.ModeChangedArgs args) { // Install profile specific to the current mode. var shortcutProfiles = ModeService.GetModeDataSection(args.nextIndex, ModeDescriptor.ShortcutsKey) as System.Collections.IList; if (shortcutProfiles == null || shortcutProfiles.Count == 0) return; string defaultMode = null; try { var shortcutProfilePath = ShortcutProfileStore.GetShortcutFolderPath(); if (!System.IO.Directory.Exists(shortcutProfilePath)) System.IO.Directory.CreateDirectory(shortcutProfilePath); for (var i = 0; i < shortcutProfiles.Count; ++i) { var srcProfilePath = shortcutProfiles[i] as string; if (String.IsNullOrEmpty(srcProfilePath) || !File.Exists(srcProfilePath)) continue; var baseName = Path.GetFileName(srcProfilePath); var dstPath = Path.Combine(shortcutProfilePath, baseName); if (!File.Exists(dstPath)) { File.Copy(srcProfilePath, dstPath); } if (i == 0) { // Assume first item is the default mode if needed. defaultMode = Path.GetFileNameWithoutExtension(srcProfilePath); } } } catch (Exception) { Debug.LogError("Error while installing new profile for mode: " + ModeService.currentId); } // Reload profiles will unset the lastUsedProfile so make a copy of it: var lastUsedProfileId = m_LastUsedProfileIdProvider.lastUsedProfileId ?? defaultMode; if (!String.IsNullOrEmpty(lastUsedProfileId)) { profileManager.ReloadProfiles(); LoadProfileById(lastUsedProfileId); } } void OnShortcutBindingChanged(IShortcutProfileManager sender, Identifier identifier, ShortcutBinding oldBinding, ShortcutBinding newBinding) { Initialize(); } void OnActiveProfileChanged(IShortcutProfileManager sender, ShortcutProfile oldActiveProfile, ShortcutProfile newActiveProfile) { m_LastUsedProfileIdProvider.lastUsedProfileId = profileManager.activeProfile?.id; Initialize(); } internal bool HasAnyEntries(Event evt) { return trigger.HasAnyEntries(); } internal void HandleKeyEvent(Event evt) { trigger.HandleKeyEvent(evt, contextManager); } internal void ResetShortcutState(EventType type, KeyCode keyCode) { trigger.ResetShortcutState(type, keyCode); } internal string GetKeyCombinationFor(string shortcutId) { var shortcutEntry = directory.FindShortcutEntry(shortcutId); if (shortcutEntry != null) { return KeyCombination.SequenceToString(shortcutEntry.combinations); } throw new System.ArgumentException(shortcutId + " is not defined.", nameof(shortcutId)); } void ActivateLastUsedProfile() { LoadProfileById(m_LastUsedProfileIdProvider.lastUsedProfileId); } void LoadProfileById(string profileId) { if (profileId == null) return; var lastUsedProfile = profileManager.GetProfileById(profileId); if (lastUsedProfile != null) profileManager.activeProfile = lastUsedProfile; } static bool TryParseUniquePrefKeyString(string prefString, out string name, out Event keyboardEvent, out string shortcut) { int i = prefString.IndexOf(";", StringComparison.Ordinal); if (i < 0) { name = null; keyboardEvent = null; shortcut = null; return false; } name = prefString.Substring(0, i); shortcut = prefString.Substring(i + 1); keyboardEvent = Event.KeyboardEvent(shortcut); return true; } void MigrateUserSpecifiedPrefKeys() { // If migration already happened then don't do anything if (EditorPrefs.GetBool(k_ProfileMigratedEditorPrefKey, false)) return; EditorPrefs.SetBool(k_ProfileMigratedEditorPrefKey, true); // Find shortcut entries that might need to be migrated var allShortcuts = new List<ShortcutEntry>(); directory.GetAllShortcuts(allShortcuts); // Find existing or create migrated profile and make it active so we can amend it var originalActiveProfile = profileManager.activeProfile; var migratedProfile = profileManager.GetProfileById(k_MigratedProfileId); var migratedProfileAlreadyExisted = migratedProfile != null; if (!migratedProfileAlreadyExisted) migratedProfile = profileManager.CreateProfile(k_MigratedProfileId); profileManager.activeProfile = migratedProfile; var migratedProfileModified = false; var tempKeyCombinations = new KeyCombination[1]; var methodsWithFormerlyPrefKeyAs = EditorAssemblies.GetAllMethodsWithAttribute<FormerlyPrefKeyAsAttribute>(); foreach (var method in methodsWithFormerlyPrefKeyAs) { ShortcutEntry entry = null; // if there are multiple shortcut attributes available, pick the first one that is not overridden foreach (var attr in Attribute.GetCustomAttributes(method, typeof(ShortcutAttribute), true)) { if (!(attr is ShortcutAttribute shortcutAttr)) continue; var e = allShortcuts.Find(e => string.Equals(e.identifier.path, shortcutAttr.identifier)); if (e == null || e.overridden) continue; entry = e; break; } if (entry == null) continue; // Parse default pref key value from FormerlyPrefKeyAs attribute var prefKeyAttr = (FormerlyPrefKeyAsAttribute)Attribute.GetCustomAttribute(method, typeof(FormerlyPrefKeyAsAttribute)); var editorPrefDefaultValue = $"{prefKeyAttr.name};{prefKeyAttr.defaultValue}"; string name; Event keyboardEvent; string shortcut; if (!TryParseUniquePrefKeyString(editorPrefDefaultValue, out name, out keyboardEvent, out shortcut)) continue; var prefKeyDefaultKeyCombination = KeyCombination.FromPrefKeyKeyboardEvent(keyboardEvent); // Parse current pref key value (falling back on default pref key value) if (!TryParseUniquePrefKeyString(EditorPrefs.GetString(prefKeyAttr.name, editorPrefDefaultValue), out name, out keyboardEvent, out shortcut)) continue; var prefKeyCurrentKeyCombination = KeyCombination.FromPrefKeyKeyboardEvent(keyboardEvent); // Only migrate pref keys that the user actually overwrote if (prefKeyCurrentKeyCombination.Equals(prefKeyDefaultKeyCombination)) continue; string invalidBindingMessage; tempKeyCombinations[0] = prefKeyCurrentKeyCombination; if (!bindingValidator.IsCombinationValid(tempKeyCombinations, out invalidBindingMessage)) { Debug.LogWarning($"Could not migrate existing binding for shortcut \"{entry.identifier.path}\" with invalid binding.\n{invalidBindingMessage}."); continue; } profileManager.ModifyShortcutEntry(entry.identifier, new List<KeyCombination> { prefKeyCurrentKeyCombination }); migratedProfileModified = true; } // Delete migrated profile if it was created and not modified if (!migratedProfileAlreadyExisted && !migratedProfileModified) profileManager.DeleteProfile(migratedProfile); // Restore original active profile unless last loaded profile was null and the migrated profile was created if (originalActiveProfile != null || migratedProfileAlreadyExisted) profileManager.activeProfile = originalActiveProfile; } } }
UnityCsReference/Modules/ShortcutManagerEditor/ShortcutController.cs/0
{ "file_path": "UnityCsReference/Modules/ShortcutManagerEditor/ShortcutController.cs", "repo_id": "UnityCsReference", "token_count": 7552 }
430
// 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; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.U2D { [StructLayoutAttribute(LayoutKind.Sequential)] [MovedFrom("UnityEngine.Experimental.U2D")] public struct SpriteShapeMetaData { public float height; public float bevelCutoff; public float bevelSize; public uint spriteIndex; public bool corner; } [StructLayoutAttribute(LayoutKind.Sequential)] [MovedFrom("UnityEngine.Experimental.U2D")] public struct ShapeControlPoint { public Vector3 position; public Vector3 leftTangent; public Vector3 rightTangent; public int mode; } [StructLayoutAttribute(LayoutKind.Sequential)] [MovedFrom("UnityEngine.Experimental.U2D")] public struct AngleRangeInfo { public float start; public float end; public uint order; public int[] sprites; } [NativeHeader("Modules/SpriteShape/Public/SpriteShapeUtility.h")] [MovedFrom("UnityEngine.Experimental.U2D")] public class SpriteShapeUtility { [NativeThrows] [FreeFunction("SpriteShapeUtility::Generate")] extern public static int[] Generate(Mesh mesh, SpriteShapeParameters shapeParams, ShapeControlPoint[] points, SpriteShapeMetaData[] metaData, AngleRangeInfo[] angleRange, Sprite[] sprites, Sprite[] corners); [NativeThrows] [FreeFunction("SpriteShapeUtility::GenerateSpriteShape")] extern public static void GenerateSpriteShape(SpriteShapeRenderer renderer, SpriteShapeParameters shapeParams, ShapeControlPoint[] points, SpriteShapeMetaData[] metaData, AngleRangeInfo[] angleRange, Sprite[] sprites, Sprite[] corners); } }
UnityCsReference/Modules/SpriteShape/Public/ScriptBindings/SpriteShapeUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/SpriteShape/Public/ScriptBindings/SpriteShapeUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 681 }
431
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License // SUBSTANCE HOOK using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Collections; namespace UnityEngine { public partial class ProceduralMaterial : Material { static void FeatureRemoved() { throw new Exception("Built-in support for Substance Designer materials has been removed from Unity. To continue using Substance Designer materials, you will need to install Allegorithmic's external importer from the Asset Store."); } //static extern void BindingsGeneratorTrigger(); } } // namespace UnityEngine
UnityCsReference/Modules/Substance/SubstanceUtility.bindings.cs/0
{ "file_path": "UnityCsReference/Modules/Substance/SubstanceUtility.bindings.cs", "repo_id": "UnityCsReference", "token_count": 227 }
432
// 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.SubsystemsImplementation; namespace UnityEngine { public static partial class SubsystemManager { static SubsystemManager() => StaticConstructScriptingClassMap(); public static void GetAllSubsystemDescriptors(List<ISubsystemDescriptor> descriptors) { SubsystemDescriptorStore.GetAllSubsystemDescriptors(descriptors); } public static void GetSubsystemDescriptors<T>(List<T> descriptors) where T : ISubsystemDescriptor { SubsystemDescriptorStore.GetSubsystemDescriptors(descriptors); } public static void GetSubsystems<T>(List<T> subsystems) where T : ISubsystem { subsystems.Clear(); AddSubsystemSubset(s_IntegratedSubsystems, subsystems); AddSubsystemSubset(s_StandaloneSubsystems, subsystems); AddSubsystemSubset(s_DeprecatedSubsystems, subsystems); } static void AddSubsystemSubset<TBaseTypeInList, TQueryType>(List<TBaseTypeInList> copyFrom, List<TQueryType> copyTo) where TQueryType : ISubsystem where TBaseTypeInList : ISubsystem { foreach (var subsystem in copyFrom) { if (subsystem is TQueryType concreteSubsystem) copyTo.Add(concreteSubsystem); } } // event never invoked warning (invoked indirectly from native code) #pragma warning disable CS0067 public static event Action beforeReloadSubsystems; public static event Action afterReloadSubsystems; #pragma warning restore CS0067 [VisibleToOtherModules("UnityEngine.XRModule")] internal static IntegratedSubsystem GetIntegratedSubsystemByPtr(IntPtr ptr) { foreach (var subsystem in s_IntegratedSubsystems) { if (subsystem.m_Ptr == ptr) return subsystem; } return null; } internal static void RemoveIntegratedSubsystemByPtr(IntPtr ptr) { for (int finderIndex = 0; finderIndex < s_IntegratedSubsystems.Count; ++finderIndex) { if (s_IntegratedSubsystems[finderIndex].m_Ptr != ptr) continue; s_IntegratedSubsystems[finderIndex].m_Ptr = IntPtr.Zero; s_IntegratedSubsystems.RemoveAt(finderIndex); break; } } internal static void AddStandaloneSubsystem(SubsystemWithProvider subsystem) { s_StandaloneSubsystems.Add(subsystem); } internal static bool RemoveStandaloneSubsystem(SubsystemWithProvider subsystem) { return s_StandaloneSubsystems.Remove(subsystem); } internal static SubsystemWithProvider FindStandaloneSubsystemByDescriptor(SubsystemDescriptorWithProvider descriptor) { foreach (var subsystem in s_StandaloneSubsystems) { if (subsystem.descriptor == descriptor) return subsystem; } return null; } static List<IntegratedSubsystem> s_IntegratedSubsystems = new List<IntegratedSubsystem>(); static List<SubsystemWithProvider> s_StandaloneSubsystems = new List<SubsystemWithProvider>(); #pragma warning disable CS0618 static List<Subsystem> s_DeprecatedSubsystems = new List<Subsystem>(); #pragma warning restore CS0618 } }
UnityCsReference/Modules/Subsystems/SubsystemManager.cs/0
{ "file_path": "UnityCsReference/Modules/Subsystems/SubsystemManager.cs", "repo_id": "UnityCsReference", "token_count": 1609 }
433
// 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 UnityEditor; using UnityEngine; using UnityEngine.TerrainTools; namespace UnityEditor.TerrainTools { internal class PaintTreesUtils { public static bool ValidateTreePrototype(Terrain terrain, int treePrototype) { int prototypeCount = TerrainInspectorUtil.GetPrototypeCount(terrain.terrainData); if (treePrototype == PaintTreesTool.kInvalidTree || treePrototype >= prototypeCount) return false; if (!TerrainInspectorUtil.PrototypeIsRenderable(terrain.terrainData, treePrototype)) return false; return true; } public static int FindTreePrototype(Terrain terrain, Terrain sourceTerrain, int sourceTree) { if (sourceTree == PaintTreesTool.kInvalidTree || sourceTree >= sourceTerrain.terrainData.treePrototypes.Length) { return PaintTreesTool.kInvalidTree; } if (terrain == sourceTerrain) { return sourceTree; } TreePrototype sourceTreePrototype = sourceTerrain.terrainData.treePrototypes[sourceTree]; for (int i = 0; i < terrain.terrainData.treePrototypes.Length; ++i) { if (sourceTreePrototype.Equals(terrain.terrainData.treePrototypes[i])) return i; } return PaintTreesTool.kInvalidTree; } public static int CopyTreePrototype(Terrain terrain, Terrain sourceTerrain, int sourceTree) { TreePrototype sourceTreePrototype = sourceTerrain.terrainData.treePrototypes[sourceTree]; TreePrototype[] newTreePrototypesArray = new TreePrototype[terrain.terrainData.treePrototypes.Length + 1]; System.Array.Copy(terrain.terrainData.treePrototypes, newTreePrototypesArray, terrain.terrainData.treePrototypes.Length); newTreePrototypesArray[newTreePrototypesArray.Length - 1] = new TreePrototype(sourceTreePrototype); terrain.terrainData.treePrototypes = newTreePrototypesArray; return newTreePrototypesArray.Length - 1; } public static void PlaceTree(Terrain terrain, int treePrototype, Vector3 position, Color color, float height, float width, float rotation) { TreeInstance instance = new TreeInstance(); instance.position = position; instance.color = color; instance.lightmapColor = Color.white; instance.prototypeIndex = treePrototype; instance.heightScale = height; instance.widthScale = width; instance.rotation = rotation; terrain.AddTreeInstance(instance); } } internal class PaintTreesTool : TerrainPaintToolWithOverlays<PaintTreesTool> { internal const string k_ToolName = "Paint Trees"; public override string OnIcon => "TerrainOverlays/PaintTrees_On.png"; public override string OffIcon => "TerrainOverlays/PaintTrees.png"; public const int kInvalidTree = -1; static class Styles { // Trees public static readonly GUIContent trees = EditorGUIUtility.TrTextContent("Trees"); public static readonly GUIContent editTrees = EditorGUIUtility.TrTextContent("Edit Trees...", "Add/remove tree types."); public static readonly GUIContent treeDensity = EditorGUIUtility.TrTextContent("Tree Density", "How dense trees are you painting"); public static readonly GUIContent treeHeight = EditorGUIUtility.TrTextContent("Tree Height", "The height scale of the planted trees"); public static readonly GUIContent treeHeightRandomLabel = EditorGUIUtility.TrTextContent("Random?", "Enable random variation in tree height (variation)"); public static readonly GUIContent treeHeightRandomToggle = EditorGUIUtility.TrTextContent("", "Enable random variation in tree height (variation)"); public static readonly GUIContent lockWidthToHeight = EditorGUIUtility.TrTextContent("Lock Width to Height", "Let the tree width scale be equal to the tree height scale"); public static readonly GUIContent treeWidth = EditorGUIUtility.TrTextContent("Tree Width", "The width scale of the planted trees"); public static readonly GUIContent treeWidthRandomLabel = EditorGUIUtility.TrTextContent("Random?", "Enable random variation in tree width (variation)"); public static readonly GUIContent treeWidthRandomToggle = EditorGUIUtility.TrTextContent("", "Enable random variation in tree width (variation)"); public static readonly GUIContent treeColorVar = EditorGUIUtility.TrTextContent("Color Variation", "Amount of random shading applied to trees. This only works if the shader supports _TreeInstanceColor (for example, Speedtree shaders do not use this)"); public static readonly GUIContent treeRotation = EditorGUIUtility.TrTextContent("Random Tree Rotation", "Randomize tree rotation. This only works when the tree has an LOD group."); public static readonly GUIContent treeRotationDisabled = EditorGUIUtility.TrTextContent("The selected tree does not have an LOD group, so it will use the default impostor system and will not support rotation."); public static readonly GUIContent treeHasChildRenderers = EditorGUIUtility.TrTextContent("The selected tree does not have an LOD group, but has a hierarchy of MeshRenderers, only MeshRenderer on root GameObject in the trees hierarchy will be used. Use a tree with LOD group if you want a tree with hierarchy of MeshRenderers."); public static readonly GUIContent massPlaceTrees = EditorGUIUtility.TrTextContent("Mass Place Trees", "The Mass Place Trees button is a very useful way to create an overall covering of trees without painting over the whole landscape. Following a mass placement, you can still use painting to add or remove trees to create denser or sparser areas."); public static readonly GUIContent treeContributeGI = EditorGUIUtility.TrTextContent("Tree Contribute Global Illumination", "The state of the Contribute GI flag for the tree prefab root GameObject. The flag can be changed on the prefab. When disabled, this tree will not be visible to the lightmapper. When enabled, any child GameObjects which also have the static flag enabled, will be present in lightmap calculations. Regardless of the value of the flag, each tree instance receives its own light probe and no lightmap texels."); public static readonly GUIContent noTreesDefined = EditorGUIUtility.TrTextContent("No trees defined."); } private TreePrototype m_LastSelectedTreePrototype; private Terrain m_TargetTerrain; GUIContent[] m_TreeContents = null; public float brushSize { get; set; } = 40; public float spacing { get; set; } = .8f; public bool lockWidthToHeight { get; set; } = true; public bool randomRotation { get; set; } = true; public bool allowHeightVar { get; set; } = true; public bool allowWidthVar { get; set; } = true; public float treeColorAdjustment { get; set; } = .4f; public float treeHeight { get; set; } = 1; public float treeHeightVariation { get; set; } = .1f; public float treeWidth { get; set; } = 1; public float treeWidthVariation { get; set; } = .1f; public int selectedTree { get; set; } = kInvalidTree; private Color GetTreeColor() { Color c = Color.white * Random.Range(1.0F, 1.0F - treeColorAdjustment); c.a = 1; return c; } private float GetTreeHeight() { float v = allowHeightVar ? treeHeightVariation : 0.0f; return treeHeight * Random.Range(1.0F - v, 1.0F + v); } private float GetRandomizedTreeWidth() { float v = allowWidthVar ? treeWidthVariation : 0.0f; return treeWidth * Random.Range(1.0F - v, 1.0F + v); } private float GetTreeWidth(float height) { float width; if (lockWidthToHeight) { // keep scales equal since these scales are applied to the // prefab scale to get the final tree instance scale width = height; } else { width = GetRandomizedTreeWidth(); } return width; } private float GetTreeRotation() { return randomRotation ? Random.Range(0, 2 * Mathf.PI) : 0; } private void PlaceTrees(Terrain terrain, IOnPaint editContext) { if (m_TargetTerrain == null || selectedTree == kInvalidTree || selectedTree >= m_TargetTerrain.terrainData.treePrototypes.Length) { return; } PaintTreesDetailsContext ctx = PaintTreesDetailsContext.Create(terrain, editContext.uv); int placedTreeCount = 0; int treePrototype = PaintTreesUtils.FindTreePrototype(terrain, m_TargetTerrain, selectedTree); if (treePrototype == kInvalidTree) { treePrototype = PaintTreesUtils.CopyTreePrototype(terrain, m_TargetTerrain, selectedTree); } if (PaintTreesUtils.ValidateTreePrototype(terrain, treePrototype)) { // When painting single tree // And just clicking we always place it, so you can do overlapping trees Vector3 position = new Vector3(editContext.uv.x, 0, editContext.uv.y); bool checkTreeDistance = Event.current.type == EventType.MouseDrag || brushSize > 1; if (!checkTreeDistance || TerrainInspectorUtil.CheckTreeDistance(terrain.terrainData, position, treePrototype, spacing)) { TerrainPaintUtilityEditor.UpdateTerrainDataUndo(terrain.terrainData, "Terrain - Place Trees"); var instanceHeight = GetTreeHeight(); PaintTreesUtils.PlaceTree(terrain, treePrototype, position, GetTreeColor(), instanceHeight, GetTreeWidth(instanceHeight), GetTreeRotation()); ++placedTreeCount; } } for (int i = 0; i < ctx.neighborTerrains.Length; ++i) { Terrain ctxTerrain = ctx.neighborTerrains[i]; if (ctxTerrain != null) { Vector2 ctxUV = ctx.neighborUvs[i]; treePrototype = PaintTreesUtils.FindTreePrototype(ctxTerrain, m_TargetTerrain, selectedTree); if (treePrototype == kInvalidTree) { treePrototype = PaintTreesUtils.CopyTreePrototype(ctxTerrain, m_TargetTerrain, selectedTree); } if (PaintTreesUtils.ValidateTreePrototype(ctxTerrain, treePrototype)) { Vector3 size = TerrainInspectorUtil.GetPrototypeExtent(ctxTerrain.terrainData, treePrototype); size.y = 0; float treeCountOneAxis = brushSize / (size.magnitude * spacing * .5f); int treeCount = (int)((treeCountOneAxis * treeCountOneAxis) * .5f); treeCount = Mathf.Clamp(treeCount, 0, 100); // Plant a bunch of trees for (int j = ctxTerrain == terrain ? 1 : 0; j < treeCount && placedTreeCount < treeCount; ++j) { Vector2 randomOffset = 0.5f * Random.insideUnitCircle; randomOffset.x *= brushSize / ctxTerrain.terrainData.size.x; randomOffset.y *= brushSize / ctxTerrain.terrainData.size.z; Vector3 position = new Vector3(ctxUV.x + randomOffset.x, 0, ctxUV.y + randomOffset.y); if (position.x >= 0 && position.x <= 1 && position.z >= 0 && position.z <= 1 && TerrainInspectorUtil.CheckTreeDistance(ctxTerrain.terrainData, position, treePrototype, spacing * .5f)) { TerrainPaintUtilityEditor.UpdateTerrainDataUndo(ctxTerrain.terrainData, "Terrain - Place Trees"); var instanceHeight = GetTreeHeight(); PaintTreesUtils.PlaceTree(ctxTerrain, treePrototype, position, GetTreeColor(), instanceHeight, GetTreeWidth(instanceHeight), GetTreeRotation()); ++placedTreeCount; } } } } } } private void RemoveTrees(Terrain terrain, IOnPaint editContext, bool clearSelectedOnly) { PaintTreesDetailsContext ctx = PaintTreesDetailsContext.Create(terrain, editContext.uv); for (int i = 0; i < ctx.neighborTerrains.Length; ++i) { Terrain ctxTerrain = ctx.neighborTerrains[i]; if (ctxTerrain != null) { Vector2 ctxUV = ctx.neighborUvs[i]; float radius = 0.5f * brushSize / ctxTerrain.terrainData.size.x; int treePrototype = kInvalidTree; if (clearSelectedOnly && selectedTree != kInvalidTree) { treePrototype = PaintTreesUtils.FindTreePrototype(ctxTerrain, m_TargetTerrain, selectedTree); } if (!clearSelectedOnly || treePrototype != kInvalidTree) { TerrainPaintUtilityEditor.UpdateTerrainDataUndo(ctxTerrain.terrainData, "Terrain - Remove Trees"); ctxTerrain.RemoveTrees(ctxUV, radius, treePrototype); } } } } public void MassPlaceTrees(TerrainData terrainData, int numberOfTrees, bool randomTreeColor, bool keepExistingTrees) { int nbPrototypes = terrainData.treePrototypes.Length; if (nbPrototypes == 0) { Debug.Log("Can't place trees because no prototypes are defined"); return; } Undo.RegisterCompleteObjectUndo(terrainData, "Mass Place Trees"); TreeInstance[] instances = new TreeInstance[numberOfTrees]; int i = 0; while (i < instances.Length) { TreeInstance instance = new TreeInstance(); instance.position = new Vector3(Random.value, 0, Random.value); if (terrainData.GetSteepness(instance.position.x, instance.position.z) < 30) { instance.color = randomTreeColor ? GetTreeColor() : Color.white; instance.lightmapColor = Color.white; instance.prototypeIndex = Random.Range(0, nbPrototypes); instance.heightScale = GetTreeHeight(); instance.widthScale = GetTreeWidth(instance.heightScale); instance.rotation = GetTreeRotation(); instances[i++] = instance; } } if (keepExistingTrees) { var existingTrees = terrainData.treeInstances; var allTrees = new TreeInstance[existingTrees.Length + instances.Length]; System.Array.Copy(existingTrees, 0, allTrees, 0, existingTrees.Length); System.Array.Copy(instances, 0, allTrees, existingTrees.Length, instances.Length); instances = allTrees; } terrainData.SetTreeInstances(instances, true); } public override bool OnPaint(Terrain terrain, IOnPaint editContext) { if (!Event.current.shift && !Event.current.control) { if (selectedTree != PaintTreesTool.kInvalidTree) { PlaceTrees(terrain, editContext); } } else { RemoveTrees(terrain, editContext, Event.current.control); } return false; } public override void OnEnterToolMode() { Terrain terrain = null; if (Selection.activeGameObject != null) { terrain = Selection.activeGameObject.GetComponent<Terrain>(); } if (terrain != null && terrain.terrainData != null && m_LastSelectedTreePrototype != null) { for (int i = 0; i < terrain.terrainData.treePrototypes.Length; ++i) { if (m_LastSelectedTreePrototype.Equals(terrain.terrainData.treePrototypes[i])) { selectedTree = i; break; } } } m_TargetTerrain = terrain; m_LastSelectedTreePrototype = null; } public override void OnExitToolMode() { if (m_TargetTerrain != null && m_TargetTerrain.terrainData != null && selectedTree != kInvalidTree && selectedTree < m_TargetTerrain.terrainData.treePrototypes.Length) { m_LastSelectedTreePrototype = new TreePrototype(m_TargetTerrain.terrainData.treePrototypes[selectedTree]); } selectedTree = kInvalidTree; } public override int IconIndex { get { return (int) FoliageIndex.PaintTrees; } } public override TerrainCategory Category { get { return TerrainCategory.Foliage; } } public override string GetName() { return k_ToolName; } public override string GetDescription() { return "Click to paint trees.\n\nHold shift and click to erase trees.\n\nHold Ctrl and click to erase only trees of the selected type."; } public override bool HasToolSettings => true; public override void OnRenderBrushPreview(Terrain terrain, IOnSceneGUI editContext) { // We're only doing painting operations, early out if it's not a repaint if (Event.current.type != EventType.Repaint) return; if (editContext.hitValidTerrain) { BrushTransform brushXform = TerrainPaintUtility.CalculateBrushTransform(terrain, editContext.raycastHit.textureCoord, brushSize, 0.0f); PaintContext ctx = TerrainPaintUtility.BeginPaintHeightmap(terrain, brushXform.GetBrushXYBounds(), 1); TerrainPaintUtilityEditor.DrawBrushPreview(ctx, TerrainBrushPreviewMode.SourceRenderTexture, editContext.brushTexture, brushXform, TerrainPaintUtilityEditor.GetDefaultBrushPreviewMaterial(), 0); TerrainPaintUtility.ReleaseContextResources(ctx); } } void LoadTreeIcons(Terrain terrain) { // Locate the proto types asset preview textures TreePrototype[] trees = terrain.terrainData.treePrototypes; m_TreeContents = new GUIContent[trees.Length]; for (int i = 0; i < m_TreeContents.Length; i++) { m_TreeContents[i] = new GUIContent(); Texture tex = AssetPreview.GetAssetPreview(trees[i].prefab); m_TreeContents[i].image = tex != null ? tex : null; m_TreeContents[i].text = m_TreeContents[i].tooltip = trees[i].prefab != null ? trees[i].prefab.name : "Missing"; } } void ShowUpgradeTreePrototypeScaleUI(Terrain terrain) { if (terrain.terrainData != null && terrain.terrainData.NeedUpgradeScaledTreePrototypes()) { var msgContent = EditorGUIUtility.TempContent( "Some of your prototypes have scaling values on the prefab. Since Unity 5.2 these scalings will be applied to terrain tree instances. Do you want to upgrade to this behaviour?", EditorGUIUtility.GetHelpIcon(MessageType.Warning)); GUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(msgContent, EditorStyles.wordWrappedLabel); GUILayout.Space(3); if (GUILayout.Button("Upgrade", GUILayout.ExpandWidth(false))) { terrain.terrainData.UpgradeScaledTreePrototype(); TerrainMenus.RefreshPrototypes(); } GUILayout.Space(3); GUILayout.EndVertical(); } } public override void OnToolSettingsGUI(Terrain terrain, IOnInspectorGUI editContext) { LoadTreeIcons(terrain); // Tree picker GUI.changed = false; ShowUpgradeTreePrototypeScaleUI(terrain); GUILayout.Label(Styles.trees, EditorStyles.boldLabel); selectedTree = TerrainInspector.AspectSelectionGridImageAndText(selectedTree, m_TreeContents, 64, Styles.noTreesDefined, out var doubleClick); if (selectedTree >= m_TreeContents.Length) selectedTree = PaintTreesTool.kInvalidTree; if (doubleClick) { TerrainTreeContextMenus.EditTree(new MenuCommand(terrain, selectedTree)); GUIUtility.ExitGUI(); } GUILayout.BeginHorizontal(); using (new EditorGUI.DisabledScope(selectedTree == PaintTreesTool.kInvalidTree)) { if (GUILayout.Button(Styles.massPlaceTrees)) { TerrainMenus.MassPlaceTrees(); } } GUILayout.FlexibleSpace(); TerrainInspector.MenuButton(Styles.editTrees, "CONTEXT/TerrainEngineTrees", terrain, selectedTree); TerrainInspector.ShowRefreshPrototypes(); GUILayout.EndHorizontal(); GUILayout.Label(TerrainInspector.styles.settings, EditorStyles.boldLabel); // Placement distance brushSize = TerrainInspectorUtility.PowerSlider(TerrainInspector.styles.brushSize, brushSize, 1, Mathf.Min(terrain.terrainData.size.x, terrain.terrainData.size.z), 4.0f); float oldDens = (3.3f - spacing) / 3f; float newDens = TerrainInspectorUtility.ScaledSliderWithRounding(Styles.treeDensity, oldDens, 0.1f, 1.0f, 100.0f, 1.0f); // Only set spacing when value actually changes. Otherwise // it will lose precision because we're constantly doing math // back and forth with it. if (newDens != oldDens) spacing = (1.1f - newDens) * 3f; GUILayout.Space(5); GUILayout.BeginHorizontal(); GUILayout.Label(Styles.treeHeight, GUILayout.Width(EditorGUIUtility.labelWidth - 6)); GUILayout.Label(Styles.treeHeightRandomLabel, GUILayout.ExpandWidth(false)); allowHeightVar = GUILayout.Toggle(allowHeightVar, Styles.treeHeightRandomToggle, GUILayout.ExpandWidth(false)); if (allowHeightVar) { EditorGUI.BeginChangeCheck(); float min = treeHeight * (1.0f - treeHeightVariation); float max = treeHeight * (1.0f + treeHeightVariation); EditorGUILayout.MinMaxSlider(ref min, ref max, 0.01f, 2.0f); if (EditorGUI.EndChangeCheck()) { treeHeight = (min + max) * 0.5f; treeHeightVariation = (max - min) / (min + max); } } else { treeHeight = EditorGUILayout.Slider(treeHeight, 0.01f, 2.0f); treeHeightVariation = 0.0f; } GUILayout.EndHorizontal(); GUILayout.Space(5); lockWidthToHeight = EditorGUILayout.Toggle(Styles.lockWidthToHeight, lockWidthToHeight); GUILayout.Space(5); using (new EditorGUI.DisabledScope(lockWidthToHeight)) { GUILayout.BeginHorizontal(); GUILayout.Label(Styles.treeWidth, GUILayout.Width(EditorGUIUtility.labelWidth - 6)); GUILayout.Label(Styles.treeWidthRandomLabel, GUILayout.ExpandWidth(false)); allowWidthVar = GUILayout.Toggle(allowWidthVar, Styles.treeWidthRandomToggle, GUILayout.ExpandWidth(false)); if (allowWidthVar) { EditorGUI.BeginChangeCheck(); float min = treeWidth * (1.0f - treeWidthVariation); float max = treeWidth * (1.0f + treeWidthVariation); EditorGUILayout.MinMaxSlider(ref min, ref max, 0.01f, 2.0f); if (EditorGUI.EndChangeCheck()) { treeWidth = (min + max) * 0.5f; treeWidthVariation = (max - min) / (min + max); } } else { treeWidth = EditorGUILayout.Slider(treeWidth, 0.01f, 2.0f); treeWidthVariation = 0.0f; } GUILayout.EndHorizontal(); } if (selectedTree == PaintTreesTool.kInvalidTree) return; GUILayout.Space(5); GameObject prefab = terrain.terrainData.treePrototypes[selectedTree].m_Prefab; string treePrototypeWarning; terrain.terrainData.treePrototypes[selectedTree].Validate(out treePrototypeWarning); bool isLodTreePrototype = TerrainEditorUtility.IsLODTreePrototype(prefab); using (new EditorGUI.DisabledScope(!isLodTreePrototype)) { randomRotation = EditorGUILayout.Toggle(Styles.treeRotation, randomRotation); } if (!isLodTreePrototype) { EditorGUILayout.HelpBox(Styles.treeRotationDisabled.text, MessageType.Info); } if (!string.IsNullOrEmpty(treePrototypeWarning)) { EditorGUILayout.HelpBox(treePrototypeWarning, MessageType.Warning); } // TODO: we should check if the shaders assigned to this 'tree' support _TreeInstanceColor or not.. complicated check though treeColorAdjustment = EditorGUILayout.Slider(Styles.treeColorVar, treeColorAdjustment, 0, 1); if (prefab != null) { StaticEditorFlags staticEditorFlags = GameObjectUtility.GetStaticEditorFlags(prefab); bool contributeGI = (staticEditorFlags & StaticEditorFlags.ContributeGI) != 0; using (new EditorGUI.DisabledScope(true)) // Always disabled, because we don't want to edit the prefab. contributeGI = EditorGUILayout.Toggle(Styles.treeContributeGI, contributeGI); } } public override void OnInspectorGUI(Terrain terrain, IOnInspectorGUI editContext) { OnToolSettingsGUI(terrain, editContext); } } }
UnityCsReference/Modules/TerrainEditor/PaintTools/PaintTreesTool.cs/0
{ "file_path": "UnityCsReference/Modules/TerrainEditor/PaintTools/PaintTreesTool.cs", "repo_id": "UnityCsReference", "token_count": 12717 }
434
// 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 UnityEngine.Scripting; using UnityEngine.TextCore.LowLevel; namespace UnityEngine.TextCore { /// <summary> /// A structure that contains information about a given typeface and for a specific point size. /// </summary> [Serializable] [UsedByNativeCode] [StructLayout(LayoutKind.Sequential)] public struct FaceInfo { /// <summary> /// The index of the font face and style to be loaded from the font file. /// </summary> [VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")] internal int faceIndex { get { return m_FaceIndex; } set { m_FaceIndex = value; } } /// <summary> /// The name of the font typeface also known as family name. /// </summary> public string familyName { get { return m_FamilyName; } set { m_FamilyName = value; } } /// <summary> /// The style name of the typeface which defines both the visual style and weight of the typeface. /// </summary> public string styleName { get { return m_StyleName; } set { m_StyleName = value; } } /// <summary> /// The point size used for sampling the typeface. This is also referenced as sampling point size. /// </summary> public int pointSize { get { return m_PointSize; } set { m_PointSize = value; } } /// <summary> /// The relative scale of the typeface. /// Default value is 1.0f. /// </summary> public float scale { get { return m_Scale; } set { m_Scale = value; } } /// <summary> /// The units per EM for the font face. /// </summary> [VisibleToOtherModules("UnityEngine.TextCoreTextEngineModule")] internal int unitsPerEM { get { return m_UnitsPerEM; } set { m_UnitsPerEM = value; } } // Key metrics for the typeface /// <summary> /// The line height represents the distance between consecutive lines of text. /// This is the distance from baseline to baseline. It is usually computed as line height = ascent - descent + line gap. /// </summary> public float lineHeight { get { return m_LineHeight; } set { m_LineHeight = value; } } /// <summary> /// The Ascent line is typically located at the top of the tallest glyph in the typeface. This represents the distance between the baseline and the tallest ascender. This value is usually positive. /// </summary> public float ascentLine { get { return m_AscentLine; } set { m_AscentLine = value; } } /// <summary> /// The Cap line is typically located at the top of capital letters. This value represents the distance between the baseline and the top of capital letters. /// </summary> public float capLine { get { return m_CapLine; } set { m_CapLine = value; } } /// <summary> /// The Mean line is typically located at the top of lowercase letters. This value represents the distance between the baseline and the top of lowercase letters. /// </summary> public float meanLine { get { return m_MeanLine; } set { m_MeanLine = value; } } /// <summary> /// The Baseline is an imaginary line upon which all glyphs appear to rest on. This value is typically zero. /// </summary> public float baseline { get { return m_Baseline; } set { m_Baseline = value; } } /// <summary> /// The Descent line is typically located at the bottom of the glyph with the lowest descender in the typeface. This represents the distance between the baseline and the lowest descender. This value is usually negative. /// </summary> public float descentLine { get { return m_DescentLine; } set { m_DescentLine = value; } } /// <summary> /// The position of characters using superscript. /// </summary> public float superscriptOffset { get { return m_SuperscriptOffset; } set { m_SuperscriptOffset = value; } } /// <summary> /// The relative size / scale of superscript characters. /// </summary> public float superscriptSize { get { return m_SuperscriptSize; } set { m_SuperscriptSize = value; } } /// <summary> /// The position of characters using subscript. /// </summary> public float subscriptOffset { get { return m_SubscriptOffset; } set { m_SubscriptOffset = value; } } /// <summary> /// The relative size / scale of subscript characters. /// </summary> public float subscriptSize { get { return m_SubscriptSize; } set { m_SubscriptSize = value; } } /// <summary> /// The position of the underline. /// </summary> public float underlineOffset { get { return m_UnderlineOffset; } set { m_UnderlineOffset = value; } } /// <summary> /// The thickness of the underline. /// </summary> public float underlineThickness { get { return m_UnderlineThickness; } set { m_UnderlineThickness = value; } } /// <summary> /// The position of the strikethrough. /// </summary> public float strikethroughOffset { get { return m_StrikethroughOffset; } set { m_StrikethroughOffset = value; } } /// <summary> /// The thickness of the strikethrough. /// </summary> public float strikethroughThickness { get { return m_StrikethroughThickness; } set { m_StrikethroughThickness = value; } } /// <summary> /// The width of the tab character. This width is typically the same as the space character. /// </summary> public float tabWidth { get { return m_TabWidth; } set { m_TabWidth = value; } } // ============================================= // Private backing fields for public properties. // ============================================= [SerializeField] [NativeName("faceIndex")] private int m_FaceIndex; [SerializeField] [NativeName("familyName")] private string m_FamilyName; [SerializeField] [NativeName("styleName")] private string m_StyleName; [SerializeField] [NativeName("pointSize")] private int m_PointSize; [SerializeField] [NativeName("scale")] private float m_Scale; [SerializeField] [NativeName("unitsPerEM")] private int m_UnitsPerEM; [SerializeField] [NativeName("lineHeight")] private float m_LineHeight; [SerializeField] [NativeName("ascentLine")] private float m_AscentLine; [SerializeField] [NativeName("capLine")] private float m_CapLine; [SerializeField] [NativeName("meanLine")] private float m_MeanLine; [SerializeField] [NativeName("baseline")] private float m_Baseline; [SerializeField] [NativeName("descentLine")] private float m_DescentLine; [SerializeField] [NativeName("superscriptOffset")] private float m_SuperscriptOffset; [SerializeField] [NativeName("superscriptSize")] private float m_SuperscriptSize; [SerializeField] [NativeName("subscriptOffset")] private float m_SubscriptOffset; [SerializeField] [NativeName("subscriptSize")] private float m_SubscriptSize; [SerializeField] [NativeName("underlineOffset")] private float m_UnderlineOffset; [SerializeField] [NativeName("underlineThickness")] private float m_UnderlineThickness; [SerializeField] [NativeName("strikethroughOffset")] private float m_StrikethroughOffset; [SerializeField] [NativeName("strikethroughThickness")] private float m_StrikethroughThickness; [SerializeField] [NativeName("tabWidth")] private float m_TabWidth; /// <summary> /// Constructor used for testing /// </summary> internal FaceInfo(string familyName, string styleName, int pointSize, float scale, int unitsPerEM, float lineHeight, float ascentLine, float capLine, float meanLine, float baseline, float descentLine, float superscriptOffset, float superscriptSize, float subscriptOffset, float subscriptSize, float underlineOffset, float underlineThickness, float strikethroughOffset, float strikethroughThickness, float tabWidth) { m_FaceIndex = 0; m_FamilyName = familyName; m_StyleName = styleName; m_PointSize = pointSize; m_Scale = scale; m_UnitsPerEM = unitsPerEM; m_LineHeight = lineHeight; m_AscentLine = ascentLine; m_CapLine = capLine; m_MeanLine = meanLine; m_Baseline = baseline; m_DescentLine = descentLine; m_SuperscriptOffset = superscriptOffset; m_SuperscriptSize = superscriptSize; m_SubscriptOffset = subscriptOffset; m_SubscriptSize = subscriptSize; m_UnderlineOffset = underlineOffset; m_UnderlineThickness = underlineThickness; m_StrikethroughOffset = strikethroughOffset; m_StrikethroughThickness = strikethroughThickness; m_TabWidth = tabWidth; } /// <summary> /// Compares the information in this FaceInfo structure with the information in the given FaceInfo structure to determine whether they have the same values. /// </summary> /// <param name="other">The FaceInfo structure to compare this FaceInfo structure with.</param> /// <returns>Returns true if the FaceInfo structures have the same values. False if not.</returns> public bool Compare(FaceInfo other) { return familyName == other.familyName && styleName == other.styleName && faceIndex == other.faceIndex && pointSize == other.pointSize && FontEngineUtilities.Approximately(scale, other.scale) && FontEngineUtilities.Approximately(unitsPerEM, other.unitsPerEM) && FontEngineUtilities.Approximately(lineHeight, other.lineHeight) && FontEngineUtilities.Approximately(ascentLine, other.ascentLine) && FontEngineUtilities.Approximately(capLine, other.capLine) && FontEngineUtilities.Approximately(meanLine, other.meanLine) && FontEngineUtilities.Approximately(baseline, other.baseline) && FontEngineUtilities.Approximately(descentLine, other.descentLine) && FontEngineUtilities.Approximately(superscriptOffset, other.superscriptOffset) && FontEngineUtilities.Approximately(superscriptSize, other.superscriptSize) && FontEngineUtilities.Approximately(subscriptOffset, other.subscriptOffset) && FontEngineUtilities.Approximately(subscriptSize, other.subscriptSize) && FontEngineUtilities.Approximately(underlineOffset, other.underlineOffset) && FontEngineUtilities.Approximately(underlineThickness, other.underlineThickness) && FontEngineUtilities.Approximately(strikethroughOffset, other.strikethroughOffset) && FontEngineUtilities.Approximately(strikethroughThickness, other.strikethroughThickness) && FontEngineUtilities.Approximately(tabWidth, other.tabWidth); } } }
UnityCsReference/Modules/TextCoreFontEngine/Managed/FaceInfo.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreFontEngine/Managed/FaceInfo.cs", "repo_id": "UnityCsReference", "token_count": 4556 }
435
// 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.TextCore.Text { /// <summary> /// Structure containing information about individual links contained in the text object. /// </summary> [VisibleToOtherModules("UnityEngine.IMGUIModule", "UnityEngine.UIElementsModule")] internal struct LinkInfo { public int hashCode; public int linkIdFirstCharacterIndex; public int linkIdLength; public int linkTextfirstCharacterIndex; public int linkTextLength; [VisibleToOtherModules("UnityEngine.IMGUIModule", "UnityEngine.UIElementsModule")] internal char[] linkId; string m_LinkIdString; string m_LinkTextString; internal void SetLinkId(char[] text, int startIndex, int length) { if (linkId == null || linkId.Length < length) linkId = new char[length]; for (int i = 0; i < length; i++) linkId[i] = text[startIndex + i]; linkIdLength = length; m_LinkIdString = null; m_LinkTextString = null; } /// <summary> /// Function which returns the text contained in a link. /// </summary> /// <returns></returns> public string GetLinkText(TextInfo textInfo) { if (string.IsNullOrEmpty(m_LinkTextString)) for (int i = linkTextfirstCharacterIndex; i < linkTextfirstCharacterIndex + linkTextLength; i++) m_LinkTextString += (char)textInfo.textElementInfo[i].character; return m_LinkTextString; } /// <summary> /// Function which returns the link ID as a string. /// </summary> /// <returns></returns> public string GetLinkId() { if (string.IsNullOrEmpty(m_LinkIdString)) m_LinkIdString = new string(linkId, 0, linkIdLength); return m_LinkIdString; } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/LinkInfo.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/LinkInfo.cs", "repo_id": "UnityCsReference", "token_count": 889 }
436
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using UnityEngine.Serialization; namespace UnityEngine.TextCore.Text { // Base class inherited by the various TextMeshPro Assets. [System.Serializable][ExcludeFromObjectFactory] public abstract class TextAsset : ScriptableObject { /// <summary> /// The version of the text asset class. /// Version 1.1.0 introduces new data structure to be compatible with new font asset structure. /// </summary> public string version { get { return m_Version; } internal set { m_Version = value; } } /// <summary> /// Instance ID of the TMP Asset /// </summary> public int instanceID { get { if (m_InstanceID == 0) m_InstanceID = GetInstanceID(); return m_InstanceID; } } /// <summary> /// HashCode based on the name of the asset. /// </summary> public int hashCode { get { if (m_HashCode == 0) m_HashCode = TextUtilities.GetHashCodeCaseInSensitive(name); return m_HashCode; } set => m_HashCode = value; } /// <summary> /// The material used by this asset. /// </summary> public Material material { get => m_Material; set => m_Material = value; } /// <summary> /// HashCode based on the name of the material assigned to this asset. /// </summary> public int materialHashCode { get { if (m_MaterialHashCode == 0) { if (m_Material == null) return 0; m_MaterialHashCode = TextUtilities.GetHashCodeCaseInSensitive(m_Material.name); } return m_MaterialHashCode; } set => m_MaterialHashCode = value; } // ============================================= // Private backing fields for public properties. // ============================================= [SerializeField] internal string m_Version; internal int m_InstanceID; internal int m_HashCode; [SerializeField][FormerlySerializedAs("material")] internal Material m_Material; internal int m_MaterialHashCode; } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextAsset.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextAssets/TextAsset.cs", "repo_id": "UnityCsReference", "token_count": 1243 }
437
// 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.Jobs.LowLevel.Unsafe; using UnityEngine.TextCore.LowLevel; namespace UnityEngine.TextCore.Text { internal partial class TextGenerator { public void ParsingPhase(TextInfo textInfo, TextGenerationSettings generationSettings, out uint charCode, out float maxVisibleDescender) { TextSettings textSettings = generationSettings.textSettings; m_CurrentMaterial = generationSettings.material; m_CurrentMaterialIndex = 0; m_MaterialReferenceStack.SetDefault(new MaterialReference(m_CurrentMaterialIndex, m_CurrentFontAsset, null, m_CurrentMaterial, m_Padding)); m_CurrentSpriteAsset = generationSettings.spriteAsset; // Total character count is computed when the text is parsed. int totalCharacterCount = m_TotalCharacterCount; // Calculate the scale of the font based on selected font size and sampling point size. // baseScale is calculated using the font asset assigned to the text object. float baseScale = (m_FontSize / generationSettings.fontAsset.m_FaceInfo.pointSize * generationSettings.fontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f)); float currentElementScale = baseScale; float currentEmScale = m_FontSize * 0.01f * (generationSettings.isOrthographic ? 1 : 0.1f); m_FontScaleMultiplier = 1; m_CurrentFontSize = m_FontSize; m_SizeStack.SetDefault(m_CurrentFontSize); charCode = 0; // Holds the character code of the currently being processed character. m_FontStyleInternal = generationSettings.fontStyle; // Set the default style. m_FontWeightInternal = (m_FontStyleInternal & FontStyles.Bold) == FontStyles.Bold ? TextFontWeight.Bold : generationSettings.fontWeight; m_FontWeightStack.SetDefault(m_FontWeightInternal); m_FontStyleStack.Clear(); m_LineJustification = generationSettings.textAlignment; // m_textAlignment; // Sets the line justification mode to match editor alignment. m_LineJustificationStack.SetDefault(m_LineJustification); float padding = 0; //float boldXAdvanceMultiplier = 1; // Used to increase spacing between character when style is bold. m_BaselineOffset = 0; // Used by subscript characters. m_BaselineOffsetStack.Clear(); m_FontColor32 = generationSettings.color; m_HtmlColor = m_FontColor32; m_UnderlineColor = m_HtmlColor; m_StrikethroughColor = m_HtmlColor; m_ColorStack.SetDefault(m_HtmlColor); m_UnderlineColorStack.SetDefault(m_HtmlColor); m_StrikethroughColorStack.SetDefault(m_HtmlColor); m_HighlightStateStack.SetDefault(new HighlightState(m_HtmlColor, Offset.zero)); m_ColorGradientPreset = null; m_ColorGradientStack.SetDefault(null); m_ItalicAngle = m_CurrentFontAsset.italicStyleSlant; m_ItalicAngleStack.SetDefault(m_ItalicAngle); // Clear the Action stack. m_ActionStack.Clear(); m_FXScale = Vector3.one; m_FXRotation = Quaternion.identity; m_LineOffset = 0; // Amount of space between lines (font line spacing + m_linespacing). m_LineHeight = k_FloatUnset; float lineGap = m_CurrentFontAsset.faceInfo.lineHeight - (m_CurrentFontAsset.m_FaceInfo.ascentLine - m_CurrentFontAsset.m_FaceInfo.descentLine); m_CSpacing = 0; // Amount of space added between characters as a result of the use of the <cspace> tag. m_MonoSpacing = 0; m_XAdvance = 0; // Used to track the position of each character. m_TagLineIndent = 0; // Used for indentation of text. m_TagIndent = 0; m_IndentStack.SetDefault(0); m_TagNoParsing = false; m_CharacterCount = 0; // Total characters in the char[] // Tracking of line information m_FirstCharacterOfLine = 0; m_LastCharacterOfLine = 0; m_FirstVisibleCharacterOfLine = 0; m_LastVisibleCharacterOfLine = 0; m_MaxLineAscender = TextGeneratorUtilities.largeNegativeFloat; m_MaxLineDescender = TextGeneratorUtilities.largePositiveFloat; m_LineNumber = 0; m_StartOfLineAscender = 0; m_LineVisibleCharacterCount = 0; m_LineVisibleSpaceCount = 0; bool isStartOfNewLine = true; m_IsDrivenLineSpacing = false; m_FirstOverflowCharacterIndex = -1; m_LastBaseGlyphIndex = int.MinValue; bool kerning = generationSettings.fontFeatures.Contains(OTL_FeatureTag.kern); bool markToBase = generationSettings.fontFeatures.Contains(OTL_FeatureTag.mark); bool markToMark = generationSettings.fontFeatures.Contains(OTL_FeatureTag.mkmk); m_PageNumber = 0; int pageToDisplay = Mathf.Clamp(generationSettings.pageToDisplay - 1, 0, textInfo.pageInfo.Length - 1); textInfo.ClearPageInfo(); Vector4 margins = generationSettings.margins; float marginWidth = m_MarginWidth > 0 ? m_MarginWidth : 0; float marginHeight = m_MarginHeight > 0 ? m_MarginHeight : 0; m_MarginLeft = 0; m_MarginRight = 0; m_Width = -1; float widthOfTextArea = marginWidth + 0.0001f - m_MarginLeft - m_MarginRight; // Need to initialize these Extents structures m_MeshExtents.min = TextGeneratorUtilities.largePositiveVector2; m_MeshExtents.max = TextGeneratorUtilities.largeNegativeVector2; // Initialize lineInfo textInfo.ClearLineInfo(); // Tracking of the highest Ascender m_MaxCapHeight = 0; m_MaxAscender = 0; m_MaxDescender = 0; m_PageAscender = 0; maxVisibleDescender = 0; bool isMaxVisibleDescenderSet = false; m_IsNewPage = false; // Initialize struct to track states of word wrapping bool isFirstWordOfLine = true; m_IsNonBreakingSpace = false; bool ignoreNonBreakingSpace = false; int lastSoftLineBreak = 0; CharacterSubstitution characterToSubstitute = new CharacterSubstitution(-1, 0); bool isSoftHyphenIgnored = false; var wordWrap = generationSettings.wordWrap ? TextWrappingMode.Normal : TextWrappingMode.NoWrap; // Save character and line state before we begin layout. SaveWordWrappingState(ref m_SavedWordWrapState, -1, -1, textInfo); SaveWordWrappingState(ref m_SavedLineState, -1, -1, textInfo); SaveWordWrappingState(ref m_SavedEllipsisState, -1, -1, textInfo); SaveWordWrappingState(ref m_SavedLastValidState, -1, -1, textInfo); SaveWordWrappingState(ref m_SavedSoftLineBreakState, -1, -1, textInfo); m_EllipsisInsertionCandidateStack.Clear(); // Clear the previous truncated / ellipsed state m_IsTextTruncated = false; // Safety Tracker int restoreCount = 0; // Parse through Character buffer to read HTML tags and begin creating mesh. for (int i = 0; i < m_TextProcessingArray.Length && m_TextProcessingArray[i].unicode != 0; i++) { charCode = m_TextProcessingArray[i].unicode; if (restoreCount > 5) { Debug.LogError("Line breaking recursion max threshold hit... Character [" + charCode + "] index: " + i); characterToSubstitute.index = m_CharacterCount; characterToSubstitute.unicode = k_EndOfText; } // Skip characters that have been substituted. if (charCode == 0x1A) continue; // Parse Rich Text Tag #region Parse Rich Text Tag if (generationSettings.richText && charCode == '<') { m_isTextLayoutPhase = true; m_TextElementType = TextElementType.Character; int endTagIndex; // Check if Tag is valid. If valid, skip to the end of the validated tag. if (ValidateHtmlTag(m_TextProcessingArray, i + 1, out endTagIndex, generationSettings, textInfo, out bool isThreadSuccess)) { i = endTagIndex; // Continue to next character or handle the sprite element if (m_TextElementType == TextElementType.Character) continue; } } else { m_TextElementType = textInfo.textElementInfo[m_CharacterCount].elementType; m_CurrentMaterialIndex = textInfo.textElementInfo[m_CharacterCount].materialReferenceIndex; m_CurrentFontAsset = textInfo.textElementInfo[m_CharacterCount].fontAsset; } #endregion End Parse Rich Text Tag int previousMaterialIndex = m_CurrentMaterialIndex; bool isUsingAltTypeface = textInfo.textElementInfo[m_CharacterCount].isUsingAlternateTypeface; m_isTextLayoutPhase = false; // Handle potential character substitutions #region Character Substitutions bool isInjectedCharacter = false; if (characterToSubstitute.index == m_CharacterCount) { charCode = characterToSubstitute.unicode; m_TextElementType = TextElementType.Character; isInjectedCharacter = true; switch (charCode) { case k_EndOfText: textInfo.textElementInfo[m_CharacterCount].textElement = m_CurrentFontAsset.characterLookupTable[k_EndOfText]; m_IsTextTruncated = true; break; case k_HyphenMinus: // break; case k_HorizontalEllipsis: textInfo.textElementInfo[m_CharacterCount].textElement = m_Ellipsis.character; textInfo.textElementInfo[m_CharacterCount].elementType = TextElementType.Character; textInfo.textElementInfo[m_CharacterCount].fontAsset = m_Ellipsis.fontAsset; textInfo.textElementInfo[m_CharacterCount].material = m_Ellipsis.material; textInfo.textElementInfo[m_CharacterCount].materialReferenceIndex = m_Ellipsis.materialIndex; // Need to increase reference count in the event the primary mesh has no characters. m_MaterialReferences[m_Underline.materialIndex].referenceCount += 1; // Indicates the source parsing data has been modified. m_IsTextTruncated = true; // End Of Text characterToSubstitute.index = m_CharacterCount + 1; characterToSubstitute.unicode = k_EndOfText; break; } } #endregion // When using Linked text, mark character as ignored and skip to next character. #region Linked Text if (m_CharacterCount < generationSettings.firstVisibleCharacter && charCode != k_EndOfText) { textInfo.textElementInfo[m_CharacterCount].isVisible = false; textInfo.textElementInfo[m_CharacterCount].character = (char)k_ZeroWidthSpace; textInfo.textElementInfo[m_CharacterCount].lineNumber = 0; m_CharacterCount += 1; continue; } #endregion // Handle Font Styles like LowerCase, UpperCase and SmallCaps. #region Handling of LowerCase, UpperCase and SmallCaps Font Styles float smallCapsMultiplier = 1.0f; if (m_TextElementType == TextElementType.Character) { if ((m_FontStyleInternal & FontStyles.UpperCase) == FontStyles.UpperCase) { // If this character is lowercase, switch to uppercase. if (char.IsLower((char)charCode)) charCode = char.ToUpper((char)charCode); } else if ((m_FontStyleInternal & FontStyles.LowerCase) == FontStyles.LowerCase) { // If this character is uppercase, switch to lowercase. if (char.IsUpper((char)charCode)) charCode = char.ToLower((char)charCode); } else if ((m_FontStyleInternal & FontStyles.SmallCaps) == FontStyles.SmallCaps) { if (char.IsLower((char)charCode)) { smallCapsMultiplier = 0.8f; charCode = char.ToUpper((char)charCode); } } } #endregion // Look up Character Data from Dictionary and cache it. #region Look up Character Data float baselineOffset = 0; float elementAscentLine = 0; float elementDescentLine = 0; if (m_TextElementType == TextElementType.Sprite) { // If a sprite is used as a fallback then get a reference to it and set the color to white. SpriteCharacter sprite = (SpriteCharacter)textInfo.textElementInfo[m_CharacterCount].textElement; m_CurrentSpriteAsset = sprite.textAsset as SpriteAsset; m_SpriteIndex = (int)sprite.glyphIndex; if (sprite == null) continue; // Sprites are assigned in the E000 Private Area + sprite Index if (charCode == '<') charCode = 57344 + (uint)m_SpriteIndex; else m_SpriteColor = Color.white; float fontScale = (m_CurrentFontSize / m_CurrentFontAsset.faceInfo.pointSize * m_CurrentFontAsset.faceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f)); // The sprite scale calculations are based on the font asset assigned to the text object. if (m_CurrentSpriteAsset.m_FaceInfo.pointSize > 0) { float spriteScale = m_CurrentFontSize / m_CurrentSpriteAsset.m_FaceInfo.pointSize * m_CurrentSpriteAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f); currentElementScale = sprite.m_Scale * sprite.m_Glyph.scale * spriteScale; elementAscentLine = m_CurrentSpriteAsset.m_FaceInfo.ascentLine; baselineOffset = m_CurrentSpriteAsset.m_FaceInfo.baseline * fontScale * m_FontScaleMultiplier * m_CurrentSpriteAsset.m_FaceInfo.scale; elementDescentLine = m_CurrentSpriteAsset.m_FaceInfo.descentLine; } else { float spriteScale = m_CurrentFontSize / m_CurrentFontAsset.m_FaceInfo.pointSize * m_CurrentFontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f); currentElementScale = m_CurrentFontAsset.m_FaceInfo.ascentLine / sprite.m_Glyph.metrics.height * sprite.m_Scale * sprite.m_Glyph.scale * spriteScale; float scaleDelta = spriteScale / currentElementScale; elementAscentLine = m_CurrentFontAsset.m_FaceInfo.ascentLine * scaleDelta; baselineOffset = m_CurrentFontAsset.m_FaceInfo.baseline * fontScale * m_FontScaleMultiplier * m_CurrentFontAsset.m_FaceInfo.scale; elementDescentLine = m_CurrentFontAsset.m_FaceInfo.descentLine * scaleDelta; } m_CachedTextElement = sprite; textInfo.textElementInfo[m_CharacterCount].elementType = TextElementType.Sprite; textInfo.textElementInfo[m_CharacterCount].scale = currentElementScale; textInfo.textElementInfo[m_CharacterCount].spriteAsset = m_CurrentSpriteAsset; textInfo.textElementInfo[m_CharacterCount].fontAsset = m_CurrentFontAsset; textInfo.textElementInfo[m_CharacterCount].materialReferenceIndex = m_CurrentMaterialIndex; m_CurrentMaterialIndex = previousMaterialIndex; padding = 0; } else if (m_TextElementType == TextElementType.Character) { m_CachedTextElement = textInfo.textElementInfo[m_CharacterCount].textElement; if (m_CachedTextElement == null) { continue; } m_CurrentFontAsset = textInfo.textElementInfo[m_CharacterCount].fontAsset; m_CurrentMaterial = textInfo.textElementInfo[m_CharacterCount].material; m_CurrentMaterialIndex = textInfo.textElementInfo[m_CharacterCount].materialReferenceIndex; // Special handling if replaced character was a line feed where in this case we have to use the scale of the previous character. float adjustedScale; if (isInjectedCharacter && m_TextProcessingArray[i].unicode == 0x0A && m_CharacterCount != m_FirstCharacterOfLine) adjustedScale = textInfo.textElementInfo[m_CharacterCount - 1].pointSize * smallCapsMultiplier / m_CurrentFontAsset.m_FaceInfo.pointSize * m_CurrentFontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f); else adjustedScale = m_CurrentFontSize * smallCapsMultiplier / m_CurrentFontAsset.m_FaceInfo.pointSize * m_CurrentFontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f); // Special handling for injected Ellipsis if (isInjectedCharacter && charCode == k_HorizontalEllipsis) { elementAscentLine = 0; elementDescentLine = 0; } else { elementAscentLine = m_CurrentFontAsset.m_FaceInfo.ascentLine; elementDescentLine = m_CurrentFontAsset.m_FaceInfo.descentLine; } currentElementScale = adjustedScale * m_FontScaleMultiplier * m_CachedTextElement.m_Scale * m_CachedTextElement.m_Glyph.scale; baselineOffset = m_CurrentFontAsset.m_FaceInfo.baseline * adjustedScale * m_FontScaleMultiplier * m_CurrentFontAsset.m_FaceInfo.scale; textInfo.textElementInfo[m_CharacterCount].elementType = TextElementType.Character; textInfo.textElementInfo[m_CharacterCount].scale = currentElementScale; padding = m_Padding; } #endregion // Handle Soft Hyphen #region Handle Soft Hyphen float currentElementUnmodifiedScale = currentElementScale; if (charCode == k_SoftHyphen || charCode == k_EndOfText) currentElementScale = 0; #endregion // Store some of the text object's information textInfo.textElementInfo[m_CharacterCount].character = charCode; textInfo.textElementInfo[m_CharacterCount].pointSize = m_CurrentFontSize; textInfo.textElementInfo[m_CharacterCount].color = m_HtmlColor; textInfo.textElementInfo[m_CharacterCount].underlineColor = m_UnderlineColor; textInfo.textElementInfo[m_CharacterCount].strikethroughColor = m_StrikethroughColor; textInfo.textElementInfo[m_CharacterCount].highlightState = m_HighlightState; textInfo.textElementInfo[m_CharacterCount].style = m_FontStyleInternal; if (m_FontWeightInternal == TextFontWeight.Bold) { textInfo.textElementInfo[m_CharacterCount].style |= FontStyles.Bold; } // Cache glyph metrics Glyph altGlyph = textInfo.textElementInfo[m_CharacterCount].alternativeGlyph; GlyphMetrics currentGlyphMetrics = altGlyph == null ? m_CachedTextElement.m_Glyph.metrics : altGlyph.metrics; // Optimization to avoid calling this more than once per character. bool isWhiteSpace = charCode <= 0xFFFF && char.IsWhiteSpace((char)charCode); // Handle Kerning if Enabled. #region Handle Kerning GlyphValueRecord glyphAdjustments = new GlyphValueRecord(); float characterSpacingAdjustment = generationSettings.characterSpacing; if (kerning && m_TextElementType == TextElementType.Character) { GlyphPairAdjustmentRecord adjustmentPair; uint baseGlyphIndex = m_CachedTextElement.m_GlyphIndex; if (m_CharacterCount < totalCharacterCount - 1 && textInfo.textElementInfo[m_CharacterCount + 1].elementType == TextElementType.Character) { uint nextGlyphIndex = textInfo.textElementInfo[m_CharacterCount + 1].textElement.m_GlyphIndex; uint key = nextGlyphIndex << 16 | baseGlyphIndex; if (m_CurrentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.TryGetValue(key, out adjustmentPair)) { glyphAdjustments = adjustmentPair.firstAdjustmentRecord.glyphValueRecord; characterSpacingAdjustment = (adjustmentPair.featureLookupFlags & FontFeatureLookupFlags.IgnoreSpacingAdjustments) == FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment; } } if (m_CharacterCount >= 1) { uint previousGlyphIndex = textInfo.textElementInfo[m_CharacterCount - 1].textElement.m_GlyphIndex; uint key = baseGlyphIndex << 16 | previousGlyphIndex; if (textInfo.textElementInfo[m_CharacterCount - 1].elementType == TextElementType.Character && m_CurrentFontAsset.m_FontFeatureTable.m_GlyphPairAdjustmentRecordLookup.TryGetValue(key, out adjustmentPair)) { glyphAdjustments += adjustmentPair.secondAdjustmentRecord.glyphValueRecord; characterSpacingAdjustment = (adjustmentPair.featureLookupFlags & FontFeatureLookupFlags.IgnoreSpacingAdjustments) == FontFeatureLookupFlags.IgnoreSpacingAdjustments ? 0 : characterSpacingAdjustment; } } textInfo.textElementInfo[m_CharacterCount].adjustedHorizontalAdvance = glyphAdjustments.xAdvance; } #endregion // Handle Diacritical Marks #region Handle Diacritical Marks bool isBaseGlyph = TextGeneratorUtilities.IsBaseGlyph((uint)charCode); if (isBaseGlyph) m_LastBaseGlyphIndex = m_CharacterCount; if (m_CharacterCount > 0 && !isBaseGlyph) { // Check for potential Mark-to-Base lookup if previous glyph was a base glyph if (markToBase && m_LastBaseGlyphIndex != int.MinValue && m_LastBaseGlyphIndex == m_CharacterCount - 1) { Glyph baseGlyph = textInfo.textElementInfo[m_LastBaseGlyphIndex].textElement.glyph; uint baseGlyphIndex = baseGlyph.index; uint markGlyphIndex = m_CachedTextElement.glyphIndex; uint key = markGlyphIndex << 16 | baseGlyphIndex; if (m_CurrentFontAsset.fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.TryGetValue(key, out MarkToBaseAdjustmentRecord glyphAdjustmentRecord)) { float advanceOffset = (textInfo.textElementInfo[m_LastBaseGlyphIndex].origin - m_XAdvance) / currentElementScale; glyphAdjustments.xPlacement = advanceOffset + glyphAdjustmentRecord.baseGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.markPositionAdjustment.xPositionAdjustment; glyphAdjustments.yPlacement = glyphAdjustmentRecord.baseGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.markPositionAdjustment.yPositionAdjustment; characterSpacingAdjustment = 0; } } else { // Iterate from previous glyph to last base glyph checking for any potential Mark-to-Mark lookups to apply. Otherwise check for potential Mark-to-Base lookup between the current glyph and last base glyph bool wasLookupApplied = false; // Check for any potential Mark-to-Mark lookups if (markToMark) { for (int characterLookupIndex = m_CharacterCount - 1; characterLookupIndex >= 0 && characterLookupIndex != m_LastBaseGlyphIndex; characterLookupIndex--) { // Handle any potential Mark-to-Mark lookup Glyph baseMarkGlyph = textInfo.textElementInfo[characterLookupIndex].textElement.glyph; uint baseGlyphIndex = baseMarkGlyph.index; uint combiningMarkGlyphIndex = m_CachedTextElement.glyphIndex; uint key = combiningMarkGlyphIndex << 16 | baseGlyphIndex; if (m_CurrentFontAsset.fontFeatureTable.m_MarkToMarkAdjustmentRecordLookup.TryGetValue(key, out MarkToMarkAdjustmentRecord glyphAdjustmentRecord)) { float baseMarkOrigin = (textInfo.textElementInfo[characterLookupIndex].origin - m_XAdvance) / currentElementScale; float currentBaseline = baselineOffset - m_LineOffset + m_BaselineOffset; float baseMarkBaseline = (textInfo.textElementInfo[characterLookupIndex].baseLine - currentBaseline) / currentElementScale; glyphAdjustments.xPlacement = baseMarkOrigin + glyphAdjustmentRecord.baseMarkGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.combiningMarkPositionAdjustment.xPositionAdjustment; glyphAdjustments.yPlacement = baseMarkBaseline + glyphAdjustmentRecord.baseMarkGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.combiningMarkPositionAdjustment.yPositionAdjustment; characterSpacingAdjustment = 0; wasLookupApplied = true; break; } } } // If no Mark-to-Mark lookups were applied, check for potential Mark-to-Base lookup. if (markToBase && m_LastBaseGlyphIndex != int.MinValue && !wasLookupApplied) { // Handle lookup for Mark-to-Base Glyph baseGlyph = textInfo.textElementInfo[m_LastBaseGlyphIndex].textElement.glyph; uint baseGlyphIndex = baseGlyph.index; uint markGlyphIndex = m_CachedTextElement.glyphIndex; uint key = markGlyphIndex << 16 | baseGlyphIndex; if (m_CurrentFontAsset.fontFeatureTable.m_MarkToBaseAdjustmentRecordLookup.TryGetValue(key, out MarkToBaseAdjustmentRecord glyphAdjustmentRecord)) { float advanceOffset = (textInfo.textElementInfo[m_LastBaseGlyphIndex].origin - m_XAdvance) / currentElementScale; glyphAdjustments.xPlacement = advanceOffset + glyphAdjustmentRecord.baseGlyphAnchorPoint.xCoordinate - glyphAdjustmentRecord.markPositionAdjustment.xPositionAdjustment; glyphAdjustments.yPlacement = glyphAdjustmentRecord.baseGlyphAnchorPoint.yCoordinate - glyphAdjustmentRecord.markPositionAdjustment.yPositionAdjustment; characterSpacingAdjustment = 0; } } } } // Adjust relevant text metrics elementAscentLine += glyphAdjustments.yPlacement; elementDescentLine += glyphAdjustments.yPlacement; #endregion // Initial Implementation for RTL support. #region Handle Right-to-Left if (generationSettings.isRightToLeft) { m_XAdvance -= currentGlyphMetrics.horizontalAdvance * (1 - m_CharWidthAdjDelta) * currentElementScale; if (isWhiteSpace || charCode == k_ZeroWidthSpace) m_XAdvance -= generationSettings.wordSpacing * currentEmScale; } #endregion // Handle Mono Spacing #region Handle Mono Spacing float monoAdvance = 0; if (m_MonoSpacing != 0 && charCode != k_ZeroWidthSpace) { if (m_DuoSpace && (charCode == '.' || charCode == ':' || charCode == ',')) monoAdvance = (m_MonoSpacing / 4 - (currentGlyphMetrics.width / 2 + currentGlyphMetrics.horizontalBearingX) * currentElementScale) * (1 - m_CharWidthAdjDelta); else monoAdvance = (m_MonoSpacing / 2 - (currentGlyphMetrics.width / 2 + currentGlyphMetrics.horizontalBearingX) * currentElementScale) * (1 - m_CharWidthAdjDelta); m_XAdvance += monoAdvance; } #endregion // Set Padding based on selected font style #region Handle Style Padding float boldSpacingAdjustment; float stylePadding; bool hasGradientScale = m_CurrentFontAsset.atlasRenderMode != GlyphRenderMode.SMOOTH && m_CurrentFontAsset.atlasRenderMode != GlyphRenderMode.COLOR; if (m_TextElementType == TextElementType.Character && !isUsingAltTypeface && ((textInfo.textElementInfo[m_CharacterCount].style & FontStyles.Bold) == FontStyles.Bold)) // Checks for any combination of Bold Style. { if (hasGradientScale) { var gradientScale = generationSettings.isIMGUI ? m_CurrentMaterial.GetFloat(TextShaderUtilities.ID_GradientScale) : m_CurrentFontAsset.atlasPadding + 1; stylePadding = m_CurrentFontAsset.boldStyleWeight / 4.0f * gradientScale; // Clamp overall padding to Gradient Scale size. if (stylePadding + padding > gradientScale) padding = gradientScale - stylePadding; } else stylePadding = 0; boldSpacingAdjustment = m_CurrentFontAsset.boldStyleSpacing; } else { if (hasGradientScale) { var gradientScale = generationSettings.isIMGUI ? m_CurrentMaterial.GetFloat(TextShaderUtilities.ID_GradientScale) : m_CurrentFontAsset.atlasPadding + 1; stylePadding = m_CurrentFontAsset.m_RegularStyleWeight / 4.0f * gradientScale; // Clamp overall padding to Gradient Scale size. if (stylePadding + padding > gradientScale) padding = gradientScale - stylePadding; } else stylePadding = 0; boldSpacingAdjustment = 0; } #endregion Handle Style Padding // Determine the position of the vertices of the Character or Sprite. #region Calculate Vertices Position Vector3 topLeft; topLeft.x = m_XAdvance + ((currentGlyphMetrics.horizontalBearingX * m_FXScale.x - padding - stylePadding + glyphAdjustments.xPlacement) * currentElementScale * (1 - m_CharWidthAdjDelta)); topLeft.y = baselineOffset + (currentGlyphMetrics.horizontalBearingY + padding + glyphAdjustments.yPlacement) * currentElementScale - m_LineOffset + m_BaselineOffset; topLeft.z = 0; Vector3 bottomLeft; bottomLeft.x = topLeft.x; bottomLeft.y = topLeft.y - ((currentGlyphMetrics.height + padding * 2) * currentElementScale); bottomLeft.z = 0; Vector3 topRight; topRight.x = bottomLeft.x + ((currentGlyphMetrics.width * m_FXScale.x + padding * 2 + stylePadding * 2) * currentElementScale * (1 - m_CharWidthAdjDelta)); topRight.y = topLeft.y; topRight.z = 0; Vector3 bottomRight; bottomRight.x = topRight.x; bottomRight.y = bottomLeft.y; bottomRight.z = 0; #endregion // Check if we need to Shear the rectangles for Italic styles #region Handle Italic & Shearing if (m_TextElementType == TextElementType.Character && !isUsingAltTypeface && ((m_FontStyleInternal & FontStyles.Italic) == FontStyles.Italic)) { // Shift Top vertices forward by half (Shear Value * height of character) and Bottom vertices back by same amount. float shearValue = m_ItalicAngle * 0.01f; float midPoint = ((m_CurrentFontAsset.m_FaceInfo.capLine - (m_CurrentFontAsset.m_FaceInfo.baseline + m_BaselineOffset)) / 2) * m_FontScaleMultiplier * m_CurrentFontAsset.m_FaceInfo.scale; Vector3 topShear = new Vector3(shearValue * ((currentGlyphMetrics.horizontalBearingY + padding + stylePadding - midPoint) * currentElementScale), 0, 0); Vector3 bottomShear = new Vector3(shearValue * (((currentGlyphMetrics.horizontalBearingY - currentGlyphMetrics.height - padding - stylePadding - midPoint)) * currentElementScale), 0, 0); topLeft += topShear; bottomLeft += bottomShear; topRight += topShear; bottomRight += bottomShear; } #endregion Handle Italics & Shearing // Handle Character FX Rotation #region Handle Character FX Rotation if (m_FXRotation != Quaternion.identity) { Matrix4x4 rotationMatrix = Matrix4x4.Rotate(m_FXRotation); Vector3 positionOffset = (topRight + bottomLeft) / 2; topLeft = rotationMatrix.MultiplyPoint3x4(topLeft - positionOffset) + positionOffset; bottomLeft = rotationMatrix.MultiplyPoint3x4(bottomLeft - positionOffset) + positionOffset; topRight = rotationMatrix.MultiplyPoint3x4(topRight - positionOffset) + positionOffset; bottomRight = rotationMatrix.MultiplyPoint3x4(bottomRight - positionOffset) + positionOffset; } #endregion // Store vertex information for the character or sprite. textInfo.textElementInfo[m_CharacterCount].bottomLeft = bottomLeft; textInfo.textElementInfo[m_CharacterCount].topLeft = topLeft; textInfo.textElementInfo[m_CharacterCount].topRight = topRight; textInfo.textElementInfo[m_CharacterCount].bottomRight = bottomRight; textInfo.textElementInfo[m_CharacterCount].origin = m_XAdvance + glyphAdjustments.xPlacement * currentElementScale; textInfo.textElementInfo[m_CharacterCount].baseLine = (baselineOffset - m_LineOffset + m_BaselineOffset) + glyphAdjustments.yPlacement * currentElementScale; textInfo.textElementInfo[m_CharacterCount].aspectRatio = (topRight.x - bottomLeft.x) / (topLeft.y - bottomLeft.y); // Compute text metrics #region Compute Ascender & Descender values // Element Ascender in line space float elementAscender = m_TextElementType == TextElementType.Character ? elementAscentLine * currentElementScale / smallCapsMultiplier + m_BaselineOffset : elementAscentLine * currentElementScale + m_BaselineOffset; // Element Descender in line space float elementDescender = m_TextElementType == TextElementType.Character ? elementDescentLine * currentElementScale / smallCapsMultiplier + m_BaselineOffset : elementDescentLine * currentElementScale + m_BaselineOffset; float adjustedAscender = elementAscender; float adjustedDescender = elementDescender; // Max line ascender and descender in line space bool isFirstCharacterOfLine = m_CharacterCount == m_FirstCharacterOfLine; if (isFirstCharacterOfLine || isWhiteSpace == false) { // Special handling for Superscript and Subscript where we use the unadjusted line ascender and descender if (m_BaselineOffset != 0) { adjustedAscender = Mathf.Max((elementAscender - m_BaselineOffset) / m_FontScaleMultiplier, adjustedAscender); adjustedDescender = Mathf.Min((elementDescender - m_BaselineOffset) / m_FontScaleMultiplier, adjustedDescender); } m_MaxLineAscender = Mathf.Max(adjustedAscender, m_MaxLineAscender); m_MaxLineDescender = Mathf.Min(adjustedDescender, m_MaxLineDescender); } // Element Ascender and Descender in object space if (isFirstCharacterOfLine || isWhiteSpace == false) { textInfo.textElementInfo[m_CharacterCount].adjustedAscender = adjustedAscender; textInfo.textElementInfo[m_CharacterCount].adjustedDescender = adjustedDescender; textInfo.textElementInfo[m_CharacterCount].ascender = elementAscender - m_LineOffset; m_MaxDescender = textInfo.textElementInfo[m_CharacterCount].descender = elementDescender - m_LineOffset; } else { textInfo.textElementInfo[m_CharacterCount].adjustedAscender = m_MaxLineAscender; textInfo.textElementInfo[m_CharacterCount].adjustedDescender = m_MaxLineDescender; textInfo.textElementInfo[m_CharacterCount].ascender = m_MaxLineAscender - m_LineOffset; m_MaxDescender = textInfo.textElementInfo[m_CharacterCount].descender = m_MaxLineDescender - m_LineOffset; } // Max text object ascender and cap height if (m_LineNumber == 0 || m_IsNewPage) { if (isFirstCharacterOfLine || isWhiteSpace == false) { m_MaxAscender = m_MaxLineAscender; m_MaxCapHeight = Mathf.Max(m_MaxCapHeight, m_CurrentFontAsset.m_FaceInfo.capLine * currentElementScale / smallCapsMultiplier); } } // Page ascender if (m_LineOffset == 0) { if (isFirstCharacterOfLine || isWhiteSpace == false) m_PageAscender = m_PageAscender > elementAscender ? m_PageAscender : elementAscender; } #endregion // Set Characters to not visible by default. textInfo.textElementInfo[m_CharacterCount].isVisible = false; // Setup Mesh for visible text elements. ie. not a SPACE / LINEFEED / CARRIAGE RETURN. #region Handle Visible Characters if (charCode == k_Tab || ((wordWrap == TextWrappingMode.PreserveWhitespace || wordWrap == TextWrappingMode.PreserveWhitespaceNoWrap) && (isWhiteSpace || charCode == k_ZeroWidthSpace)) || (isWhiteSpace == false && charCode != k_ZeroWidthSpace && charCode != k_SoftHyphen && charCode != k_EndOfText) || (charCode == k_SoftHyphen && isSoftHyphenIgnored == false) || m_TextElementType == TextElementType.Sprite) { textInfo.textElementInfo[m_CharacterCount].isVisible = true; #region Experimental Margin Shaper //Vector2 shapedMargins; //if (marginShaper) //{HorizontalAlignmentOption // shapedMargins = m_marginShaper.GetShapedMargins(textInfo.textElementInfo[m_CharacterCount].baseLine); // if (shapedMargins.x < margins.x) // { // shapedMargins.x = m_MarginLeft; // } // else // { // shapedMargins.x += m_MarginLeft - margins.x; // } // if (shapedMargins.y < margins.z) // { // shapedMargins.y = m_MarginRight; // } // else // { // shapedMargins.y += m_MarginRight - margins.z; // } //} //else //{ // shapedMargins.x = m_MarginLeft; // shapedMargins.y = m_MarginRight; //} //width = marginWidth + 0.0001f - shapedMargins.x - shapedMargins.y; //if (m_Width != -1 && m_Width < width) //{ // width = m_Width; //} //textInfo.lineInfo[m_LineNumber].marginLeft = shapedMargins.x; #endregion float marginLeft = m_MarginLeft; float marginRight = m_MarginRight; // Injected characters do not override margins if (isInjectedCharacter) { marginLeft = textInfo.lineInfo[m_LineNumber].marginLeft; marginRight = textInfo.lineInfo[m_LineNumber].marginRight; } widthOfTextArea = m_Width != -1 ? Mathf.Min(marginWidth + 0.0001f - marginLeft - marginRight, m_Width) : marginWidth + 0.0001f - marginLeft - marginRight; // Calculate the line breaking width of the text. float textWidth = Mathf.Abs(m_XAdvance) + (!generationSettings.isRightToLeft ? currentGlyphMetrics.horizontalAdvance : 0) * (1 - m_CharWidthAdjDelta) * (charCode == k_SoftHyphen ? currentElementUnmodifiedScale : currentElementScale); float textHeight = m_MaxAscender - (m_MaxLineDescender - m_LineOffset) + (m_LineOffset > 0 && m_IsDrivenLineSpacing == false ? m_MaxLineAscender - m_StartOfLineAscender : 0); int testedCharacterCount = m_CharacterCount; // Handling of current line Vertical Bounds #region Current Line Vertical Bounds Check if (textHeight > marginHeight + 0.0001f) { // Set isTextOverflowing and firstOverflowCharacterIndex if (m_FirstOverflowCharacterIndex == -1) m_FirstOverflowCharacterIndex = m_CharacterCount; // Check if Auto-Size is enabled if (generationSettings.autoSize) { // Handle Line spacing adjustments #region Line Spacing Adjustments if (m_LineSpacingDelta > generationSettings.lineSpacingMax && m_LineOffset > 0 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { float adjustmentDelta = (marginHeight - textHeight) / m_LineNumber; m_LineSpacingDelta = Mathf.Max(m_LineSpacingDelta + adjustmentDelta / baseScale, generationSettings.lineSpacingMax); return; } #endregion // Handle Text Auto-sizing resulting from text exceeding vertical bounds. #region Text Auto-Sizing (Text greater than vertical bounds) if (m_FontSize > generationSettings.fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { m_MaxFontSize = m_FontSize; float sizeDelta = Mathf.Max((m_FontSize - m_MinFontSize) / 2, 0.05f); m_FontSize -= sizeDelta; m_FontSize = Mathf.Max((int)(m_FontSize * 20 + 0.5f) / 20f, generationSettings.fontSizeMin); return; } #endregion Text Auto-Sizing } // Handle Vertical Overflow on current line switch (generationSettings.overflowMode) { case TextOverflowMode.Overflow: case TextOverflowMode.ScrollRect: case TextOverflowMode.Masking: // Nothing happens as vertical bounds are ignored in this mode. break; case TextOverflowMode.Truncate: i = RestoreWordWrappingState(ref m_SavedLastValidState, textInfo); characterToSubstitute.index = testedCharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; case TextOverflowMode.Ellipsis: if (m_LineNumber > 0) { if (m_EllipsisInsertionCandidateStack.Count == 0) { i = -1; m_CharacterCount = 0; characterToSubstitute.index = 0; characterToSubstitute.unicode = k_EndOfText; m_FirstCharacterOfLine = 0; continue; } var ellipsisState = m_EllipsisInsertionCandidateStack.Pop(); i = RestoreWordWrappingState(ref ellipsisState, textInfo); i -= 1; m_CharacterCount -= 1; characterToSubstitute.index = m_CharacterCount; characterToSubstitute.unicode = k_HorizontalEllipsis; restoreCount += 1; continue; } break; case TextOverflowMode.Linked: i = RestoreWordWrappingState(ref m_SavedLastValidState, textInfo); // Truncate remaining text characterToSubstitute.index = testedCharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; case TextOverflowMode.Page: // End layout of text if first character / page doesn't fit. if (i < 0 || testedCharacterCount == 0) { i = -1; m_CharacterCount = 0; characterToSubstitute.index = 0; characterToSubstitute.unicode = k_EndOfText; continue; } else if (m_MaxLineAscender - m_MaxLineDescender > marginHeight + 0.0001f) { // Current line exceeds the height of the text container // as such we stop on the previous line. i = RestoreWordWrappingState(ref m_SavedLineState, textInfo); characterToSubstitute.index = testedCharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; } // Go back to previous line and re-layout i = RestoreWordWrappingState(ref m_SavedLineState, textInfo); m_IsNewPage = true; m_FirstCharacterOfLine = m_CharacterCount; m_MaxLineAscender = TextGeneratorUtilities.largeNegativeFloat; m_MaxLineDescender = TextGeneratorUtilities.largePositiveFloat; m_StartOfLineAscender = 0; m_XAdvance = 0 + m_TagIndent; m_LineOffset = 0; m_MaxAscender = 0; m_PageAscender = 0; m_LineNumber += 1; m_PageNumber += 1; // Should consider saving page data here continue; } } #endregion // Handling of Horizontal Bounds #region Current Line Horizontal Bounds Check if (isBaseGlyph && textWidth > widthOfTextArea) { // Handle Line Breaking (if still possible) if (wordWrap != TextWrappingMode.NoWrap && wordWrap != TextWrappingMode.PreserveWhitespaceNoWrap && m_CharacterCount != m_FirstCharacterOfLine) { // Restore state to previous safe line breaking i = RestoreWordWrappingState(ref m_SavedWordWrapState, textInfo); // Compute potential new line offset in the event a line break is needed. float lineOffsetDelta = 0; if (m_LineHeight == k_FloatUnset) { float ascender = textInfo.textElementInfo[m_CharacterCount].adjustedAscender; lineOffsetDelta = (m_LineOffset > 0 && m_IsDrivenLineSpacing == false ? m_MaxLineAscender - m_StartOfLineAscender : 0) - m_MaxLineDescender + ascender + (lineGap + m_LineSpacingDelta) * baseScale + generationSettings.lineSpacing * currentEmScale; } else { lineOffsetDelta = m_LineHeight + generationSettings.lineSpacing * currentEmScale; m_IsDrivenLineSpacing = true; } // Calculate new text height float newTextHeight = m_MaxAscender + lineOffsetDelta + m_LineOffset - textInfo.textElementInfo[m_CharacterCount].adjustedDescender; // Replace Soft Hyphen by Hyphen Minus 0x2D #region Handle Soft Hyphenation if (textInfo.textElementInfo[m_CharacterCount - 1].character == k_SoftHyphen && isSoftHyphenIgnored == false) { // Only inject Hyphen Minus if new line is possible if (generationSettings.overflowMode == TextOverflowMode.Overflow || newTextHeight < marginHeight + 0.0001f) { characterToSubstitute.index = m_CharacterCount - 1; characterToSubstitute.unicode = k_HyphenMinus; i -= 1; m_CharacterCount -= 1; continue; } } isSoftHyphenIgnored = false; // Ignore Soft Hyphen to prevent it from wrapping if (textInfo.textElementInfo[m_CharacterCount].character == k_SoftHyphen) { isSoftHyphenIgnored = true; continue; } #endregion // Adjust character spacing before breaking up word if auto size is enabled if (generationSettings.autoSize && isFirstWordOfLine) { // Handle Character Width Adjustments #region Character Width Adjustments if (m_CharWidthAdjDelta < generationSettings.charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { float adjustedTextWidth = textWidth; // Determine full width of the text if (m_CharWidthAdjDelta > 0) adjustedTextWidth /= 1f - m_CharWidthAdjDelta; float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f); m_CharWidthAdjDelta += adjustmentDelta / adjustedTextWidth; m_CharWidthAdjDelta = Mathf.Min(m_CharWidthAdjDelta, generationSettings.charWidthMaxAdj / 100); return; } #endregion // Handle Text Auto-sizing resulting from text exceeding vertical bounds. #region Text Auto-Sizing (Text greater than vertical bounds) if (m_FontSize > generationSettings.fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { m_MaxFontSize = m_FontSize; float sizeDelta = Mathf.Max((m_FontSize - m_MinFontSize) / 2, 0.05f); m_FontSize -= sizeDelta; m_FontSize = Mathf.Max((int)(m_FontSize * 20 + 0.5f) / 20f, generationSettings.fontSizeMin); return; } #endregion Text Auto-Sizing } // Special handling if first word of line and non breaking space int savedSoftLineBreakingSpace = m_SavedSoftLineBreakState.previousWordBreak; if (isFirstWordOfLine && savedSoftLineBreakingSpace != -1) { if (savedSoftLineBreakingSpace != lastSoftLineBreak) { i = RestoreWordWrappingState(ref m_SavedSoftLineBreakState, textInfo); lastSoftLineBreak = savedSoftLineBreakingSpace; // check if soft hyphen if (textInfo.textElementInfo[m_CharacterCount - 1].character == k_SoftHyphen) { characterToSubstitute.index = m_CharacterCount - 1; characterToSubstitute.unicode = k_HyphenMinus; i -= 1; m_CharacterCount -= 1; continue; } } } // Determine if new line of text would exceed the vertical bounds of text container if (newTextHeight > marginHeight + 0.0001f) { // Set isTextOverflowing and firstOverflowCharacterIndex if (m_FirstOverflowCharacterIndex == -1) m_FirstOverflowCharacterIndex = m_CharacterCount; // Check if Auto-Size is enabled if (generationSettings.autoSize) { // Handle Line spacing adjustments #region Line Spacing Adjustments if (m_LineSpacingDelta > generationSettings.lineSpacingMax && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { float adjustmentDelta = (marginHeight - newTextHeight) / (m_LineNumber + 1); m_LineSpacingDelta = Mathf.Max(m_LineSpacingDelta + adjustmentDelta / baseScale, generationSettings.lineSpacingMax); return; } #endregion // Handle Character Width Adjustments #region Character Width Adjustments if (m_CharWidthAdjDelta < generationSettings.charWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { float adjustedTextWidth = textWidth; // Determine full width of the text if (m_CharWidthAdjDelta > 0) adjustedTextWidth /= 1f - m_CharWidthAdjDelta; float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f); m_CharWidthAdjDelta += adjustmentDelta / adjustedTextWidth; m_CharWidthAdjDelta = Mathf.Min(m_CharWidthAdjDelta, generationSettings.charWidthMaxAdj / 100); return; } #endregion // Handle Text Auto-sizing resulting from text exceeding vertical bounds. #region Text Auto-Sizing (Text greater than vertical bounds) if (m_FontSize > generationSettings.fontSizeMin && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { m_MaxFontSize = m_FontSize; float sizeDelta = Mathf.Max((m_FontSize - m_MinFontSize) / 2, 0.05f); m_FontSize -= sizeDelta; m_FontSize = Mathf.Max((int)(m_FontSize * 20 + 0.5f) / 20f, generationSettings.fontSizeMin); return; } #endregion Text Auto-Sizing } // Check Text Overflow Modes switch (generationSettings.overflowMode) { case TextOverflowMode.Overflow: case TextOverflowMode.ScrollRect: case TextOverflowMode.Masking: InsertNewLine(i, baseScale, currentElementScale, currentEmScale, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender, generationSettings, textInfo); isStartOfNewLine = true; isFirstWordOfLine = true; continue; case TextOverflowMode.Truncate: i = RestoreWordWrappingState(ref m_SavedLastValidState, textInfo); characterToSubstitute.index = testedCharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; case TextOverflowMode.Ellipsis: if (m_EllipsisInsertionCandidateStack.Count == 0) { i = -1; m_CharacterCount = 0; characterToSubstitute.index = 0; characterToSubstitute.unicode = k_EndOfText; m_FirstCharacterOfLine = 0; continue; } var ellipsisState = m_EllipsisInsertionCandidateStack.Pop(); i = RestoreWordWrappingState(ref ellipsisState, textInfo); i -= 1; m_CharacterCount -= 1; characterToSubstitute.index = m_CharacterCount; characterToSubstitute.unicode = k_HorizontalEllipsis; restoreCount += 1; continue; case TextOverflowMode.Linked: // Truncate remaining text characterToSubstitute.index = m_CharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; case TextOverflowMode.Page: // Add new page m_IsNewPage = true; InsertNewLine(i, baseScale, currentElementScale, currentEmScale, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender, generationSettings, textInfo); m_StartOfLineAscender = 0; m_LineOffset = 0; m_MaxAscender = 0; m_PageAscender = 0; m_PageNumber += 1; isStartOfNewLine = true; isFirstWordOfLine = true; continue; } } else { //if (generationSettings.autoSize && isFirstWordOfLine) //{ // // Handle Character Width Adjustments // #region Character Width Adjustments // if (m_CharWidthAdjDelta < m_CharWidthMaxAdj / 100 && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) // { // //m_AutoSizeIterationCount = 0; // float adjustedTextWidth = textWidth; // // Determine full width of the text // if (m_CharWidthAdjDelta > 0) // adjustedTextWidth /= 1f - m_CharWidthAdjDelta; // float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f) * (isJustifiedOrFlush ? 1.05f : 1.0f); // m_CharWidthAdjDelta += adjustmentDelta / adjustedTextWidth; // m_CharWidthAdjDelta = Mathf.Min(m_CharWidthAdjDelta, m_CharWidthMaxAdj / 100); // //Debug.Log("[" + m_AutoSizeIterationCount + "] Reducing Character Width by " + (m_CharWidthAdjDelta * 100) + "%"); // GenerateTextMesh(); // return; // } // #endregion //} // New line of text does not exceed vertical bounds of text container InsertNewLine(i, baseScale, currentElementScale, currentEmScale, boldSpacingAdjustment, characterSpacingAdjustment, widthOfTextArea, lineGap, ref isMaxVisibleDescenderSet, ref maxVisibleDescender, generationSettings, textInfo); isStartOfNewLine = true; isFirstWordOfLine = true; continue; } } else { if (generationSettings.autoSize && m_AutoSizeIterationCount < m_AutoSizeMaxIterationCount) { // Handle Character Width Adjustments #region Character Width Adjustments if (m_CharWidthAdjDelta < generationSettings.charWidthMaxAdj / 100) { float adjustedTextWidth = textWidth; // Determine full width of the text if (m_CharWidthAdjDelta > 0) adjustedTextWidth /= 1f - m_CharWidthAdjDelta; float adjustmentDelta = textWidth - (widthOfTextArea - 0.0001f); m_CharWidthAdjDelta += adjustmentDelta / adjustedTextWidth; m_CharWidthAdjDelta = Mathf.Min(m_CharWidthAdjDelta, generationSettings.charWidthMaxAdj / 100); return; } #endregion // Handle Text Auto-sizing resulting from text exceeding horizontal bounds. #region Text Exceeds Horizontal Bounds - Reducing Point Size if (m_FontSize > generationSettings.fontSizeMin) { // Adjust Point Size m_MaxFontSize = m_FontSize; float sizeDelta = Mathf.Max((m_FontSize - m_MinFontSize) / 2, 0.05f); m_FontSize -= sizeDelta; m_FontSize = Mathf.Max((int)(m_FontSize * 20 + 0.5f) / 20f, generationSettings.fontSizeMin); return; } #endregion } // Check Text Overflow Modes switch (generationSettings.overflowMode) { case TextOverflowMode.Overflow: case TextOverflowMode.ScrollRect: case TextOverflowMode.Masking: // Nothing happens as horizontal bounds are ignored in this mode. break; case TextOverflowMode.Truncate: i = RestoreWordWrappingState(ref m_SavedWordWrapState, textInfo); characterToSubstitute.index = testedCharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; case TextOverflowMode.Ellipsis: if (m_EllipsisInsertionCandidateStack.Count == 0) { i = -1; m_CharacterCount = 0; characterToSubstitute.index = 0; characterToSubstitute.unicode = k_EndOfText; m_FirstCharacterOfLine = 0; continue; } var ellipsisState = m_EllipsisInsertionCandidateStack.Pop(); i = RestoreWordWrappingState(ref ellipsisState, textInfo); i -= 1; m_CharacterCount -= 1; characterToSubstitute.index = m_CharacterCount; characterToSubstitute.unicode = k_HorizontalEllipsis; restoreCount += 1; continue; case TextOverflowMode.Linked: i = RestoreWordWrappingState(ref m_SavedWordWrapState, textInfo); // Truncate text the overflows the vertical bounds characterToSubstitute.index = m_CharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; } } } #endregion // Special handling of characters that are not ignored at the end of a line. if (isWhiteSpace) { textInfo.textElementInfo[m_CharacterCount].isVisible = false; m_LastVisibleCharacterOfLine = m_CharacterCount; m_LineVisibleSpaceCount = textInfo.lineInfo[m_LineNumber].spaceCount += 1; textInfo.lineInfo[m_LineNumber].marginLeft = marginLeft; textInfo.lineInfo[m_LineNumber].marginRight = marginRight; textInfo.spaceCount += 1; if (charCode == k_NoBreakSpace) textInfo.lineInfo[m_LineNumber].controlCharacterCount += 1; } else if (charCode == k_SoftHyphen) { textInfo.textElementInfo[m_CharacterCount].isVisible = false; } else { // Determine Vertex Color Color32 vertexColor; if (generationSettings.overrideRichTextColors) vertexColor = m_FontColor32; else vertexColor = m_HtmlColor; // Store Character & Sprite Vertex Information if (m_TextElementType == TextElementType.Character) { // Save Character Vertex Data SaveGlyphVertexInfo(padding, stylePadding, vertexColor, generationSettings, textInfo); } else if (m_TextElementType == TextElementType.Sprite) { SaveSpriteVertexInfo(vertexColor, generationSettings, textInfo); } if (isStartOfNewLine) { isStartOfNewLine = false; m_FirstVisibleCharacterOfLine = m_CharacterCount; } m_LineVisibleCharacterCount += 1; m_LastVisibleCharacterOfLine = m_CharacterCount; textInfo.lineInfo[m_LineNumber].marginLeft = marginLeft; textInfo.lineInfo[m_LineNumber].marginRight = marginRight; } } else { // Special handling for text overflow linked mode #region Check Vertical Bounds if (generationSettings.overflowMode == TextOverflowMode.Linked && (charCode == k_LineFeed || charCode == 11)) { float textHeight = m_MaxAscender - (m_MaxLineDescender - m_LineOffset) + (m_LineOffset > 0 && m_IsDrivenLineSpacing == false ? m_MaxLineAscender - m_StartOfLineAscender : 0); int testedCharacterCount = m_CharacterCount; if (textHeight > marginHeight + 0.0001f) { // Set isTextOverflowing and firstOverflowCharacterIndex if (m_FirstOverflowCharacterIndex == -1) m_FirstOverflowCharacterIndex = m_CharacterCount; i = RestoreWordWrappingState(ref m_SavedLastValidState, textInfo); // Truncate remaining text characterToSubstitute.index = testedCharacterCount; characterToSubstitute.unicode = k_EndOfText; continue; } } #endregion // Track # of spaces per line which is used for line justification. if ((charCode == k_LineFeed || charCode == k_VerticalTab || charCode == k_NoBreakSpace || charCode == k_FigureSpace || charCode == k_LineSeparator || charCode == k_ParagraphSeparator || char.IsSeparator((char)charCode)) && charCode != k_SoftHyphen && charCode != k_ZeroWidthSpace && charCode != k_WordJoiner) { textInfo.lineInfo[m_LineNumber].spaceCount += 1; textInfo.spaceCount += 1; } // Special handling for control characters like <NBSP> if (charCode == k_NoBreakSpace) textInfo.lineInfo[m_LineNumber].controlCharacterCount += 1; } #endregion Handle Visible Characters // Tracking of potential insertion positions for Ellipsis character #region Track Potential Insertion Location for Ellipsis if (generationSettings.overflowMode == TextOverflowMode.Ellipsis && (isInjectedCharacter == false || charCode == k_HyphenMinus)) { float fontScale = m_CurrentFontSize / m_Ellipsis.fontAsset.m_FaceInfo.pointSize * m_Ellipsis.fontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f); float scale = fontScale * m_FontScaleMultiplier * m_Ellipsis.character.m_Scale * m_Ellipsis.character.m_Glyph.scale; float marginLeft = m_MarginLeft; float marginRight = m_MarginRight; // Use the scale and margins of the previous character if Line Feed (LF) is not the first character of a line. if (charCode == 0x0A && m_CharacterCount != m_FirstCharacterOfLine) { fontScale = textInfo.textElementInfo[m_CharacterCount - 1].pointSize / m_Ellipsis.fontAsset.m_FaceInfo.pointSize * m_Ellipsis.fontAsset.m_FaceInfo.scale * (generationSettings.isOrthographic ? 1 : 0.1f); scale = fontScale * m_FontScaleMultiplier * m_Ellipsis.character.m_Scale * m_Ellipsis.character.m_Glyph.scale; marginLeft = textInfo.lineInfo[m_LineNumber].marginLeft; marginRight = textInfo.lineInfo[m_LineNumber].marginRight; } float textHeight = m_MaxAscender - (m_MaxLineDescender - m_LineOffset) + (m_LineOffset > 0 && m_IsDrivenLineSpacing == false ? m_MaxLineAscender - m_StartOfLineAscender : 0); float textWidth = Mathf.Abs(m_XAdvance) + (!generationSettings.isRightToLeft ? m_Ellipsis.character.m_Glyph.metrics.horizontalAdvance : 0) * (1 - m_CharWidthAdjDelta) * scale; float widthOfTextAreaForEllipsis = m_Width != -1 ? Mathf.Min(marginWidth + 0.0001f - marginLeft - marginRight, m_Width) : marginWidth + 0.0001f - marginLeft - marginRight; if (textWidth < widthOfTextAreaForEllipsis) { SaveWordWrappingState(ref m_SavedEllipsisState, i, m_CharacterCount, textInfo); m_EllipsisInsertionCandidateStack.Push(m_SavedEllipsisState); } } #endregion // Store Rectangle positions for each Character. #region Store Character Data textInfo.textElementInfo[m_CharacterCount].lineNumber = m_LineNumber; textInfo.textElementInfo[m_CharacterCount].pageNumber = m_PageNumber; if (charCode != k_LineFeed && charCode != k_VerticalTab && charCode != k_CarriageReturn && isInjectedCharacter == false /* && charCode != k_HorizontalEllipsis */ || textInfo.lineInfo[m_LineNumber].characterCount == 1) textInfo.lineInfo[m_LineNumber].alignment = m_LineJustification; #endregion Store Character Data // Handle xAdvance & Tabulation Stops. Tab stops at every 25% of Font Size. #region XAdvance, Tabulation & Stops if (charCode != k_ZeroWidthSpace) { if (charCode == k_Tab) { float tabSize = m_CurrentFontAsset.m_FaceInfo.tabWidth * m_CurrentFontAsset.tabMultiple * currentElementScale; float tabs = Mathf.Ceil(m_XAdvance / tabSize) * tabSize; m_XAdvance = tabs > m_XAdvance ? tabs : m_XAdvance + tabSize; } else if (m_MonoSpacing != 0) { float monoAdjustment; if (m_DuoSpace && (charCode == '.' || charCode == ':' || charCode == ',')) monoAdjustment = m_MonoSpacing / 2 - monoAdvance; else monoAdjustment = m_MonoSpacing - monoAdvance; m_XAdvance += (monoAdjustment + ((m_CurrentFontAsset.regularStyleSpacing + characterSpacingAdjustment) * currentEmScale) + m_CSpacing) * (1 - m_CharWidthAdjDelta); if (isWhiteSpace || charCode == k_ZeroWidthSpace) m_XAdvance += generationSettings.wordSpacing * currentEmScale; } else if (generationSettings.isRightToLeft) { m_XAdvance -= ((glyphAdjustments.xAdvance * currentElementScale + (m_CurrentFontAsset.regularStyleSpacing + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_CSpacing) * (1 - m_CharWidthAdjDelta)); if (isWhiteSpace || charCode == k_ZeroWidthSpace) m_XAdvance -= generationSettings.wordSpacing * currentEmScale; } else { m_XAdvance += ((currentGlyphMetrics.horizontalAdvance * m_FXScale.x + glyphAdjustments.xAdvance) * currentElementScale + (m_CurrentFontAsset.regularStyleSpacing + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_CSpacing) * (1 - m_CharWidthAdjDelta); if (isWhiteSpace || charCode == k_ZeroWidthSpace) m_XAdvance += generationSettings.wordSpacing * currentEmScale; } } // Store xAdvance information textInfo.textElementInfo[m_CharacterCount].xAdvance = m_XAdvance; #endregion Tabulation & Stops // Handle Carriage Return #region Carriage Return if (charCode == k_CarriageReturn) { m_XAdvance = 0 + m_TagIndent; } #endregion Carriage Return // Tracking of text overflow page mode #region Save PageInfo if (generationSettings.overflowMode == TextOverflowMode.Page && charCode != k_LineFeed && charCode != k_VerticalTab && charCode != k_CarriageReturn && charCode != k_LineSeparator && charCode != k_LineSeparator) { // Check if we need to increase allocations for the pageInfo array. if (m_PageNumber + 1 > textInfo.pageInfo.Length) TextInfo.Resize(ref textInfo.pageInfo, m_PageNumber + 1, true); textInfo.pageInfo[m_PageNumber].ascender = m_PageAscender; textInfo.pageInfo[m_PageNumber].descender = m_MaxDescender < textInfo.pageInfo[m_PageNumber].descender ? m_MaxDescender : textInfo.pageInfo[m_PageNumber].descender; if (m_IsNewPage) { m_IsNewPage = false; textInfo.pageInfo[m_PageNumber].firstCharacterIndex = m_CharacterCount; } // Last index textInfo.pageInfo[m_PageNumber].lastCharacterIndex = m_CharacterCount; } #endregion Save PageInfo // Handle Line Spacing Adjustments + Word Wrapping & special case for last line. #region Check for Line Feed and Last Character if (charCode == k_LineFeed || charCode == k_VerticalTab || charCode == k_EndOfText || charCode == k_LineSeparator || charCode == k_LineSeparator || (charCode == k_HyphenMinus && isInjectedCharacter) || m_CharacterCount == totalCharacterCount - 1) { // Adjust current line spacing (if necessary) before inserting new line float baselineAdjustmentDelta = m_MaxLineAscender - m_StartOfLineAscender; if (m_LineOffset > 0 && Math.Abs(baselineAdjustmentDelta) > 0.01f && m_IsDrivenLineSpacing == false && !m_IsNewPage) { TextGeneratorUtilities.AdjustLineOffset(m_FirstCharacterOfLine, m_CharacterCount, baselineAdjustmentDelta, textInfo); m_MaxDescender -= baselineAdjustmentDelta; m_LineOffset += baselineAdjustmentDelta; // Adjust saved ellipsis state only if we are adjusting the same line number if (m_SavedEllipsisState.lineNumber == m_LineNumber) { m_SavedEllipsisState = m_EllipsisInsertionCandidateStack.Pop(); m_SavedEllipsisState.startOfLineAscender += baselineAdjustmentDelta; m_SavedEllipsisState.lineOffset += baselineAdjustmentDelta; m_EllipsisInsertionCandidateStack.Push(m_SavedEllipsisState); } } m_IsNewPage = false; // Calculate lineAscender & make sure if last character is superscript or subscript that we check that as well. float lineAscender = m_MaxLineAscender - m_LineOffset; float lineDescender = m_MaxLineDescender - m_LineOffset; // Update maxDescender and maxVisibleDescender m_MaxDescender = m_MaxDescender < lineDescender ? m_MaxDescender : lineDescender; if (!isMaxVisibleDescenderSet) maxVisibleDescender = m_MaxDescender; if (generationSettings.useMaxVisibleDescender && (m_CharacterCount >= generationSettings.maxVisibleCharacters || m_LineNumber >= generationSettings.maxVisibleLines)) isMaxVisibleDescenderSet = true; // Save Line Information textInfo.lineInfo[m_LineNumber].firstCharacterIndex = m_FirstCharacterOfLine; textInfo.lineInfo[m_LineNumber].firstVisibleCharacterIndex = m_FirstVisibleCharacterOfLine = m_FirstCharacterOfLine > m_FirstVisibleCharacterOfLine ? m_FirstCharacterOfLine : m_FirstVisibleCharacterOfLine; textInfo.lineInfo[m_LineNumber].lastCharacterIndex = m_LastCharacterOfLine = m_CharacterCount; textInfo.lineInfo[m_LineNumber].lastVisibleCharacterIndex = m_LastVisibleCharacterOfLine = m_LastVisibleCharacterOfLine < m_FirstVisibleCharacterOfLine ? m_FirstVisibleCharacterOfLine : m_LastVisibleCharacterOfLine; int firstCharacterIndex = m_FirstVisibleCharacterOfLine; int lastCharacterIndex = m_LastVisibleCharacterOfLine; if (generationSettings.textWrappingMode == TextWrappingMode.PreserveWhitespace || generationSettings.textWrappingMode == TextWrappingMode.PreserveWhitespaceNoWrap) { // If last non visible character is /n it will have a xAdvance of 0 if (textInfo.textElementInfo[m_LastCharacterOfLine].xAdvance != 0) { firstCharacterIndex = m_FirstCharacterOfLine; lastCharacterIndex = m_LastCharacterOfLine; } } textInfo.lineInfo[m_LineNumber].characterCount = textInfo.lineInfo[m_LineNumber].lastCharacterIndex - textInfo.lineInfo[m_LineNumber].firstCharacterIndex + 1; textInfo.lineInfo[m_LineNumber].visibleCharacterCount = m_LineVisibleCharacterCount; textInfo.lineInfo[m_LineNumber].lineExtents.min = new Vector2(textInfo.textElementInfo[firstCharacterIndex].bottomLeft.x, lineDescender); textInfo.lineInfo[m_LineNumber].lineExtents.max = new Vector2(textInfo.textElementInfo[lastCharacterIndex].topRight.x, lineAscender); // UUM-46147: For IMGUI line length should include xAdvance for backward compatibility textInfo.lineInfo[m_LineNumber].length = generationSettings.isIMGUI ? textInfo.textElementInfo[lastCharacterIndex].xAdvance : textInfo.lineInfo[m_LineNumber].lineExtents.max.x - (padding * currentElementScale); textInfo.lineInfo[m_LineNumber].width = widthOfTextArea; if (textInfo.lineInfo[m_LineNumber].characterCount == 1) textInfo.lineInfo[m_LineNumber].alignment = m_LineJustification; float maxAdvanceOffset = ((m_CurrentFontAsset.regularStyleSpacing + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_CSpacing) * (1 - m_CharWidthAdjDelta); if (textInfo.textElementInfo[m_LastVisibleCharacterOfLine].isVisible) textInfo.lineInfo[m_LineNumber].maxAdvance = textInfo.textElementInfo[m_LastVisibleCharacterOfLine].xAdvance + (generationSettings.isRightToLeft ? maxAdvanceOffset : -maxAdvanceOffset); else textInfo.lineInfo[m_LineNumber].maxAdvance = textInfo.textElementInfo[m_LastCharacterOfLine].xAdvance + (generationSettings.isRightToLeft ? maxAdvanceOffset : -maxAdvanceOffset); textInfo.lineInfo[m_LineNumber].baseline = 0 - m_LineOffset; textInfo.lineInfo[m_LineNumber].ascender = lineAscender; textInfo.lineInfo[m_LineNumber].descender = lineDescender; textInfo.lineInfo[m_LineNumber].lineHeight = lineAscender - lineDescender + lineGap * baseScale; // Add new line if not last line or character. if (charCode == k_LineFeed || charCode == k_VerticalTab|| charCode == k_HyphenMinus || charCode == k_LineSeparator || charCode == k_ParagraphSeparator) { // Store the state of the line before starting on the new line. SaveWordWrappingState(ref m_SavedLineState, i, m_CharacterCount, textInfo); m_LineNumber += 1; isStartOfNewLine = true; ignoreNonBreakingSpace = false; isFirstWordOfLine = true; m_FirstCharacterOfLine = m_CharacterCount + 1; m_LineVisibleCharacterCount = 0; m_LineVisibleSpaceCount = 0; // Check to make sure Array is large enough to hold a new line. if (m_LineNumber >= textInfo.lineInfo.Length) TextGeneratorUtilities.ResizeLineExtents(m_LineNumber, textInfo); float lastVisibleAscender = textInfo.textElementInfo[m_CharacterCount].adjustedAscender; // Apply Line Spacing with special handling for VT char(11) if (m_LineHeight == k_FloatUnset) { float lineOffsetDelta = 0 - m_MaxLineDescender + lastVisibleAscender + (lineGap + m_LineSpacingDelta) * baseScale + (generationSettings.lineSpacing + (charCode == k_LineFeed || charCode == k_ParagraphSeparator ? generationSettings.paragraphSpacing : 0)) * currentEmScale; m_LineOffset += lineOffsetDelta; m_IsDrivenLineSpacing = false; } else { m_LineOffset += m_LineHeight + (generationSettings.lineSpacing + (charCode == k_LineFeed || charCode == k_ParagraphSeparator ? generationSettings.paragraphSpacing : 0)) * currentEmScale; m_IsDrivenLineSpacing = true; } m_MaxLineAscender = TextGeneratorUtilities.largeNegativeFloat; m_MaxLineDescender = TextGeneratorUtilities.largePositiveFloat; m_StartOfLineAscender = lastVisibleAscender; m_XAdvance = 0 + m_TagLineIndent + m_TagIndent; SaveWordWrappingState(ref m_SavedWordWrapState, i, m_CharacterCount, textInfo); SaveWordWrappingState(ref m_SavedLastValidState, i, m_CharacterCount, textInfo); m_CharacterCount += 1; continue; } // If End of Text if (charCode == k_EndOfText) i = m_TextProcessingArray.Length; } #endregion Check for Linefeed or Last Character // Track extents of the text #region Track Text Extents // Determine the bounds of the Mesh. if (textInfo.textElementInfo[m_CharacterCount].isVisible) { m_MeshExtents.min.x = Mathf.Min(m_MeshExtents.min.x, textInfo.textElementInfo[m_CharacterCount].bottomLeft.x); m_MeshExtents.min.y = Mathf.Min(m_MeshExtents.min.y, textInfo.textElementInfo[m_CharacterCount].bottomLeft.y); m_MeshExtents.max.x = Mathf.Max(m_MeshExtents.max.x, textInfo.textElementInfo[m_CharacterCount].topRight.x); m_MeshExtents.max.y = Mathf.Max(m_MeshExtents.max.y, textInfo.textElementInfo[m_CharacterCount].topRight.y); //m_MeshExtents.min = new Vector2(Mathf.Min(m_MeshExtents.min.x, textInfo.textElementInfo[m_CharacterCount].bottomLeft.x), Mathf.Min(m_MeshExtents.min.y, textInfo.textElementInfo[m_CharacterCount].bottomLeft.y)); //m_MeshExtents.max = new Vector2(Mathf.Max(m_MeshExtents.max.x, textInfo.textElementInfo[m_CharacterCount].topRight.x), Mathf.Max(m_MeshExtents.max.y, textInfo.textElementInfo[m_CharacterCount].topRight.y)); } #endregion Track Text Extents // Save State of Mesh Creation for handling of Word Wrapping #region Save Word Wrapping State if ((wordWrap != TextWrappingMode.NoWrap && wordWrap != TextWrappingMode.PreserveWhitespaceNoWrap) || generationSettings.overflowMode == TextOverflowMode.Truncate || generationSettings.overflowMode == TextOverflowMode.Ellipsis || generationSettings.overflowMode == TextOverflowMode.Linked) { bool shouldSaveHardLineBreak = false; bool shouldSaveSoftLineBreak = false; if ((isWhiteSpace || charCode == k_ZeroWidthSpace || (charCode == k_HyphenMinus && (m_CharacterCount <= 0 || char.IsWhiteSpace((char)textInfo.textElementInfo[m_CharacterCount - 1].character) == false)) || charCode == k_SoftHyphen) && (!m_IsNonBreakingSpace || ignoreNonBreakingSpace) && charCode != k_NoBreakSpace && charCode != k_FigureSpace && charCode != k_NonBreakingHyphen && charCode != k_NarrowNoBreakSpace && charCode != k_WordJoiner) { isFirstWordOfLine = false; shouldSaveHardLineBreak = true; //Reset soft line breaking point since we now have a valid hard break point. m_SavedSoftLineBreakState.previousWordBreak = -1; } // Handling for East Asian scripts else if (m_IsNonBreakingSpace == false && (TextGeneratorUtilities.IsHangul(charCode) && textSettings.lineBreakingRules.useModernHangulLineBreakingRules == false || TextGeneratorUtilities.IsCJK(charCode))) { bool isCurrentLeadingCharacter = textSettings.lineBreakingRules.leadingCharactersLookup.Contains((uint)charCode); bool isNextFollowingCharacter = m_CharacterCount < totalCharacterCount - 1 && textSettings.lineBreakingRules.followingCharactersLookup.Contains((uint)textInfo.textElementInfo[m_CharacterCount + 1].character); if (isCurrentLeadingCharacter == false) { if (isNextFollowingCharacter == false) { isFirstWordOfLine = false; shouldSaveHardLineBreak = true; } if (isFirstWordOfLine) { // Special handling for non-breaking space and soft line breaks if (isWhiteSpace) shouldSaveSoftLineBreak = true; shouldSaveHardLineBreak = true; } } else { if (isFirstWordOfLine && isFirstCharacterOfLine) { // Special handling for non-breaking space and soft line breaks if (isWhiteSpace) shouldSaveSoftLineBreak = true; shouldSaveHardLineBreak = true; } } } // Special handling for Latin characters followed by a CJK character. else if (m_IsNonBreakingSpace == false && m_CharacterCount + 1 < totalCharacterCount && TextGeneratorUtilities.IsCJK(textInfo.textElementInfo[m_CharacterCount + 1].character)) { shouldSaveHardLineBreak = true; } else if (isFirstWordOfLine) { // Special handling for non-breaking space and soft line breaks if (isWhiteSpace && charCode != k_NoBreakSpace || (charCode == k_SoftHyphen && isSoftHyphenIgnored == false)) shouldSaveSoftLineBreak = true; shouldSaveHardLineBreak = true; } // Save potential Hard lines break if (shouldSaveHardLineBreak) SaveWordWrappingState(ref m_SavedWordWrapState, i, m_CharacterCount, textInfo); // Save potential Soft line break if (shouldSaveSoftLineBreak) SaveWordWrappingState(ref m_SavedSoftLineBreakState, i, m_CharacterCount, textInfo); // k_SaveProcessingStatesMarker.End(); } #endregion Save Word Wrapping State // Consider only saving state on base glyphs SaveWordWrappingState(ref m_SavedLastValidState, i, m_CharacterCount, textInfo); m_CharacterCount += 1; } } void InsertNewLine(int i, float baseScale, float currentElementScale, float currentEmScale, float boldSpacingAdjustment, float characterSpacingAdjustment, float width, float lineGap, ref bool isMaxVisibleDescenderSet, ref float maxVisibleDescender, TextGenerationSettings generationSettings, TextInfo textInfo) { // Adjust line spacing if necessary float baselineAdjustmentDelta = m_MaxLineAscender - m_StartOfLineAscender; if (m_LineOffset > 0 && Math.Abs(baselineAdjustmentDelta) > 0.01f && m_IsDrivenLineSpacing == false && !m_IsNewPage) { TextGeneratorUtilities.AdjustLineOffset(m_FirstCharacterOfLine, m_CharacterCount, baselineAdjustmentDelta, textInfo); m_MaxDescender -= baselineAdjustmentDelta; m_LineOffset += baselineAdjustmentDelta; } // Calculate lineAscender & make sure if last character is superscript or subscript that we check that as well. float lineAscender = m_MaxLineAscender - m_LineOffset; float lineDescender = m_MaxLineDescender - m_LineOffset; // Update maxDescender and maxVisibleDescender m_MaxDescender = m_MaxDescender < lineDescender ? m_MaxDescender : lineDescender; if (!isMaxVisibleDescenderSet) maxVisibleDescender = m_MaxDescender; if (generationSettings.useMaxVisibleDescender && (m_CharacterCount >= generationSettings.maxVisibleCharacters || m_LineNumber >= generationSettings.maxVisibleLines)) isMaxVisibleDescenderSet = true; // Track & Store lineInfo for the new line textInfo.lineInfo[m_LineNumber].firstCharacterIndex = m_FirstCharacterOfLine; textInfo.lineInfo[m_LineNumber].firstVisibleCharacterIndex = m_FirstVisibleCharacterOfLine = m_FirstCharacterOfLine > m_FirstVisibleCharacterOfLine ? m_FirstCharacterOfLine : m_FirstVisibleCharacterOfLine; textInfo.lineInfo[m_LineNumber].lastCharacterIndex = m_LastCharacterOfLine = m_CharacterCount - 1 > 0 ? m_CharacterCount - 1 : 0; textInfo.lineInfo[m_LineNumber].lastVisibleCharacterIndex = m_LastVisibleCharacterOfLine = m_LastVisibleCharacterOfLine < m_FirstVisibleCharacterOfLine ? m_FirstVisibleCharacterOfLine : m_LastVisibleCharacterOfLine; textInfo.lineInfo[m_LineNumber].characterCount = textInfo.lineInfo[m_LineNumber].lastCharacterIndex - textInfo.lineInfo[m_LineNumber].firstCharacterIndex + 1; textInfo.lineInfo[m_LineNumber].visibleCharacterCount = m_LineVisibleCharacterCount; textInfo.lineInfo[m_LineNumber].lineExtents.min = new Vector2(textInfo.textElementInfo[m_FirstVisibleCharacterOfLine].bottomLeft.x, lineDescender); textInfo.lineInfo[m_LineNumber].lineExtents.max = new Vector2(textInfo.textElementInfo[m_LastVisibleCharacterOfLine].topRight.x, lineAscender); // UUM-46147: For IMGUI line length should include xAdvance for backward compatibility textInfo.lineInfo[m_LineNumber].length = generationSettings.isIMGUI ? textInfo.textElementInfo[m_LastVisibleCharacterOfLine].xAdvance : textInfo.lineInfo[m_LineNumber].lineExtents.max.x; textInfo.lineInfo[m_LineNumber].width = width; float glyphAdjustment = textInfo.textElementInfo[m_LastVisibleCharacterOfLine].adjustedHorizontalAdvance; float maxAdvanceOffset = (glyphAdjustment * currentElementScale + (m_CurrentFontAsset.regularStyleSpacing + characterSpacingAdjustment + boldSpacingAdjustment) * currentEmScale + m_CSpacing) * (1 - generationSettings.charWidthMaxAdj); float adjustedHorizontalAdvance = textInfo.lineInfo[m_LineNumber].maxAdvance = textInfo.textElementInfo[m_LastVisibleCharacterOfLine].xAdvance + (generationSettings.isRightToLeft ? maxAdvanceOffset : -maxAdvanceOffset); textInfo.textElementInfo[m_LastVisibleCharacterOfLine].xAdvance = adjustedHorizontalAdvance; textInfo.lineInfo[m_LineNumber].baseline = 0 - m_LineOffset; textInfo.lineInfo[m_LineNumber].ascender = lineAscender; textInfo.lineInfo[m_LineNumber].descender = lineDescender; textInfo.lineInfo[m_LineNumber].lineHeight = lineAscender - lineDescender + lineGap * baseScale; m_FirstCharacterOfLine = m_CharacterCount; // Store first character of the next line. m_LineVisibleCharacterCount = 0; m_LineVisibleSpaceCount = 0; // Store the state of the line before starting on the new line. SaveWordWrappingState(ref m_SavedLineState, i, m_CharacterCount - 1, textInfo); m_LineNumber += 1; // Check to make sure Array is large enough to hold a new line. if (m_LineNumber >= textInfo.lineInfo.Length) TextGeneratorUtilities.ResizeLineExtents(m_LineNumber, textInfo); // Apply Line Spacing based on scale of the last character of the line. if (m_LineHeight == k_FloatUnset) { float ascender = textInfo.textElementInfo[m_CharacterCount].adjustedAscender; float lineOffsetDelta = 0 - m_MaxLineDescender + ascender + (lineGap + m_LineSpacingDelta) * baseScale + generationSettings.lineSpacing * currentEmScale; m_LineOffset += lineOffsetDelta; m_StartOfLineAscender = ascender; } else { m_LineOffset += m_LineHeight + generationSettings.lineSpacing * currentEmScale; } m_MaxLineAscender = TextGeneratorUtilities.largeNegativeFloat; m_MaxLineDescender = TextGeneratorUtilities.largePositiveFloat; m_XAdvance = 0 + m_TagIndent; } } }
UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorParsing.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngine/Managed/TextGenerator/TextGeneratorParsing.cs", "repo_id": "UnityCsReference", "token_count": 55203 }
438
// 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.IO; using UnityEngine; using UnityEngine.TextCore.Text; using UnityEngine.TextCore.LowLevel; using GlyphRect = UnityEngine.TextCore.GlyphRect; namespace UnityEditor.TextCore.Text { internal static class FontAsset_CreationMenu { /// <summary> /// Enables the creation of a font asset with unique face info attributes but sharing the same atlas texture and material. /// </summary> [MenuItem("Assets/Create/Text Core/Font Asset Variant", false, 105)] internal static void CreateFontAssetVariant() { Object target = Selection.activeObject; // Make sure the selection is a font file if (target == null || target.GetType() != typeof(FontAsset)) { Debug.LogWarning("A Font Asset must first be selected in order to create a Font Asset Variant."); return; } FontAsset sourceFontAsset = (FontAsset)target; string sourceFontFilePath = AssetDatabase.GetAssetPath(target); string folderPath = Path.GetDirectoryName(sourceFontFilePath); string assetName = Path.GetFileNameWithoutExtension(sourceFontFilePath); string newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " - Variant.asset"); // Set Texture and Material reference to the source font asset. FontAsset fontAsset = ScriptableObject.Instantiate<FontAsset>(sourceFontAsset); AssetDatabase.CreateAsset(fontAsset, newAssetFilePathWithName); fontAsset.atlasPopulationMode = AtlasPopulationMode.Static; // Initialize array for the font atlas textures. fontAsset.atlasTextures = sourceFontAsset.atlasTextures; fontAsset.material = sourceFontAsset.material; // Not sure if this is still necessary in newer versions of Unity. EditorUtility.SetDirty(fontAsset); AssetDatabase.SaveAssets(); } [MenuItem("Assets/Create/Text Core/Font Asset/SDF", false, 100)] static void CreateFontAssetSDF() { CreateFontAsset(GlyphRenderMode.SDFAA); } [MenuItem("Assets/Create/Text Core/Font Asset/Bitmap", false, 105)] static void CreateFontAssetBitmap() { CreateFontAsset(GlyphRenderMode.SMOOTH); } [MenuItem("Assets/Create/Text Core/Font Asset/Color", false, 110)] static void CreateFontAssetColor() { CreateFontAsset(GlyphRenderMode.COLOR); } static void CreateFontAsset(GlyphRenderMode renderMode) { Object[] targets = Selection.objects; if (targets == null) { Debug.LogWarning("A Font file must first be selected in order to create a Font Asset."); return; } for (int i = 0; i < targets.Length; i++) { Object target = targets[i]; // Make sure the selection is a font file if (target == null || target.GetType() != typeof(Font)) { Debug.LogWarning("Selected Object [" + target?.name + "] is not a Font file. A Font file must be selected in order to create a Font Asset.", target); continue; } CreateFontAssetFromSelectedObject(target, renderMode); } } static void CreateFontAssetFromSelectedObject(Object target, GlyphRenderMode renderMode) { Font font = (Font)target; string sourceFontFilePath = AssetDatabase.GetAssetPath(target); string folderPath = Path.GetDirectoryName(sourceFontFilePath); string assetName = Path.GetFileNameWithoutExtension(sourceFontFilePath); string newAssetFilePathWithName; ; switch (renderMode) { case GlyphRenderMode.SMOOTH: newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " Bitmap.asset"); break; case GlyphRenderMode.COLOR: newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " Color.asset"); break; case GlyphRenderMode.SDFAA: default: newAssetFilePathWithName = AssetDatabase.GenerateUniqueAssetPath(folderPath + "/" + assetName + " SDF.asset"); break; } // Initialize FontEngine FontEngine.InitializeFontEngine(); // Load Font Face if (FontEngine.LoadFontFace(font, 90) != FontEngineError.Success) { Debug.LogWarning("Unable to load font face for [" + font.name + "]. Make sure \"Include Font Data\" is enabled in the Font Import Settings.", font); return; } // Create new Font Asset FontAsset fontAsset = ScriptableObject.CreateInstance<FontAsset>(); AssetDatabase.CreateAsset(fontAsset, newAssetFilePathWithName); fontAsset.version = "1.1.0"; fontAsset.faceInfo = FontEngine.GetFaceInfo(); // Set font reference and GUID fontAsset.sourceFontFile = font; fontAsset.m_SourceFontFileGUID = AssetDatabase.AssetPathToGUID(sourceFontFilePath); fontAsset.m_SourceFontFile_EditorRef = font; fontAsset.atlasPopulationMode = AtlasPopulationMode.Dynamic; //fontAsset.clearDynamicDataOnBuild = TextSettings.clearDynamicDataOnBuild; // Default atlas resolution is 1024 x 1024. fontAsset.atlasTextures = new Texture2D[1]; int atlasWidth = fontAsset.atlasWidth = 1024; int atlasHeight = fontAsset.atlasHeight = 1024; int atlasPadding = fontAsset.atlasPadding = 9; Texture2D texture; Material mat; Shader shader; int packingModifier; switch (renderMode) { case GlyphRenderMode.SMOOTH: fontAsset.atlasRenderMode = GlyphRenderMode.SMOOTH; texture = new Texture2D(1, 1, TextureFormat.Alpha8, false); shader = TextShaderUtilities.ShaderRef_MobileBitmap; packingModifier = 0; mat = new Material(shader); break; case GlyphRenderMode.COLOR: fontAsset.atlasRenderMode = GlyphRenderMode.COLOR; texture = new Texture2D(1, 1, TextureFormat.RGBA32, false); shader = TextShaderUtilities.ShaderRef_Sprite; packingModifier = 0; mat = new Material(shader); break; case GlyphRenderMode.SDFAA: default: fontAsset.atlasRenderMode = GlyphRenderMode.SDFAA; texture = new Texture2D(1, 1, TextureFormat.Alpha8, false); shader = TextShaderUtilities.ShaderRef_MobileSDF; packingModifier = 1; mat = new Material(shader); mat.SetFloat(TextShaderUtilities.ID_GradientScale, atlasPadding + packingModifier); mat.SetFloat(TextShaderUtilities.ID_WeightNormal, fontAsset.regularStyleWeight); mat.SetFloat(TextShaderUtilities.ID_WeightBold, fontAsset.boldStyleWeight); break; } texture.name = assetName + " Atlas"; mat.name = texture.name + " Material"; fontAsset.atlasTextures[0] = texture; AssetDatabase.AddObjectToAsset(texture, fontAsset); fontAsset.freeGlyphRects = new List<GlyphRect>() { new GlyphRect(0, 0, atlasWidth - packingModifier, atlasHeight - packingModifier) }; fontAsset.usedGlyphRects = new List<GlyphRect>(); mat.SetTexture(TextShaderUtilities.ID_MainTex, texture); mat.SetFloat(TextShaderUtilities.ID_TextureWidth, atlasWidth); mat.SetFloat(TextShaderUtilities.ID_TextureHeight, atlasHeight); fontAsset.material = mat; AssetDatabase.AddObjectToAsset(mat, fontAsset); // Add Font Asset Creation Settings fontAsset.fontAssetCreationEditorSettings = new FontAssetCreationEditorSettings(fontAsset.m_SourceFontFileGUID, fontAsset.faceInfo.pointSize, 0, atlasPadding, 0, 1024, 1024, 7, string.Empty, (int)GlyphRenderMode.SDFAA); // Not sure if this is still necessary in newer versions of Unity. EditorUtility.SetDirty(fontAsset); AssetDatabase.SaveAssets(); } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetCreationMenu.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/FontAssetCreationMenu.cs", "repo_id": "UnityCsReference", "token_count": 4045 }
439
// 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(UnicodeLineBreakingRules))] internal class UnicodeLineBreakingRulesPropertyDrawer : PropertyDrawer { static readonly GUIContent s_KoreanSpecificRules = new GUIContent("Use Modern Rules", "Determines if traditional or modern line breaking rules will be used to control line breaking. Traditional line breaking rules use the Leading and Following Character rules whereas Modern uses spaces for line breaking."); public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty prop_LeadingCharactersAsset = property.FindPropertyRelative("m_LeadingCharacters"); SerializedProperty prop_FollowingCharactersAsset = property.FindPropertyRelative("m_FollowingCharacters"); SerializedProperty prop_UseModernHangulLineBreakingRules = property.FindPropertyRelative("m_UseModernHangulLineBreakingRules"); // We get Rect since a valid position may not be provided by the caller. Rect rect = new Rect(position.x, position.y, position.width, 49); EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, 18), prop_LeadingCharactersAsset); EditorGUI.PropertyField(new Rect(rect.x, rect.y + 20, rect.width, 18), prop_FollowingCharactersAsset); EditorGUI.LabelField(new Rect(rect.x, rect.y + 45, rect.width, 18), new GUIContent("Korean Line Breaking Rules"), EditorStyles.boldLabel); EditorGUI.indentLevel += 1; EditorGUI.PropertyField(new Rect(rect.x, rect.y + 65, rect.width, 18), prop_UseModernHangulLineBreakingRules, s_KoreanSpecificRules); EditorGUI.indentLevel -= 1; } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 80f; } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/PropertyDrawers/UnicodeLineBreakingRulesPropertyDrawer.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/PropertyDrawers/UnicodeLineBreakingRulesPropertyDrawer.cs", "repo_id": "UnityCsReference", "token_count": 706 }
440
// 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.TextCore.Text; using UnityEditorInternal; namespace UnityEditor.TextCore.Text { [CustomEditor(typeof(TextSettings))] public class TextSettingsEditor : Editor { internal class Styles { public static readonly GUIContent defaultFontAssetLabel = new GUIContent("Default Font Asset", "The Font Asset that will be assigned by default to newly created text objects when no Font Asset is specified."); public static readonly GUIContent defaultFontAssetPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Font Assets and Material Presets are located.\nExample \"Fonts & Materials/\""); public static readonly GUIContent fallbackFontAssetsLabel = new GUIContent("Font Assets Fallback", "The Font Assets that will be searched recursively to locate characters missing from the current font asset."); public static readonly GUIContent fallbackFontAssetsListLabel = new GUIContent("Font Assets Fallback List", "The Font Assets that will be searched recursively to locate characters missing from the current font asset."); public static readonly GUIContent fallbackMaterialSettingsLabel = new GUIContent("Fallback Material Settings"); public static readonly GUIContent matchMaterialPresetLabel = new GUIContent("Match Material Presets"); public static readonly GUIContent containerDefaultSettingsLabel = new GUIContent("Text Container Default Settings"); public static readonly GUIContent textMeshProLabel = new GUIContent("TextMeshPro"); public static readonly GUIContent textMeshProUiLabel = new GUIContent("TextMeshPro UI"); public static readonly GUIContent enableRaycastTarget = new GUIContent("Enable Raycast Target"); public static readonly GUIContent autoSizeContainerLabel = new GUIContent("Auto Size Text Container", "Set the size of the text container to match the text."); public static readonly GUIContent textComponentDefaultSettingsLabel = new GUIContent("Text Component Default Settings"); public static readonly GUIContent defaultFontSize = new GUIContent("Default Font Size"); public static readonly GUIContent autoSizeRatioLabel = new GUIContent("Text Auto Size Ratios"); public static readonly GUIContent minLabel = new GUIContent("Min"); public static readonly GUIContent maxLabel = new GUIContent("Max"); public static readonly GUIContent textWrappingModeLabel = new GUIContent("Text Wrapping Mode"); public static readonly GUIContent kerningLabel = new GUIContent("Kerning"); public static readonly GUIContent extraPaddingLabel = new GUIContent("Extra Padding"); public static readonly GUIContent tintAllSpritesLabel = new GUIContent("Tint All Sprites"); public static readonly GUIContent parseEscapeCharactersLabel = new GUIContent("Parse Escape Sequence"); public static readonly GUIContent dynamicFontSystemSettingsLabel = new GUIContent("Dynamic Font System Settings"); // public static readonly GUIContent getFontFeaturesAtRuntime = new GUIContent("Get Font Features at Runtime", "Determines if Glyph Adjustment Data will be retrieved from font files at runtime when new characters and glyphs are added to font assets."); public static readonly GUIContent dynamicAtlasTextureGroup = new GUIContent("Dynamic Atlas Texture Group"); public static readonly GUIContent missingGlyphLabel = new GUIContent("Missing Character Unicode", "The character to be displayed when the requested character is not found in any font asset or fallbacks."); public static readonly GUIContent clearDynamicDataOnBuildLabel = new GUIContent("Clear Dynamic Data On Build", "Determines if the \"Clear Dynamic Data on Build\" property will be set to true or false on newly created dynamic font assets."); public static readonly GUIContent disableWarningsLabel = new GUIContent("Disable warnings", "Disable warning messages in the Console."); public static readonly GUIContent defaultSpriteAssetLabel = new GUIContent("Default Sprite Asset", "The Sprite Asset that will be assigned by default when using the <sprite> tag when no Sprite Asset is specified."); public static readonly GUIContent fallbackSpriteAssetsLabel = new GUIContent("Sprite Asset Fallback", "The Sprite Assets that will be searched recursively to locate sprite characters missing from the current sprite asset."); public static readonly GUIContent fallbackSpriteAssetsListLabel = new GUIContent("Sprite Asset Fallback List", "The Sprite Assets that will be searched recursively to locate sprite characters missing from the current sprite asset."); public static readonly GUIContent missingSpriteCharacterUnicodeLabel = new GUIContent("Missing Sprite Unicode", "The unicode value for the sprite character to be displayed when the requested sprite character is not found in any sprite assets or fallbacks."); public static readonly GUIContent enableEmojiSupportLabel = new GUIContent("iOS Emoji Support", "Enables Emoji support for Touch Screen Keyboards on target devices."); //public static readonly GUIContent spriteRelativeScale = new GUIContent("Relative Scaling", "Determines if the sprites will be scaled relative to the primary font asset assigned to the text object or relative to the current font asset."); public static readonly GUIContent emojifallbackTextAssetsListLabel = new GUIContent("Fallback Emoji Text Assets", "The Text Assets that will be searched to display characters defined as Emojis in the Unicode."); public static readonly GUIContent spriteAssetsPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Sprite Assets are located.\nExample \"Sprite Assets/\""); public static readonly GUIContent defaultStyleSheetLabel = new GUIContent("Default Style Sheet", "The Style Sheet that will be used for all text objects in this project."); public static readonly GUIContent styleSheetResourcePathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Style Sheets are located.\nExample \"Style Sheets/\""); public static readonly GUIContent colorGradientPresetsLabel = new GUIContent("Color Gradient Presets", "The relative path to a Resources folder where the Color Gradient Presets are located.\nExample \"Color Gradient Presets/\""); public static readonly GUIContent colorGradientsPathLabel = new GUIContent("Path: Resources/", "The relative path to a Resources folder where the Color Gradient Presets are located.\nExample \"Color Gradient Presets/\""); public static readonly GUIContent lineBreakingLabel = new GUIContent("Line Breaking for Asian languages", "The text assets that contain the Leading and Following characters which define the rules for line breaking with Asian languages."); public static readonly GUIContent koreanSpecificRules = new GUIContent("Korean Language Options"); } SerializedProperty m_PropFontAsset; SerializedProperty m_PropDefaultFontAssetPath; ReorderableList m_FontAssetFallbackList; SerializedProperty m_PropDefaultFontSize; SerializedProperty m_PropDefaultAutoSizeMinRatio; SerializedProperty m_PropDefaultAutoSizeMaxRatio; SerializedProperty m_PropDefaultTextMeshProTextContainerSize; SerializedProperty m_PropDefaultTextMeshProUITextContainerSize; SerializedProperty m_PropAutoSizeTextContainer; SerializedProperty m_PropEnableRaycastTarget; SerializedProperty m_PropSpriteAsset; SerializedProperty m_PropSpriteAssetPath; SerializedProperty m_PropMissingSpriteCharacterUnicode; //SerializedProperty m_PropSpriteRelativeScaling; SerializedProperty m_PropEnableEmojiSupport; ReorderableList m_EmojiFallbackTextAssetList; SerializedProperty m_PropStyleSheet; SerializedProperty m_PropStyleSheetsResourcePath; SerializedProperty m_PropColorGradientPresetsPath; SerializedProperty m_PropMatchMaterialPreset; SerializedProperty m_PropTextWrappingMode; SerializedProperty m_PropKerning; SerializedProperty m_PropExtraPadding; SerializedProperty m_PropTintAllSprites; SerializedProperty m_PropParseEscapeCharacters; SerializedProperty m_PropMissingGlyphCharacter; SerializedProperty m_PropClearDynamicDataOnBuild; //SerializedProperty m_DynamicAtlasTextureManager; // SerializedProperty m_GetFontFeaturesAtRuntime; SerializedProperty m_PropDisplayWarnings; SerializedProperty m_PropUnicodeLineBreakingRules; //SerializedProperty m_PropLeadingCharacters; //SerializedProperty m_PropFollowingCharacters; //SerializedProperty m_PropUseModernHangulLineBreakingRules; private const string k_UndoRedo = "UndoRedoPerformed"; private bool m_IsFallbackGlyphCacheDirty; public void OnEnable() { if (target == null) return; m_PropFontAsset = serializedObject.FindProperty("m_DefaultFontAsset"); m_PropDefaultFontAssetPath = serializedObject.FindProperty("m_DefaultFontAssetPath"); m_FontAssetFallbackList = new ReorderableList(serializedObject, serializedObject.FindProperty("m_FallbackFontAssets"), true, true, true, true); m_FontAssetFallbackList.drawElementCallback = (rect, index, isActive, isFocused) => { var element = m_FontAssetFallbackList.serializedProperty.GetArrayElementAtIndex(index); rect.y += 2; EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none); }; m_FontAssetFallbackList.drawHeaderCallback = rect => { EditorGUI.LabelField(rect, Styles.fallbackFontAssetsListLabel); }; m_FontAssetFallbackList.onChangedCallback = itemList => m_IsFallbackGlyphCacheDirty = true; m_PropDefaultFontSize = serializedObject.FindProperty("m_DefaultFontSize"); m_PropDefaultAutoSizeMinRatio = serializedObject.FindProperty("m_defaultAutoSizeMinRatio"); m_PropDefaultAutoSizeMaxRatio = serializedObject.FindProperty("m_defaultAutoSizeMaxRatio"); m_PropDefaultTextMeshProTextContainerSize = serializedObject.FindProperty("m_defaultTextMeshProTextContainerSize"); m_PropDefaultTextMeshProUITextContainerSize = serializedObject.FindProperty("m_defaultTextMeshProUITextContainerSize"); m_PropAutoSizeTextContainer = serializedObject.FindProperty("m_autoSizeTextContainer"); m_PropEnableRaycastTarget = serializedObject.FindProperty("m_EnableRaycastTarget"); m_PropSpriteAsset = serializedObject.FindProperty("m_DefaultSpriteAsset"); // Emoji Fallback ReorderableList m_EmojiFallbackTextAssetList = new ReorderableList(serializedObject, serializedObject.FindProperty("m_EmojiFallbackTextAssets"), true, true, true, true); m_EmojiFallbackTextAssetList.drawHeaderCallback = rect => { EditorGUI.LabelField(rect, "Text Asset List"); }; m_EmojiFallbackTextAssetList.drawElementCallback = (rect, index, isActive, isFocused) => { var element = m_EmojiFallbackTextAssetList.serializedProperty.GetArrayElementAtIndex(index); rect.y += 2; EditorGUI.PropertyField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element, GUIContent.none); }; m_EmojiFallbackTextAssetList.onChangedCallback = itemList => { m_IsFallbackGlyphCacheDirty = true; }; m_PropMissingSpriteCharacterUnicode = serializedObject.FindProperty("m_MissingSpriteCharacterUnicode"); //m_PropSpriteRelativeScaling = serializedObject.FindProperty("m_SpriteRelativeScaling"); m_PropEnableEmojiSupport = serializedObject.FindProperty("m_EnableEmojiSupport"); m_PropSpriteAssetPath = serializedObject.FindProperty("m_DefaultSpriteAssetPath"); m_PropStyleSheet = serializedObject.FindProperty("m_DefaultStyleSheet"); m_PropStyleSheetsResourcePath = serializedObject.FindProperty("m_StyleSheetsResourcePath"); m_PropColorGradientPresetsPath = serializedObject.FindProperty("m_DefaultColorGradientPresetsPath"); m_PropMatchMaterialPreset = serializedObject.FindProperty("m_MatchMaterialPreset"); m_PropTextWrappingMode = serializedObject.FindProperty("m_TextWrappingMode"); m_PropKerning = serializedObject.FindProperty("m_enableKerning"); m_PropExtraPadding = serializedObject.FindProperty("m_enableExtraPadding"); m_PropTintAllSprites = serializedObject.FindProperty("m_enableTintAllSprites"); m_PropParseEscapeCharacters = serializedObject.FindProperty("m_enableParseEscapeCharacters"); m_PropMissingGlyphCharacter = serializedObject.FindProperty("m_MissingCharacterUnicode"); m_PropClearDynamicDataOnBuild = serializedObject.FindProperty("m_ClearDynamicDataOnBuild"); m_PropDisplayWarnings = serializedObject.FindProperty("m_DisplayWarnings"); //m_DynamicAtlasTextureManager = serializedObject.FindProperty("m_DynamicAtlasTextureGroup"); // m_GetFontFeaturesAtRuntime = serializedObject.FindProperty("m_GetFontFeaturesAtRuntime"); m_PropUnicodeLineBreakingRules = serializedObject.FindProperty("m_UnicodeLineBreakingRules"); //m_PropLeadingCharacters = m_PropUnicodeLineBreakingRules.FindPropertyRelative("m_LeadingCharacters"); //m_PropFollowingCharacters = m_PropUnicodeLineBreakingRules.FindPropertyRelative("m_FollowingCharacters"); //m_PropUseModernHangulLineBreakingRules = m_PropUnicodeLineBreakingRules.FindPropertyRelative("m_UseModernHangulLineBreakingRules"); } public override void OnInspectorGUI() { serializedObject.Update(); string evt_cmd = Event.current.commandName; m_IsFallbackGlyphCacheDirty = false; float labelWidth = EditorGUIUtility.labelWidth; float fieldWidth = EditorGUIUtility.fieldWidth; // TextMeshPro Font Info Panel EditorGUI.indentLevel = 0; // FONT ASSET EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.defaultFontAssetLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_PropFontAsset, Styles.defaultFontAssetLabel); if (EditorGUI.EndChangeCheck()) m_IsFallbackGlyphCacheDirty = true; EditorGUILayout.PropertyField(m_PropDefaultFontAssetPath, Styles.defaultFontAssetPathLabel); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); // FONT ASSET FALLBACK(s) EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.fallbackFontAssetsLabel, EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); m_FontAssetFallbackList.DoLayoutList(); if (EditorGUI.EndChangeCheck()) m_IsFallbackGlyphCacheDirty = true; GUILayout.Label(Styles.fallbackMaterialSettingsLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(m_PropMatchMaterialPreset, Styles.matchMaterialPresetLabel); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); // MISSING GLYPHS EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.dynamicFontSystemSettingsLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; //EditorGUILayout.PropertyField(m_GetFontFeaturesAtRuntime, Styles.getFontFeaturesAtRuntime); EditorGUILayout.PropertyField(m_PropMissingGlyphCharacter, Styles.missingGlyphLabel); EditorGUILayout.PropertyField(m_PropClearDynamicDataOnBuild, Styles.clearDynamicDataOnBuildLabel); EditorGUILayout.PropertyField(m_PropDisplayWarnings, Styles.disableWarningsLabel); //EditorGUILayout.PropertyField(m_DynamicAtlasTextureManager, Styles.dynamicAtlasTextureManager); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); // TEXT OBJECT DEFAULT PROPERTIES /* EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.containerDefaultSettingsLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(m_PropDefaultTextMeshProTextContainerSize, Styles.textMeshProLabel); EditorGUILayout.PropertyField(m_PropDefaultTextMeshProUITextContainerSize, Styles.textMeshProUiLabel); EditorGUILayout.PropertyField(m_PropEnableRaycastTarget, Styles.enableRaycastTarget); EditorGUILayout.PropertyField(m_PropAutoSizeTextContainer, Styles.autoSizeContainerLabel); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); GUILayout.Label(Styles.textComponentDefaultSettingsLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(m_PropDefaultFontSize, Styles.defaultFontSize); EditorGUILayout.BeginHorizontal(); { EditorGUILayout.PrefixLabel(Styles.autoSizeRatioLabel); EditorGUIUtility.labelWidth = 32; EditorGUIUtility.fieldWidth = 10; EditorGUI.indentLevel = 0; EditorGUILayout.PropertyField(m_PropDefaultAutoSizeMinRatio, Styles.minLabel); EditorGUILayout.PropertyField(m_PropDefaultAutoSizeMaxRatio, Styles.maxLabel); EditorGUI.indentLevel = 1; } EditorGUILayout.EndHorizontal(); EditorGUIUtility.labelWidth = labelWidth; EditorGUIUtility.fieldWidth = fieldWidth; EditorGUILayout.PropertyField(m_PropWordWrapping, Styles.wordWrappingLabel); EditorGUILayout.PropertyField(m_PropKerning, Styles.kerningLabel); EditorGUILayout.PropertyField(m_PropExtraPadding, Styles.extraPaddingLabel); EditorGUILayout.PropertyField(m_PropTintAllSprites, Styles.tintAllSpritesLabel); EditorGUILayout.PropertyField(m_PropParseEscapeCharacters, Styles.parseEscapeCharactersLabel); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); */ // SPRITE ASSET EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.defaultSpriteAssetLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_PropSpriteAsset, Styles.defaultSpriteAssetLabel); if (EditorGUI.EndChangeCheck()) m_IsFallbackGlyphCacheDirty = true; EditorGUILayout.PropertyField(m_PropMissingSpriteCharacterUnicode, Styles.missingSpriteCharacterUnicodeLabel); //EditorGUILayout.PropertyField(m_PropEnableEmojiSupport, Styles.enableEmojiSupportLabel); //EditorGUILayout.PropertyField(m_PropSpriteRelativeScaling, Styles.spriteRelativeScale); EditorGUILayout.PropertyField(m_PropSpriteAssetPath, Styles.spriteAssetsPathLabel); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); // SPRITE ASSET FALLBACK(s) EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.emojifallbackTextAssetsListLabel, EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); m_EmojiFallbackTextAssetList.DoLayoutList(); if (EditorGUI.EndChangeCheck()) m_IsFallbackGlyphCacheDirty = true; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); // STYLE SHEET EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.defaultStyleSheetLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUI.BeginChangeCheck(); EditorGUILayout.PropertyField(m_PropStyleSheet, Styles.defaultStyleSheetLabel); if (EditorGUI.EndChangeCheck()) { serializedObject.ApplyModifiedProperties(); TextStyleSheet styleSheet = m_PropStyleSheet.objectReferenceValue as TextStyleSheet; if (styleSheet != null) styleSheet.RefreshStyles(); } EditorGUILayout.PropertyField(m_PropStyleSheetsResourcePath, Styles.styleSheetResourcePathLabel); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); // COLOR GRADIENT PRESETS EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.colorGradientPresetsLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(m_PropColorGradientPresetsPath, Styles.colorGradientsPathLabel); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); EditorGUILayout.Space(); // LINE BREAKING RULE EditorGUILayout.BeginVertical(EditorStyles.helpBox); GUILayout.Label(Styles.lineBreakingLabel, EditorStyles.boldLabel); EditorGUI.indentLevel = 1; EditorGUILayout.PropertyField(m_PropUnicodeLineBreakingRules); //EditorGUILayout.Space(); //GUILayout.Label(Styles.koreanSpecificRules, EditorStyles.boldLabel); //EditorGUILayout.PropertyField(m_PropUseModernHangulLineBreakingRules, new GUIContent("Use Modern Line Breaking", "Determines if traditional or modern line breaking rules will be used to control line breaking. Traditional line breaking rules use the Leading and Following Character rules whereas Modern uses spaces for line breaking.")); EditorGUI.indentLevel = 0; EditorGUILayout.Space(); EditorGUILayout.EndVertical(); if (m_IsFallbackGlyphCacheDirty || evt_cmd == k_UndoRedo) TextResourceManager.RebuildFontAssetCache(); if (serializedObject.ApplyModifiedProperties() || evt_cmd == k_UndoRedo) { EditorUtility.SetDirty(target); TextEventManager.ON_TMP_SETTINGS_CHANGED(); } } } }
UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextSettingsEditor.cs/0
{ "file_path": "UnityCsReference/Modules/TextCoreTextEngineEditor/Managed/TextSettingsEditor.cs", "repo_id": "UnityCsReference", "token_count": 9028 }
441
// 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; using Unity.Collections.LowLevel.Unsafe; namespace UnityEngine.Tilemaps { public partial class Tilemap { public static event Action<Tilemap, SyncTile[]> tilemapTileChanged; public static event Action<Tilemap, NativeArray<Vector3Int>> tilemapPositionsChanged; public static event Action<Tilemap, NativeArray<Vector3Int>> loopEndedForTileAnimation; private bool m_BufferSyncTile; internal bool bufferSyncTile { get { return m_BufferSyncTile; } set { if (value == false && m_BufferSyncTile != value && HasSyncTileCallback()) SendAndClearSyncTileBuffer(); m_BufferSyncTile = value; } } internal static bool HasLoopEndedForTileAnimationCallback() { return (Tilemap.loopEndedForTileAnimation != null); } private unsafe void HandleLoopEndedForTileAnimationCallback(int count, IntPtr positionsIntPtr) { if (!HasLoopEndedForTileAnimationCallback()) return; void* positionsPtr = positionsIntPtr.ToPointer(); var positions = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector3Int>(positionsPtr, count, Allocator.Invalid); var safety = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref positions, safety); SendLoopEndedForTileAnimationCallback(positions); AtomicSafetyHandle.CheckDeallocateAndThrow(safety); AtomicSafetyHandle.Release(safety); } private void SendLoopEndedForTileAnimationCallback(NativeArray<Vector3Int> positions) { try { Tilemap.loopEndedForTileAnimation(this, positions); } catch (Exception e) { // Case 1215834: Log user exception/s and ensure engine code continues to run Debug.LogException(e, this); } } internal static bool HasSyncTileCallback() { return (Tilemap.tilemapTileChanged != null); } internal static bool HasPositionsChangedCallback() { return (Tilemap.tilemapPositionsChanged != null); } private void HandleSyncTileCallback(SyncTile[] syncTiles) { if (Tilemap.tilemapTileChanged == null) return; SendTilemapTileChangedCallback(syncTiles); } private unsafe void HandlePositionsChangedCallback(int count, IntPtr positionsIntPtr) { if (!HasPositionsChangedCallback()) return; void* positionsPtr = positionsIntPtr.ToPointer(); var positions = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<Vector3Int>(positionsPtr, count, Allocator.Invalid); var safety = AtomicSafetyHandle.Create(); NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref positions, safety); SendTilemapPositionsChangedCallback(positions); AtomicSafetyHandle.CheckDeallocateAndThrow(safety); AtomicSafetyHandle.Release(safety); } private void SendTilemapTileChangedCallback(SyncTile[] syncTiles) { try { Tilemap.tilemapTileChanged(this, syncTiles); } catch (Exception e) { // Case 1215834: Log user exception/s and ensure engine code continues to run Debug.LogException(e, this); } } private void SendTilemapPositionsChangedCallback(NativeArray<Vector3Int> positions) { try { Tilemap.tilemapPositionsChanged(this, positions); } catch (Exception e) { // Case 1215834: Log user exception/s and ensure engine code continues to run Debug.LogException(e, this); } } internal static void SetSyncTileCallback(Action<Tilemap, SyncTile[]> callback) { Tilemap.tilemapTileChanged += callback; } internal static void RemoveSyncTileCallback(Action<Tilemap, SyncTile[]> callback) { Tilemap.tilemapTileChanged -= callback; } } }
UnityCsReference/Modules/Tilemap/Managed/Tilemap.cs/0
{ "file_path": "UnityCsReference/Modules/Tilemap/Managed/Tilemap.cs", "repo_id": "UnityCsReference", "token_count": 1998 }
442
// 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.Profiling; using UnityEditor; namespace TreeEditor { // // Branch group // [System.Serializable] public class TreeGroupBranch : TreeGroup { private static float spreadMul = 5.0f; public enum GeometryMode { Branch = 0, BranchFrond = 1, Frond = 2 } static class Styles { public static string groupSeedString = LocalizationDatabase.GetLocalizedString("Group Seed|The seed for this group of branches. Modify to vary procedural generation."); public static string frequencyString = LocalizationDatabase.GetLocalizedString("Frequency|Adjusts the number of branches created for each parent branch."); public static string distributionModeString = LocalizationDatabase.GetLocalizedString("Distribution|The way the branches are distributed along their parent."); public static string twirlString = LocalizationDatabase.GetLocalizedString("Twirl|Twirl around the parent branch."); public static string whorledStepString = LocalizationDatabase.GetLocalizedString("Whorled Step|Defines how many nodes are in each whorled step when using Whorled distribution. For real plants this is normally a Fibonacci number."); public static string growthScaleString = LocalizationDatabase.GetLocalizedString("Growth Scale|Defines the scale of nodes along the parent node. Use the curve to adjust and the slider to fade the effect in and out."); public static string growthAngleString = LocalizationDatabase.GetLocalizedString("Growth Angle|Defines the initial angle of growth relative to the parent. Use the curve to adjust and the slider to fade the effect in and out."); public static string mainWindString = LocalizationDatabase.GetLocalizedString("Main Wind|Primary wind effect. This creates a soft swaying motion and is typically the only parameter needed for primary branches."); public static string mainTurbulenceString = LocalizationDatabase.GetLocalizedString("Main Turbulence|Secondary turbulence effect. Produces more stochastic motion, which is individual per branch. Typically used for branches with fronds, such as ferns and palms."); public static string edgeTurbulenceString = LocalizationDatabase.GetLocalizedString("Edge Turbulence|Turbulence along the edge of fronds. Useful for ferns, palms, etc."); } // members //[field: TreeAttribute("Geometry", "category", 0.0f, 1.0f)] //public bool showGeometryProps = true; //[field: TreeAttribute("LODQuality", "slider", 0.0f, 2.0f)] public float lodQualityMultiplier = 1.0f; //[field: TreeAttribute("GeometryMode", "popup", "Branch Only,Branch + Fronds,Fronds Only")] public GeometryMode geometryMode = GeometryMode.Branch; // Materials //[field: TreeAttribute("BranchMaterial", "material", 0.0f, 1.0f)] public Material materialBranch = null; //[field: TreeAttribute("BreakMaterial", "material", 0.0f, 1.0f)] public Material materialBreak = null; //[field: TreeAttribute("FrondMaterial", "material", 0.0f, 1.0f)] public Material materialFrond = null; //[field: TreeAttribute("Shape", "category", 0.0f, 1.0f)] //public bool showShapeProps = true; //[field: TreeAttribute("Length", "minmaxslider", 0.1f, 50.0f,"notLocked")] public Vector2 height = new Vector2(10.0f, 15.0f); //[field: TreeAttribute("Radius", "slider", 0.1f, 5.0f, "radiusCurve", 0.0f, 1.0f, "branchGeometry")] public float radius = 0.5f; public AnimationCurve radiusCurve = new AnimationCurve(new Keyframe(0, 1, -1, -1), new Keyframe(1, 0, -1, -1)); //[field: TreeAttribute("IsLengthRelative", "toggle", 0.0f, 1.0f, "branchGeometry")] public bool radiusMode = true; //[field: TreeAttribute("CapSmoothing", "slider", 0.0f, 1.0f, "branchGeometry")] public float capSmoothing = 0.0f; // Shape stuff //[field: TreeAttribute("Growth", "heading", "all")] //public bool showGrowthProps = true; //[field: TreeAttribute("Crinklyness", "slider", 0.0f, 1.0f, "crinkCurve", 0.0f, 1.0f, "notLocked")] public float crinklyness = 0.1f; public AnimationCurve crinkCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 1.0f)); //[field: TreeAttribute("SeekSunGround", "slider", 0.0f, 1.0f, "seekCurve", -1.0f, 1.0f, "notLocked")] public float seekBlend = 0.0f; public AnimationCurve seekCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 1.0f)); // Surface/vertex noise stuff //[field: TreeAttribute("SurfaceNoise", "heading", "all")] //public bool showNoiseProps = true; //[field: TreeAttribute("Noise", "slider", 0.0f, 1.0f, "noiseCurve", 0.0f, 1.0f, "branchGeometry")] public float noise = 0.1f; public AnimationCurve noiseCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 1.0f)); //[field: TreeAttribute("NoiseScaleU", "slider", 0.0f, 1.0f, "branchGeometry")] public float noiseScaleU = 0.2f; //[field: TreeAttribute("NoiseScaleV", "slider", 0.0f, 1.0f, "branchGeometry")] public float noiseScaleV = 0.1f; // Flares.. Only for root branches/trunks //[field: TreeAttribute("Flare", "heading", "root")] //public bool showFlareProps = true; //[field: TreeAttribute("FlareRadius", "slider", 0.0f, 5.0f, "branchGeometry")] public float flareSize = 0.0f; //[field: TreeAttribute("FlareHeight", "slider", 0.01f, 1.0f, "branchGeometry")] public float flareHeight = 0.1f; //[field: TreeAttribute("FlareNoise", "slider", 0.0f, 1.0f, "branchGeometry")] public float flareNoise = 0.3f; // Welding stuff.. Only for branches that are attached to another branch.. //[field: TreeAttribute("Welding", "heading", "notRoot")] //public bool showWeldProps = true; //[field: TreeAttribute("WeldHeight", "slider", 0.01f, 1.0f, "branchGeometry")] public float weldHeight = 0.1f; //[field: TreeAttribute("WeldSpreadTop", "slider", 0.0f, 1.0f, "branchGeometry")] public float weldSpreadTop = 0.0f; //[field: TreeAttribute("WeldSpreadBottom", "slider", 0.0f, 1.0f, "branchGeometry")] public float weldSpreadBottom = 0.0f; // Breaking stuff.. //[field: TreeAttribute("Breaking", "category", 0.0f, 1.0f)] //public bool showBreakProps = true; //[field: TreeAttribute("BreakChance", "slider", 0.0f, 1.0f)] public float breakingChance = 0.0f; //[field: TreeAttribute("BreakLocation", "minmaxslider", 0.0f, 1.0f)] public Vector2 breakingSpot = new Vector2(0.4f, 0.6f); // Frond stuff.. //[field: TreeAttribute("Fronds", "category", 0.0f, 1.0f)] //public bool showFrondProps = true; //[field: TreeAttribute("FrondCount", "intslider", 1.0f, 16.0f)] public int frondCount = 1; //[field: TreeAttribute("FrondWidth", "slider", 0.1f, 10.0f, "frondCurve", 0.0f, 1.0f)] public float frondWidth = 1.0f; public AnimationCurve frondCurve = new AnimationCurve(new Keyframe(0.0f, 1.0f), new Keyframe(1.0f, 1.0f)); //[field: TreeAttribute("FrondRange", "minmaxslider", 0.0f, 1.0f)] public Vector2 frondRange = new Vector2(0.1f, 1.0f); //[field: TreeAttribute("FrondRotation", "slider", 0.0f, 1.0f)] public float frondRotation = 0.0f; //[field: TreeAttribute("FrondCrease", "slider", -1.0f, 1.0f)] public float frondCrease = 0.0f; override internal bool HasExternalChanges() { string hash; List<Object> objects = new List<Object>(); if (geometryMode == GeometryMode.Branch) { objects.Add(materialBranch); if (breakingChance > 0) objects.Add(materialBreak); } else if (geometryMode == GeometryMode.BranchFrond) { objects.Add(materialBranch); objects.Add(materialFrond); if (breakingChance > 0) objects.Add(materialBreak); } else if (geometryMode == GeometryMode.Frond) { objects.Add(materialFrond); } hash = UnityEditorInternal.InternalEditorUtility.CalculateHashForObjectsAndDependencies(objects.ToArray()); if (hash != m_Hash) { m_Hash = hash; return true; } return false; } private Vector3 GetFlareWeldAtTime(TreeNode node, float time) { float scale = node.GetScale(); float flareFactor = 0.0f; float spreadFactor = 0.0f; // flares if (flareHeight > 0.001f) { float flareDist = ((1.0f - time) - (1.0f - flareHeight)) / flareHeight; flareFactor = Mathf.Pow(Mathf.Clamp01(flareDist), 1.5f) * scale; } // weld spread top/bottom if (weldHeight > 0.001f) { float spreadDist = ((1.0f - time) - (1.0f - weldHeight)) / weldHeight; spreadFactor = Mathf.Pow(Mathf.Clamp01(spreadDist), 1.5f) * scale; } return new Vector3(flareFactor * flareSize, spreadFactor * weldSpreadTop * spreadMul, spreadFactor * weldSpreadBottom * spreadMul); } override public float GetRadiusAtTime(TreeNode node, float time, bool includeModifications) { // no radius when only fronds are displayed.. if (geometryMode == GeometryMode.Frond) return 0.0f; float mainRadius = Mathf.Clamp01(radiusCurve.Evaluate(time)) * node.size; // Smooth capping float capStart = 1.0f - node.capRange; if (time > capStart) { // within cap area float angle = Mathf.Acos(Mathf.Clamp01((time - capStart) / node.capRange)); float roundScale = Mathf.Sin(angle); mainRadius *= roundScale; } // Flare / welding if (includeModifications) { Vector3 flareWeldRad = GetFlareWeldAtTime(node, time); mainRadius += Mathf.Max(flareWeldRad.x, Mathf.Max(flareWeldRad.y, flareWeldRad.z) * 0.25f) * 0.1f; } return mainRadius; } override public void UpdateParameters() { // // Reset un-needed values // if ((parentGroup == null) || (parentGroup.GetType() == typeof(TreeGroupRoot))) { // no spreading for root branches weldSpreadTop = 0.0f; weldSpreadBottom = 0.0f; // no secondary motion for root branches animationSecondary = 0.0f; } else { // no flares for sub-branches flareSize = 0.0f; } float heightVariation = (height.y - height.x) / height.y; for (int n = 0; n < nodes.Count; n++) { TreeNode node = nodes[n]; Random.InitState(node.seed); // Size variation float variationScale = 1.0f; for (int x = 0; x < 5; x++) { variationScale = 1.0f - (Random.value * heightVariation); } if (lockFlags == 0) { node.scale *= variationScale; } // breaking.. float bks = 0.0f; for (int x = 0; x < 5; x++) { bks = Random.value; } for (int x = 0; x < 5; x++) { // outside range node.breakOffset = 1.0f; // will it break .. will it break.. if ((Random.value <= breakingChance) && (breakingChance > 0.0f)) { node.breakOffset = breakingSpot.x + ((breakingSpot.y - breakingSpot.x) * bks); if (node.breakOffset < 0.01f) { node.breakOffset = 0.01f; } } } // compute radius of this node if (!(parentGroup is TreeGroupRoot)) { node.size = radius; if (radiusMode) { // scale according to length node.size *= node.scale; } if ((node.parent != null) && (node.parent.spline != null)) { // Clamp to parent node.size = Mathf.Min(node.parent.group.GetRadiusAtTime(node.parent, node.offset, false) * 0.75f, node.size); } } else if (lockFlags == 0) { // special case for root, we don't want the radius to change if it's moved around by hand node.size = radius; if (radiusMode) { // scale according to length node.size *= node.scale; } } /* for (int i = 0; i < nodes.Count; i++) { nodes[i].triStart = 0; nodes[i].triEnd = 0; } */ /* // Generate the spline according to the settings UpdateSpline( node ); // Compute smoothing range for cap if (capSmoothing < 0.01f) { node.capRange = 0.0f; } else { float capRadius = Mathf.Clamp(radiusCurve.Evaluate(1.0f), 0.0f, 1.0f) * node.size; float totalHeight = height * node.GetScale(); node.capRange = (capRadius / totalHeight) * capSmoothing * 2.0f; } */ } // Matrix must be updated before spline generation UpdateMatrix(); // Spline generation UpdateSplines(); // Update child groups.. base.UpdateParameters(); } public void UpdateSplines() { for (int n = 0; n < nodes.Count; n++) { TreeNode node = nodes[n]; // Generate the spline according to the settings UpdateSpline(node); // Compute smoothing range for cap if (capSmoothing < 0.01f) { node.capRange = 0.0f; } else { float capRadius = Mathf.Clamp(radiusCurve.Evaluate(1.0f), 0.0f, 1.0f) * node.size; float totalHeight = Mathf.Max(node.spline.GetApproximateLength(), 0.00001f); node.capRange = (capRadius / totalHeight) * capSmoothing * 2.0f; } } } override public void UpdateMatrix() { if (parentGroup == null) { // root node, use rootSpread parameter for (int i = 0; i < nodes.Count; i++) { TreeNode node = nodes[i]; /* float dist = node.offset * rootSpread; float ang = node.angle * Mathf.Deg2Rad; Vector3 pos = new Vector3(Mathf.Cos(ang) * dist, 0.0f, Mathf.Sin(ang) * dist); Quaternion rot = Quaternion.Euler(node.pitch*-Mathf.Sin(ang), 0, node.pitch * Mathf.Cos(ang)) * Quaternion.Euler(0, node.angle, 0); node.matrix = Matrix4x4.TRS(pos, rot, Vector3.one); */ node.matrix = Matrix4x4.identity; } } else if (parentGroup is TreeGroupRoot) { TreeGroupRoot tgr = parentGroup as TreeGroupRoot; // Attached to root node for (int i = 0; i < nodes.Count; i++) { TreeNode node = nodes[i]; float dist = node.offset * GetRootSpread(); float ang = node.angle * Mathf.Deg2Rad; Vector3 pos = new Vector3(Mathf.Cos(ang) * dist, -tgr.groundOffset, Mathf.Sin(ang) * dist); Quaternion rot = Quaternion.Euler(node.pitch * -Mathf.Sin(ang), 0, node.pitch * Mathf.Cos(ang)) * Quaternion.Euler(0, node.angle, 0); node.matrix = Matrix4x4.TRS(pos, rot, Vector3.one); } } else { // has a parent so, use that.. for (int i = 0; i < nodes.Count; i++) { TreeNode node = nodes[i]; Vector3 pos = new Vector3(); Quaternion rot = new Quaternion(); float rad = 0.0f; node.parent.GetPropertiesAtTime(node.offset, out pos, out rot, out rad); // x=90 makes sure start growth is perpendicular.. Quaternion angle = Quaternion.Euler(90.0f, node.angle, 0); Matrix4x4 aog = Matrix4x4.TRS(Vector3.zero, angle, Vector3.one); // pitch matrix Matrix4x4 pit = Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(node.pitch, 0.0f, 0.0f), Vector3.one); node.matrix = node.parent.matrix * Matrix4x4.TRS(pos, rot, Vector3.one) * aog * pit; Vector3 off = node.matrix.MultiplyPoint(new Vector3(0, rad, 0)); node.matrix.m03 = off.x; node.matrix.m13 = off.y; node.matrix.m23 = off.z; } } // Update child groups.. //base.UpdateMatrix(); } override public void BuildAOSpheres(List<TreeAOSphere> aoSpheres) { float minStepSize = 0.5f; if (visible) { bool includeFronds = (geometryMode != GeometryMode.Branch); bool includeBranch = (geometryMode != GeometryMode.Frond); for (int n = 0; n < nodes.Count; n++) { TreeNode node = nodes[n]; if (!node.visible) continue; float scale = node.GetScale(); float totalHeight = node.spline.GetApproximateLength(); if (totalHeight < minStepSize) totalHeight = minStepSize; float minStep = minStepSize / totalHeight; float t = 0.0f; while (t < 1.0f) { Vector3 pos = node.matrix.MultiplyPoint(node.spline.GetPositionAtTime(t)); float rad = 0.0f; if (includeBranch) { rad = GetRadiusAtTime(node, t, false) * 0.95f; } if (includeFronds) { rad = Mathf.Max(rad, 0.95f * (Mathf.Clamp01(frondCurve.Evaluate(t)) * frondWidth * scale)); // push position down.. pos.y -= rad; } if (rad > 0.01f) { aoSpheres.Add(new TreeAOSphere(pos, rad, 1.0f)); } t += Mathf.Max(minStep, rad / totalHeight); } } } // Update child groups.. base.BuildAOSpheres(aoSpheres); } override public void UpdateMesh(List<TreeMaterial> materials, List<TreeVertex> verts, List<TreeTriangle> tris, List<TreeAOSphere> aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) { // int materialIndex = GetMaterialIndex(materialBranch, materials); // Debug.Log("branch material index: "+materialIndex); // Create mesh for nodes if (geometryMode == GeometryMode.Branch || geometryMode == GeometryMode.BranchFrond) { GetMaterialIndex(materialBranch, materials, true); if (breakingChance > 0) { GetMaterialIndex(materialBreak, materials, false); } } if (geometryMode == GeometryMode.Frond || geometryMode == GeometryMode.BranchFrond) { GetMaterialIndex(materialFrond, materials, false); } // Create mesh for nodes for (int i = 0; i < nodes.Count; i++) { UpdateNodeMesh(nodes[i], materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity); } // Update child groups.. base.UpdateMesh(materials, verts, tris, aoSpheres, buildFlags, adaptiveQuality, aoDensity); } private void UpdateNodeMesh(TreeNode node, List<TreeMaterial> materials, List<TreeVertex> verts, List<TreeTriangle> tris, List<TreeAOSphere> aoSpheres, int buildFlags, float adaptiveQuality, float aoDensity) { // Clear tri range node.triStart = tris.Count; node.triEnd = tris.Count; node.vertStart = verts.Count; node.vertEnd = verts.Count; // Check for visibility if (!node.visible || !visible) return; Profiler.BeginSample("TreeGroupBranch.UpdateNodeMesh"); int vertOffset = verts.Count; float totalHeight = node.spline.GetApproximateLength();// *node.GetScale(); //height * node.GetScale(); // list to hold the ring loops List<RingLoop> ringloops = new List<RingLoop>(); // Modify LOD to fit local settings float lodQuality = Mathf.Clamp01(adaptiveQuality * lodQualityMultiplier); // LOD settings List<float> heightSamples = TreeData.GetAdaptiveSamples(this, node, lodQuality); int radialSamples = TreeData.GetAdaptiveRadialSegments(radius, lodQuality); // // Parent branch group if any.. TreeGroupBranch parentBranchGroup = null; if ((parentGroup != null) && (parentGroup.GetType() == typeof(TreeGroupBranch))) { parentBranchGroup = (TreeGroupBranch)parentGroup; } if ((geometryMode == GeometryMode.BranchFrond) || (geometryMode == GeometryMode.Branch)) { int materialIndex = GetMaterialIndex(materialBranch, materials, true); float uvOffset = 0.0f; float uvBaseOffset = 0.0f; float uvStep = totalHeight / (GetRadiusAtTime(node, 0.0f, false) * Mathf.PI * 2.0f); bool uvAdapt = true; if (node.parent != null && parentBranchGroup != null) { uvBaseOffset = node.offset * node.parent.spline.GetApproximateLength(); } float capStart = 1.0f - node.capRange; for (int i = 0; i < heightSamples.Count; i++) { float t = heightSamples[i]; Vector3 pos = node.spline.GetPositionAtTime(t); Quaternion rot = node.spline.GetRotationAtTime(t); float rad = GetRadiusAtTime(node, t, false); Matrix4x4 m = node.matrix * Matrix4x4.TRS(pos, rot, new Vector3(1, 1, 1)); // total offset for wind animation //float totalOffset = (totalOffsetBase + t); // flare / weld spreading Vector3 flareWeldSpread = GetFlareWeldAtTime(node, t); // Do adaptive LOD for ringloops float radModify = Mathf.Max(flareWeldSpread.x, Mathf.Max(flareWeldSpread.y, flareWeldSpread.z) * 0.25f); // keep the same number of vertices per ring for the cap.. to give a nicer result if (t <= capStart) { radialSamples = TreeData.GetAdaptiveRadialSegments(rad + radModify, lodQuality); } // uv offset.. if (uvAdapt) { if (i > 0) { float preT = heightSamples[i - 1]; float uvDelta = t - preT; float uvRad = (rad + GetRadiusAtTime(node, preT, false)) * 0.5f; uvOffset += (uvDelta * totalHeight) / (uvRad * Mathf.PI * 2.0f); } } else { uvOffset = uvBaseOffset + (t * uvStep); } // wind Vector2 windFactors = ComputeWindFactor(node, t); RingLoop r = new RingLoop(); r.Reset(rad, m, uvOffset, radialSamples); r.SetSurfaceAngle(node.GetSurfaceAngleAtTime(t)); r.SetAnimationProperties(windFactors.x, windFactors.y, 0.0f, node.animSeed); r.SetSpread(flareWeldSpread.y, flareWeldSpread.z); r.SetNoise(noise * Mathf.Clamp01(noiseCurve.Evaluate(t)), noiseScaleU * 10.0f, noiseScaleV * 10.0f); r.SetFlares(flareWeldSpread.x, flareNoise * 10.0f); int vertStart = verts.Count; r.BuildVertices(verts); int vertEnd = verts.Count; if ((buildFlags & (int)BuildFlag.BuildWeldParts) != 0) { float projectionRange = weldHeight; float projectionBlend = Mathf.Pow(Mathf.Clamp01(((1.0f - t) - (1.0f - weldHeight)) / weldHeight), 1.5f); float invProjectionBlend = 1.0f - projectionBlend; if (t < projectionRange) { if ((node.parent != null) && (node.parent.spline != null)) { Ray ray = new Ray(); for (int v = vertStart; v < vertEnd; v++) { ray.origin = verts[v].pos; ray.direction = m.MultiplyVector(-Vector3.up); Vector3 origPos = verts[v].pos; Vector3 origNor = verts[v].nor; float minDist = -10000.0f; float maxDist = 100000.0f; // project vertices onto parent for (int tri = node.parent.triStart; tri < node.parent.triEnd; tri++) { object hit = MathUtils.IntersectRayTriangle(ray, verts[tris[tri].v[0]].pos, verts[tris[tri].v[1]].pos, verts[tris[tri].v[2]].pos, true); if (hit != null) { RaycastHit rayHit = ((RaycastHit)hit); if ((Mathf.Abs(rayHit.distance) < maxDist) && (rayHit.distance > minDist)) { maxDist = Mathf.Abs(rayHit.distance); verts[v].nor = (verts[tris[tri].v[0]].nor * rayHit.barycentricCoordinate.x) + (verts[tris[tri].v[1]].nor * rayHit.barycentricCoordinate.y) + (verts[tris[tri].v[2]].nor * rayHit.barycentricCoordinate.z); verts[v].nor = (verts[v].nor * projectionBlend) + (origNor * invProjectionBlend); verts[v].pos = (rayHit.point * projectionBlend) + (origPos * invProjectionBlend); } } } } } } } ringloops.Add(r); // make sure we cap the puppy.. if ((t == 1.0f) && (r.radius > 0.005f)) { RingLoop r2 = r.Clone(); r2.radius = 0.0f; r2.baseOffset += rad / (Mathf.PI * 2.0f); r2.BuildVertices(verts); ringloops.Add(r2); } } // Cap // if needed.. if (ringloops.Count > 0) { if (ringloops[ringloops.Count - 1].radius > 0.025f) { if (node.breakOffset < 1.0f) { float mappingScale = 1.0f / (radius * Mathf.PI * 2.0f); float tempCapSpherical = 0.0f; float tempCapNoise = 1.0f; int tempCapMapping = 0; Material tempCapMaterial = materialBranch; if (materialBreak != null) { tempCapMaterial = materialBreak; } int capMaterialIndex = GetMaterialIndex(tempCapMaterial, materials, false); ringloops[ringloops.Count - 1].Cap(tempCapSpherical, tempCapNoise, tempCapMapping, mappingScale, verts, tris, capMaterialIndex); } } } // Build triangles // Debug.Log("MAT INDEX: "+materialIndex); node.triStart = tris.Count; for (int i = 0; i < (ringloops.Count - 1); i++) { ringloops[i].Connect(ringloops[i + 1], tris, materialIndex, false, false); } node.triEnd = tris.Count; ringloops.Clear(); } // Build fronds float frondMin = Mathf.Min(frondRange.x, frondRange.y); float frondMax = Mathf.Max(frondRange.x, frondRange.y); // Mapping range.. may be different from min/max if broken.. float frondMappingMin = frondMin; float frondMappingMax = frondMax; // Include breaking frondMin = Mathf.Clamp(frondMin, 0.0f, node.breakOffset); frondMax = Mathf.Clamp(frondMax, 0.0f, node.breakOffset); if ((geometryMode == GeometryMode.BranchFrond) || (geometryMode == GeometryMode.Frond)) { if ((frondCount > 0) && (frondMin != frondMax)) { bool needStartPoint = true; bool needEndPoint = true; for (int i = 0; i < heightSamples.Count; i++) { float t = heightSamples[i]; if (t < frondMin) { heightSamples.RemoveAt(i); i--; } else if (t == frondMin) { needStartPoint = false; } else if (t == frondMax) { needEndPoint = false; } else if (t > frondMax) { heightSamples.RemoveAt(i); i--; } } if (needStartPoint) { heightSamples.Insert(0, frondMin); } if (needEndPoint) { heightSamples.Add(frondMax); } int frondMaterialIndex = GetMaterialIndex(materialFrond, materials, false); float capStart = 1.0f - node.capRange; //float capRadius = GetRadiusAtTime(capStart); for (int j = 0; j < frondCount; j++) { float crease = (frondCrease * 90.0f) * Mathf.Deg2Rad; float angle = ((frondRotation * 360.0f) + (((float)j * 180.0f) / frondCount) - 90.0f) * Mathf.Deg2Rad; float angleA = -angle - crease; float angleB = angle - crease; Vector3 directionA = new Vector3(Mathf.Sin(angleA), 0.0f, Mathf.Cos(angleA)); Vector3 normalA = new Vector3(directionA.z, 0.0f, -directionA.x); Vector3 directionB = new Vector3(Mathf.Sin(angleB), 0.0f, -Mathf.Cos(angleB)); Vector3 normalB = new Vector3(-directionB.z, 0.0f, directionB.x); //float totalOffsetBase = GetTotalOffset(); for (int i = 0; i < heightSamples.Count; i++) { float t = heightSamples[i]; float v = (t - frondMappingMin) / (frondMappingMax - frondMappingMin); // handle soft capping.. float t2 = t; if (t > capStart) { t2 = capStart; float capAngle = Mathf.Acos(Mathf.Clamp01((t - capStart) / node.capRange)); float sinCapAngle = Mathf.Sin(capAngle); float cosCapAngle = Mathf.Cos(capAngle) * capSmoothing; directionA = new Vector3(Mathf.Sin(angleA) * sinCapAngle, cosCapAngle, Mathf.Cos(angleA) * sinCapAngle); normalA = new Vector3(directionA.z, directionA.y, -directionA.x); directionB = new Vector3(Mathf.Sin(angleB) * sinCapAngle, cosCapAngle, -Mathf.Cos(angleB) * sinCapAngle); normalB = new Vector3(-directionB.z, directionB.y, directionB.x); } Vector3 normalMid = new Vector3(0, 0, -1); Vector3 pos = node.spline.GetPositionAtTime(t2); Quaternion rot = node.spline.GetRotationAtTime(t); float rad = (Mathf.Clamp01(frondCurve.Evaluate(t)) * frondWidth * node.GetScale()); Matrix4x4 m = node.matrix * Matrix4x4.TRS(pos, rot, new Vector3(1, 1, 1)); if (GenerateDoubleSidedGeometry) { // Generate double sided geometry to compensate for lack of VFACE shader semantic // Twice the poly count // Split vertices along back seam, to avoid bent normals.. 8 verts instead of 3 for (float side = -1; side < 2; side += 2) { TreeVertex v0 = new TreeVertex(); v0.pos = m.MultiplyPoint(directionA * rad); v0.nor = m.MultiplyVector(normalA * side).normalized; v0.tangent = CreateTangent(node, rot, v0.nor); v0.tangent.w = -side; v0.uv0 = new Vector2(1.0f, v); TreeVertex v1 = new TreeVertex(); v1.pos = m.MultiplyPoint(Vector3.zero); v1.nor = m.MultiplyVector(normalMid * side).normalized; v1.tangent = CreateTangent(node, rot, v1.nor); v1.tangent.w = -side; v1.uv0 = new Vector2(0.5f, v); TreeVertex v2 = new TreeVertex(); v2.pos = m.MultiplyPoint(Vector3.zero); v2.nor = m.MultiplyVector(normalMid * side).normalized; v2.tangent = CreateTangent(node, rot, v2.nor); v2.tangent.w = -side; v2.uv0 = new Vector2(0.5f, v); TreeVertex v3 = new TreeVertex(); v3.pos = m.MultiplyPoint(directionB * rad); v3.nor = m.MultiplyVector(normalB * side).normalized; v3.tangent = CreateTangent(node, rot, v3.nor); v3.tangent.w = -side; v3.uv0 = new Vector2(0.0f, v); // Animation properties.. Vector2 windFactors = ComputeWindFactor(node, t); v0.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed); v1.SetAnimationProperties(windFactors.x, windFactors.y, 0.0f, node.animSeed); // no edge flutter for center vertex v2.SetAnimationProperties(windFactors.x, windFactors.y, 0.0f, node.animSeed); // no edge flutter for center vertex v3.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed); verts.Add(v0); verts.Add(v1); verts.Add(v2); verts.Add(v3); } if (i > 0) { int voffset = verts.Count; // // theoretical left side :) // // back TreeTriangle tri0 = new TreeTriangle(frondMaterialIndex, voffset - 4, voffset - 3, voffset - 11); TreeTriangle tri1 = new TreeTriangle(frondMaterialIndex, voffset - 4, voffset - 11, voffset - 12); tri0.flip(); tri1.flip(); // front TreeTriangle tri2 = new TreeTriangle(frondMaterialIndex, voffset - 8, voffset - 7, voffset - 15); TreeTriangle tri3 = new TreeTriangle(frondMaterialIndex, voffset - 8, voffset - 15, voffset - 16); tris.Add(tri0); tris.Add(tri1); tris.Add(tri2); tris.Add(tri3); // // theoretical right side :) // // front TreeTriangle tri4 = new TreeTriangle(frondMaterialIndex, voffset - 2, voffset - 9, voffset - 1); TreeTriangle tri5 = new TreeTriangle(frondMaterialIndex, voffset - 2, voffset - 10, voffset - 9); // back TreeTriangle tri6 = new TreeTriangle(frondMaterialIndex, voffset - 6, voffset - 13, voffset - 5); TreeTriangle tri7 = new TreeTriangle(frondMaterialIndex, voffset - 6, voffset - 14, voffset - 13); tri6.flip(); tri7.flip(); tris.Add(tri4); tris.Add(tri5); tris.Add(tri6); tris.Add(tri7); } } else { // Single sided geometry .. we'll keep this for later TreeVertex v0 = new TreeVertex(); v0.pos = m.MultiplyPoint(directionA * rad); v0.nor = m.MultiplyVector(normalA).normalized; v0.uv0 = new Vector2(0.0f, v); TreeVertex v1 = new TreeVertex(); v1.pos = m.MultiplyPoint(Vector3.zero); v1.nor = m.MultiplyVector(Vector3.back).normalized; v1.uv0 = new Vector2(0.5f, v); TreeVertex v2 = new TreeVertex(); v2.pos = m.MultiplyPoint(directionB * rad); v2.nor = m.MultiplyVector(normalB).normalized; v2.uv0 = new Vector2(1.0f, v); // Animation properties.. Vector2 windFactors = ComputeWindFactor(node, t); v0.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed); v1.SetAnimationProperties(windFactors.x, windFactors.y, 0.0f, node.animSeed); // no edge flutter for center vertex v2.SetAnimationProperties(windFactors.x, windFactors.y, animationEdge, node.animSeed); verts.Add(v0); verts.Add(v1); verts.Add(v2); if (i > 0) { int voffset = verts.Count; TreeTriangle tri0 = new TreeTriangle(frondMaterialIndex, voffset - 2, voffset - 3, voffset - 6); TreeTriangle tri1 = new TreeTriangle(frondMaterialIndex, voffset - 2, voffset - 6, voffset - 5); tris.Add(tri0); tris.Add(tri1); TreeTriangle tri2 = new TreeTriangle(frondMaterialIndex, voffset - 2, voffset - 4, voffset - 1); TreeTriangle tri3 = new TreeTriangle(frondMaterialIndex, voffset - 2, voffset - 5, voffset - 4); tris.Add(tri2); tris.Add(tri3); } } } } } } // compute ambient occlusion.. if ((buildFlags & (int)BuildFlag.BuildAmbientOcclusion) != 0) { for (int i = vertOffset; i < verts.Count; i++) { verts[i].SetAmbientOcclusion(ComputeAmbientOcclusion(verts[i].pos, verts[i].nor, aoSpheres, aoDensity)); } } node.vertEnd = verts.Count; Profiler.EndSample(); // TreeGroupBranch.UpdateNodeMesh } public void UpdateSpline(TreeNode node) { // locked due to user editing... if (lockFlags != 0) { return; } Random.InitState(node.seed); if (node.spline == null) { TreeSpline spline = new TreeSpline(); node.spline = spline; // Add asset to database.. // UnityEditor.AssetDatabase.AddObjectToAsset(spline, this); } float totalHeight = height.y * node.GetScale(); float stepSize = 1.0f; int count = (int)Mathf.Round(totalHeight / stepSize); float curHeight = 0.0f; Quaternion r = Quaternion.identity; Vector3 p = new Vector3(0, 0, 0); Matrix4x4 worldUp = (node.matrix * GetRootMatrix()).inverse; Quaternion rotPhotropism = MathUtils.QuaternionFromMatrix(worldUp) * Quaternion.Euler(0.0f, node.angle, 0.0f); Quaternion rotGravitropism = MathUtils.QuaternionFromMatrix(worldUp) * Quaternion.Euler(-180.0f, node.angle, 0.0f); node.spline.Reset(); node.spline.AddPoint(p, 0.0f); for (int i = 0; i < count; i++) { float stepPos = stepSize; if (i == (count - 1)) { stepPos = totalHeight - curHeight; } curHeight += stepPos; float curTime = curHeight / totalHeight; // seek towards sun or ground.. float seekValue = Mathf.Clamp(seekCurve.Evaluate(curTime), -1.0f, 1.0f); float seekSun = Mathf.Clamp01(seekValue) * seekBlend; float seekGround = Mathf.Clamp01(-seekValue) * seekBlend; r = Quaternion.Slerp(r, rotPhotropism, seekSun); r = Quaternion.Slerp(r, rotGravitropism, seekGround); // crinkle float crinkle = crinklyness * Mathf.Clamp01(crinkCurve.Evaluate(curTime)); Quaternion c = Quaternion.Euler(new Vector3(180.0f * (Random.value - 0.5f), node.angle, 180.0f * (Random.value - 0.5f))); r = Quaternion.Slerp(r, c, crinkle); // advance position p += r * (new Vector3(0.0f, stepPos, 0.0f)); node.spline.AddPoint(p, curTime); } // Rethink time and rotations node.spline.UpdateTime(); node.spline.UpdateRotations(); } internal override string GroupSeedString { get { return Styles.groupSeedString; } } internal override string FrequencyString { get { return Styles.frequencyString; } } internal override string DistributionModeString { get { return Styles.distributionModeString; } } internal override string TwirlString { get { return Styles.twirlString; } } internal override string WhorledStepString { get { return Styles.whorledStepString; } } internal override string GrowthScaleString { get { return Styles.growthScaleString; } } internal override string GrowthAngleString { get { return Styles.growthAngleString; } } internal override string MainWindString { get { return Styles.mainWindString; } } internal override string MainTurbulenceString { get { return Styles.mainTurbulenceString; } } internal override string EdgeTurbulenceString { get { return Styles.edgeTurbulenceString; } } } }
UnityCsReference/Modules/TreeEditor/Includes/TreeGroupBranch.cs/0
{ "file_path": "UnityCsReference/Modules/TreeEditor/Includes/TreeGroupBranch.cs", "repo_id": "UnityCsReference", "token_count": 26867 }
443
// 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.UIAutomation { class AutomatedWindow<T> : IElementFinder, IDisposable where T : EditorWindow { private readonly T m_EditorWindow; private readonly IMModel m_Model = new IMModel(); //mouseVisualization private Vector2 m_LastMousePosition = new Vector2(-1, -1); private float m_MouseMoveSpeed = 100f; //points/s private float m_LastEventSent = -1f; private bool m_Disposed; private bool m_DeveloperBuild; public T window { get { return m_EditorWindow; } } static AutomatedWindow<T> GetAutomatedWindow() { T window = EditorWindow.GetWindow<T>(); return new AutomatedWindow<T>(window); } //Make sure the events can be visualized public bool isAutomationVisible { set; get; } public AutomatedWindow(T windowToDrive, bool enableStackTraces = false) { m_EditorWindow = windowToDrive; //TODO: find a way to properly pass this data from the runner here. isAutomationVisible = EditorPrefs.GetBool("UnityEditor.PlaymodeTestsRunnerWindow" + ".visualizeUIAutomationEvents", false); //TODO: at the moment you can only debug one GUIView at a time, and nothing prevents from someone else to change who's being debugged. //figure out a way to handle this. m_Model.enableStackTraces = enableStackTraces; GUIViewDebuggerHelper.DebugWindow(m_EditorWindow.m_Parent); GUIViewDebuggerHelper.onViewInstructionsChanged += m_Model.ViewContentsChanged; m_EditorWindow.RepaintImmediately(); //will create all the instructions, and will trigger onViewInstructionsChanged m_Disposed = false; m_DeveloperBuild = Unsupported.IsDeveloperMode(); } ~AutomatedWindow() { if (!m_Disposed && m_DeveloperBuild) Debug.LogWarningFormat("{0} instance finalized without being disposed. Create it inside a using block or manually call Dispose () when done.", this.GetType()); Dispose(); } public void Dispose() { if (m_Disposed) return; GUIViewDebuggerHelper.onViewInstructionsChanged -= m_Model.ViewContentsChanged; GUIViewDebuggerHelper.StopDebugging(); m_Disposed = true; } public void Click(Vector2 editorWindowPosition, EventModifiers modifiers = EventModifiers.None) { var GUIViewPosition = EventUtility.ConvertEditorWindowCoordsToGuiViewCoords(editorWindowPosition); HandleMouseAutomationVisibility(GUIViewPosition); if (EventUtility.Click(window, GUIViewPosition, modifiers)) window.RepaintImmediately(); } public void Click(IAutomatedUIElement element, EventModifiers modifiers = EventModifiers.None) { if (!element.hasRect) { Debug.LogWarning("Cannot click on an element that has no rect"); return; } Click(EventUtility.ConvertGuiViewCoordsToEditorWindowCoords(element.rect.center), modifiers); } //TODO: this will lock up the Editor while 'moving the mouse'. //We need to decide if this is okay, or not. //This is responsible for showing the mouse moving between mouse events. private void HandleMouseAutomationVisibility(Vector2 desiredMousePosition, bool sendMouseDrag = false) { if (!isAutomationVisible) return; if (m_LastMousePosition != desiredMousePosition) { float startTime = (float)EditorApplication.timeSinceStartup; float endTime = startTime + ((m_LastMousePosition - desiredMousePosition).magnitude / m_MouseMoveSpeed); var mouseStart = m_LastMousePosition; while (m_LastMousePosition != desiredMousePosition) { float curtime = (float)EditorApplication.timeSinceStartup; float frac = Mathf.Clamp01((curtime - startTime) / (endTime - startTime)); frac = Easing.Quadratic.InOut(frac); var mousePosition = Vector2.Lerp(mouseStart, desiredMousePosition, frac); //We currently send mouse moves to the window when visualizing the interactions, //But this might create different behaviour when visualizing or not. //This is also true for the Repaint event from RepaintImmediately. //TODO: Decide what to do about it. EventUtility.UpdateMouseMove(window, mousePosition); if (sendMouseDrag) EventUtility.UpdateDragAndDrop(window, mousePosition); m_LastMousePosition = mousePosition; window.RepaintImmediately(); System.Threading.Thread.Sleep(16); } } HandleLastEventPauseVisibility(); } private void HandleLastEventPauseVisibility(float minTimeBetweenEvents = .5f) { if (!isAutomationVisible) return; float now = (float)EditorApplication.timeSinceStartup; var deltaTime = now - m_LastEventSent; if (deltaTime < minTimeBetweenEvents) { int remainderTime = Mathf.CeilToInt((minTimeBetweenEvents - deltaTime) * 100f); System.Threading.Thread.Sleep(remainderTime); } m_LastEventSent = (float)EditorApplication.timeSinceStartup; } public void DragAndDrop(Vector2 start, Vector2 end, EventModifiers modifiers = EventModifiers.None) { BeginDrag(start, modifiers); UpdateDragAndDrop(Vector2.Lerp(start, end, 0.5f)); EndDrop(end, modifiers); } public void BeginDrag(Vector2 start, EventModifiers modifiers = EventModifiers.None) { start = EventUtility.ConvertEditorWindowCoordsToGuiViewCoords(start); HandleMouseAutomationVisibility(start); if (EventUtility.BeginDragAndDrop(window, start, modifiers)) window.RepaintImmediately(); } public void UpdateDragAndDrop(Vector2 pos, EventModifiers modifiers = EventModifiers.None) { pos = EventUtility.ConvertEditorWindowCoordsToGuiViewCoords(pos); HandleMouseAutomationVisibility(pos, true); if (EventUtility.UpdateDragAndDrop(window, pos, modifiers)) window.RepaintImmediately(); window.RepaintImmediately(); } public void EndDrop(Vector2 end, EventModifiers modifiers = EventModifiers.None) { end = EventUtility.ConvertEditorWindowCoordsToGuiViewCoords(end); HandleMouseAutomationVisibility(end, true); if (EventUtility.EndDragAndDrop(window, end, modifiers)) window.RepaintImmediately(); } public void KeyDownAndUp(KeyCode key, EventModifiers modifiers = EventModifiers.None) { HandleLastEventPauseVisibility(); if (EventUtility.KeyDownAndUp(window, key, modifiers)) window.RepaintImmediately(); } // Called from Editor tests public void SendKeyStrokesStream(IEnumerable<KeyCode> keys) { foreach (var key in keys) { KeyDownAndUp(key); } } public IEnumerable<IAutomatedUIElement> FindElementsByGUIStyle(GUIStyle style) { return m_Model.FindElementsByGUIStyle(style); } public IEnumerable<IAutomatedUIElement> FindElementsByGUIContent(GUIContent guiContent) { return m_Model.FindElementsByGUIContent(guiContent); } public IEnumerable<IAutomatedUIElement> FindElementsByNamedControl(string controlName) { return m_Model.FindElementsByNamedControl(controlName); } public IEnumerable<IAutomatedUIElement> FindElementsByGUIContentText(string text) { return m_Model.FindElementsByGUIContentText(text); } public IAutomatedUIElement nextSibling { get { return m_Model.nextSibling; } } } class IMModel : IElementFinder { private readonly List<IMGUIInstruction> m_Instructions = new List<IMGUIInstruction>(); private readonly List<IMGUIClipInstruction> m_ClipList = new List<IMGUIClipInstruction>(); private readonly List<IMGUILayoutInstruction> m_LayoutList = new List<IMGUILayoutInstruction>(); private readonly List<IMGUINamedControlInstruction> m_NamedControlList = new List<IMGUINamedControlInstruction>(); private readonly List<IMGUIDrawInstruction> m_DrawInstructions = new List<IMGUIDrawInstruction>(); private AutomatedIMElement[] m_Elements; private AutomatedIMElement m_Root; public bool enableStackTraces { get; set; } public void Update() { GUIViewDebuggerHelper.GetUnifiedInstructions(m_Instructions, enableStackTraces); GUIViewDebuggerHelper.GetLayoutInstructions(m_LayoutList, enableStackTraces); GUIViewDebuggerHelper.GetClipInstructions(m_ClipList, enableStackTraces); GUIViewDebuggerHelper.GetDrawInstructions(m_DrawInstructions, enableStackTraces); GUIViewDebuggerHelper.GetNamedControlInstructions(m_NamedControlList); GenerateDom(); } private void GenerateDom() { int total = m_Instructions.Count; if (m_Elements == null || m_Elements.Length != total) m_Elements = new AutomatedIMElement[total]; m_Root = new AutomatedIMElement(this, -1); m_Root.descendants = new ArraySegment<AutomatedIMElement>(m_Elements); Stack<AutomatedIMElement> ancestors = new Stack<AutomatedIMElement>(); Stack<int> ancestorsIndex = new Stack<int>(); ancestors.Push(m_Root); ancestorsIndex.Push(-1); for (int i = 0; i < total; ++i) { var instruction = m_Instructions[i]; var parent = ancestors.Peek(); AutomatedIMElement element = CreateAutomatedElement(instruction, i); m_Elements[i] = element; element.parent = parent; parent.AddChild(element); if (i + 1 < total) { var nextInstruction = m_Instructions[i + 1]; if (nextInstruction.level > instruction.level) { ancestors.Push(element); ancestorsIndex.Push(i); } if (nextInstruction.level < instruction.level) { for (int j = instruction.level - nextInstruction.level; j > 0; --j) { var closingParent = ancestors.Pop(); var closingParentIndex = ancestorsIndex.Pop(); closingParent.descendants = new ArraySegment<AutomatedIMElement>(m_Elements, closingParentIndex + 1, i - closingParentIndex); } } } } while (ancestors.Peek() != m_Root) { var closingParent = ancestors.Pop(); var closingParentIndex = ancestorsIndex.Pop(); closingParent.descendants = new ArraySegment<AutomatedIMElement>(m_Elements, closingParentIndex, (total - 1) - closingParentIndex); } } private AutomatedIMElement CreateAutomatedElement(IMGUIInstruction imguiInstruction, int index) { AutomatedIMElement element = new AutomatedIMElement(this, index); element.enabled = imguiInstruction.enabled; switch (imguiInstruction.type) { case InstructionType.kStyleDraw: { var drawInstruction = m_DrawInstructions[imguiInstruction.typeInstructionIndex]; element.rect = drawInstruction.rect; element.style = drawInstruction.usedGUIStyle; element.guiContent = drawInstruction.usedGUIContent; break; } case InstructionType.kLayoutBeginGroup: { var layoutInstruction = m_LayoutList[imguiInstruction.typeInstructionIndex]; element.rect = layoutInstruction.unclippedRect; element.style = layoutInstruction.style; break; } case InstructionType.kLayoutNamedControl: { var namedControlInstruction = m_NamedControlList[imguiInstruction.typeInstructionIndex]; element.rect = namedControlInstruction.rect; element.controlName = namedControlInstruction.name; break; } } return element; } public IEnumerable<IAutomatedUIElement> FindElementsByGUIStyle(GUIStyle style) { return m_Root.FindElementsByGUIStyle(style); } public IEnumerable<IAutomatedUIElement> FindElementsByGUIContent(GUIContent guiContent) { return m_Root.FindElementsByGUIContent(guiContent); } public IEnumerable<IAutomatedUIElement> FindElementsByNamedControl(string controlName) { return m_Root.FindElementsByNamedControl(controlName); } public IEnumerable<IAutomatedUIElement> FindElementsByGUIContentText(string text) { return m_Root.FindElementsByGUIContentText(text); } public IAutomatedUIElement nextSibling { get { return m_Root.nextSibling; } } public void ViewContentsChanged() { //TODO: we dont need to update everytime the view actually change, we just need to "dirty" the current state //and update before we actually need the date to be synced. Update(); } } interface IElementFinder { IEnumerable<IAutomatedUIElement> FindElementsByGUIStyle(GUIStyle style); IEnumerable<IAutomatedUIElement> FindElementsByGUIContent(GUIContent guiContent); IEnumerable<IAutomatedUIElement> FindElementsByNamedControl(string controlName); /// <summary>Work-around for finding UI elements for which we do not have a recognizable GUIContent. /// Searches children elements recursively for recognizable text from GUIContents.</summary> IEnumerable<IAutomatedUIElement> FindElementsByGUIContentText(string text); IAutomatedUIElement nextSibling { get; } } interface IAutomatedUIElement : IElementFinder { string name { get; } IList<IAutomatedUIElement> children { get; } IAutomatedUIElement parent { get; } bool hasRect { get; } Rect rect { get; } bool hasControlName { get; } string controlName { get; } bool enabled { get; } GUIStyle style { get; } GUIContent guiContent { get; } } class AutomatedIMElement : IAutomatedUIElement { #pragma warning disable 414 private IMModel m_ModelOwner; private int m_instructionIndex; #pragma warning restore 414 private Rect? m_Rect; private List<IAutomatedUIElement> m_Children = new List<IAutomatedUIElement>(); public AutomatedIMElement(IMModel model, int index) { m_ModelOwner = model; m_instructionIndex = index; } public string name { get; } public IList<IAutomatedUIElement> children { get { return m_Children; } } public IAutomatedUIElement parent { get; set; } public bool enabled { get; set; } public IAutomatedUIElement nextSibling { get { if (parent == null) return null; //TODO: this is a silly implementaiton. we can probably do better. var siblings = parent.children; for (int i = 0; i < siblings.Count; ++i) { if (siblings[i] == this) { if (i + 1 < siblings.Count) return siblings[i + 1]; break; } } return null; } } public bool hasRect { get { return m_Rect.HasValue; } } public Rect rect { get { if (!hasRect) throw new InvalidOperationException("Element does not contain rect info"); return m_Rect.Value; } set { m_Rect = value; } } public bool hasControlName { get { return controlName != null; } } public string controlName { get; set; } public GUIStyle style { get; set; } public GUIContent guiContent { get; set; } public ArraySegment<AutomatedIMElement> descendants { get; set; } public void AddChild(AutomatedIMElement element) { m_Children.Add(element); } protected virtual IEnumerable<IAutomatedUIElement> FindElements(Func<IAutomatedUIElement, bool> predicate) { if (predicate == null) throw new ArgumentNullException("predicate"); // In the future, ArraySegment implements IEnumerable<T>... for (int i = 0; i < descendants.Count; ++i) { IAutomatedUIElement element = descendants.Array[descendants.Offset + i]; if (predicate(element)) yield return element; } } public IEnumerable<IAutomatedUIElement> FindElementsByGUIStyle(GUIStyle style) { return FindElements(element => element.style == style); } public IEnumerable<IAutomatedUIElement> FindElementsByNamedControl(string controlName) { return FindElements(element => element.controlName == controlName); } public IEnumerable<IAutomatedUIElement> FindElementsByGUIContentText(string text) { foreach (IAutomatedUIElement matchingElement in FindElementsByGUIContentTextRecursive(children, text)) yield return matchingElement; } private static IEnumerable<IAutomatedUIElement> FindElementsByGUIContentTextRecursive(IEnumerable<IAutomatedUIElement> elements, string text) { if (elements == null) yield break; foreach (IAutomatedUIElement childElement in elements) { if (childElement.guiContent?.text?.Equals(text) ?? false) yield return childElement; foreach (IAutomatedUIElement matchingSiblingElement in FindElementsByGUIContentTextRecursive(childElement.children, text)) yield return matchingSiblingElement; } } private static string NullOrEmptyToNull(string input) { return string.IsNullOrEmpty(input) ? null : input; } private static bool GUIContentsAreEqual(GUIContent content1, GUIContent content2) { if (content1 == content2) return true; if (content1 == null || content2 == null) return false; // The native string type UTF16String does not differentiate between empty and null strings // Empty and null strings are considered equal here to work around this issue return NullOrEmptyToNull(content1.text) == NullOrEmptyToNull(content2.text) && content1.image == content2.image && NullOrEmptyToNull(content1.tooltip) == NullOrEmptyToNull(content2.tooltip); } public IEnumerable<IAutomatedUIElement> FindElementsByGUIContent(GUIContent guiContent) { return FindElements(element => GUIContentsAreEqual(element.guiContent, guiContent)); } } }
UnityCsReference/Modules/UIAutomationEditor/AutomatedWindow.cs/0
{ "file_path": "UnityCsReference/Modules/UIAutomationEditor/AutomatedWindow.cs", "repo_id": "UnityCsReference", "token_count": 9661 }
444
// 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; using System.Collections.Generic; using UnityEditor; using System; using System.IO; using UnityEditor.UIElements; using Object = UnityEngine.Object; using VisualElement = UnityEngine.UIElements.VisualElement; namespace Unity.UI.Builder { [Serializable] [ExtensionOfNativeClass] class BuilderDocumentOpenUXML { // // Serialized Data // [SerializeField] List<BuilderDocumentOpenUSS> m_OpenUSSFiles = new List<BuilderDocumentOpenUSS>(); [SerializeField] string m_OpenendVisualTreeAssetOldPath; [SerializeField] VisualTreeAsset m_VisualTreeAsset; [SerializeField] StyleSheet m_ActiveStyleSheet; [SerializeField] BuilderDocumentSettings m_Settings; [SerializeField] int m_OpenSubDocumentParentIndex = -1; [SerializeField] int m_OpenSubDocumentParentSourceTemplateAssetIndex = -1; // // Unserialized Data // bool m_HasUnsavedChanges; bool m_DocumentBeingSavedExplicitly; BuilderUXMLFileSettings m_FileSettings; BuilderDocument m_Document; VisualElement m_CurrentDocumentRootElement; VisualTreeAsset m_VisualTreeAssetBackup; // // Getters // // Used in tests internal bool isBackupSet => m_VisualTreeAssetBackup != null; public BuilderUXMLFileSettings fileSettings => m_FileSettings ?? (m_FileSettings = new BuilderUXMLFileSettings(visualTreeAsset)); internal List<BuilderDocumentOpenUXML> openUXMLFiles { get { // Find or create document. if (m_Document == null) { var allDocuments = Resources.FindObjectsOfTypeAll(typeof(BuilderDocument)); if (allDocuments.Length > 1) Debug.LogError("UIBuilder: More than one BuilderDocument was somehow created!"); if (allDocuments.Length == 0) m_Document = BuilderDocument.CreateInstance(); else m_Document = allDocuments[0] as BuilderDocument; } if (m_Document == null) return null; return m_Document.openUXMLFiles; } } public StyleSheet activeStyleSheet { get { if (m_ActiveStyleSheet == null) m_ActiveStyleSheet = firstStyleSheet; return m_ActiveStyleSheet; } } public BuilderDocumentSettings settings { get { // If this uxmnl is being edited in place then use the parent document's settings if (isChildSubDocument && openSubDocumentParentSourceTemplateAssetIndex != -1) { m_Settings = openSubDocumentParent.settings; } else { m_Settings = BuilderDocumentSettings.CreateOrLoadSettingsObject(m_Settings, uxmlPath); } return m_Settings; } } public string uxmlFileName { get { var path = uxmlPath; if (path == null) return null; var fileName = Path.GetFileName(path); return fileName; } } public string uxmlOldPath { get { return m_OpenendVisualTreeAssetOldPath; } } public string uxmlPath { get { return AssetDatabase.GetAssetPath(m_VisualTreeAsset); } } public List<string> ussPaths { get { var paths = new List<string>(); for (int i = 0; i < m_OpenUSSFiles.Count; ++i) paths.Add(m_OpenUSSFiles[i].assetPath); return paths; } } public VisualTreeAsset visualTreeAsset { get { if (m_VisualTreeAsset == null) m_VisualTreeAsset = VisualTreeAssetUtilities.CreateInstance(); return m_VisualTreeAsset; } } public StyleSheet firstStyleSheet { get { return m_OpenUSSFiles.Count > 0 ? m_OpenUSSFiles[0].styleSheet : null; } } public List<BuilderDocumentOpenUSS> openUSSFiles => m_OpenUSSFiles; public bool isChildSubDocument => openSubDocumentParentIndex > -1; public BuilderDocumentOpenUXML openSubDocumentParent => isChildSubDocument ? openUXMLFiles[openSubDocumentParentIndex] : null; // // Getter/Setters // public bool hasUnsavedChanges { get { return m_HasUnsavedChanges; } set { if (value == m_HasUnsavedChanges) return; m_HasUnsavedChanges = value; } } public bool isAnonymousDocument { get { return string.IsNullOrEmpty(uxmlPath); } } public float viewportZoomScale { get { return settings.ZoomScale; } set { settings.ZoomScale = value; settings.SaveSettingsToDisk(); } } public Vector2 viewportContentOffset { get { return settings.PanOffset; } set { settings.PanOffset = value; settings.SaveSettingsToDisk(); } } public int openSubDocumentParentIndex { get { return m_OpenSubDocumentParentIndex; } set { m_OpenSubDocumentParentIndex = value; } } public int openSubDocumentParentSourceTemplateAssetIndex { get { return m_OpenSubDocumentParentSourceTemplateAssetIndex; } set { m_OpenSubDocumentParentSourceTemplateAssetIndex = value; } } // // Initialize / Construct / Enable / Clear // public void Clear() { ClearUndo(); RestoreAssetsFromBackup(); ClearBackups(); m_OpenendVisualTreeAssetOldPath = string.Empty; m_ActiveStyleSheet = null; m_FileSettings = null; if (m_VisualTreeAsset != null) { if (!AssetDatabase.Contains(m_VisualTreeAsset)) m_VisualTreeAsset.Destroy(); m_VisualTreeAsset = null; } m_OpenUSSFiles.Clear(); m_Settings = null; } // // Styles // public void RefreshStyle(VisualElement documentRootElement) { if (m_CurrentDocumentRootElement == null) m_CurrentDocumentRootElement = documentRootElement; StyleCache.ClearStyleCache(); UnityEngine.UIElements.StyleSheets.StyleSheetCache.ClearCaches(); foreach (var openUSS in m_OpenUSSFiles) openUSS.FixRuleReferences(); m_CurrentDocumentRootElement.IncrementVersion((VersionChangeType) (-1)); } public void MarkStyleSheetsDirty() { foreach (var openUSS in m_OpenUSSFiles) EditorUtility.SetDirty(openUSS.styleSheet); } public void AddStyleSheetToDocument(StyleSheet styleSheet, string ussPath) { var newOpenUssFile = new BuilderDocumentOpenUSS(); newOpenUssFile.Set(styleSheet, ussPath); m_OpenUSSFiles.Add(newOpenUssFile); AddStyleSheetsToAllRootElements(); hasUnsavedChanges = true; } public void RemoveStyleSheetFromDocument(int ussIndex) { RemoveStyleSheetFromLists(ussIndex); AddStyleSheetsToAllRootElements(); hasUnsavedChanges = true; } void AddStyleSheetsToRootAsset(VisualElementAsset rootAsset, string newUssPath = null, int newUssIndex = 0) { if (rootAsset.fullTypeName == BuilderConstants.SelectedVisualTreeAssetSpecialElementTypeName) return; rootAsset.ClearStyleSheets(); for (int i = 0; i < m_OpenUSSFiles.Count; ++i) { var localUssPath = m_OpenUSSFiles[i].assetPath; if (!string.IsNullOrEmpty(newUssPath) && i == newUssIndex) localUssPath = newUssPath; if (string.IsNullOrEmpty(localUssPath)) continue; rootAsset.AddStyleSheet(m_OpenUSSFiles[i].styleSheet); rootAsset.AddStyleSheetPath(localUssPath); } } void RemoveStyleSheetsFromRootAsset(VisualElementAsset rootAsset) { if (rootAsset.fullTypeName == BuilderConstants.SelectedVisualTreeAssetSpecialElementTypeName) return; for (int i = 0; i < m_OpenUSSFiles.Count; ++i) { var localUssPath = m_OpenUSSFiles[i].assetPath; if (string.IsNullOrEmpty(localUssPath)) continue; rootAsset.RemoveStyleSheet(m_OpenUSSFiles[i].styleSheet); rootAsset.RemoveStyleSheetPath(localUssPath); } } // For the near to mid term, we have this code that cleans up any // existing root element stylesheets. void RemoveLegacyStyleSheetsFromRootAssets() { foreach (var asset in visualTreeAsset.visualElementAssets) { if (!visualTreeAsset.IsRootElement(asset)) continue; // Not a root asset. RemoveStyleSheetsFromRootAsset(asset); } foreach (var asset in visualTreeAsset.templateAssets) { if (!visualTreeAsset.IsRootElement(asset)) continue; // Not a root asset. RemoveStyleSheetsFromRootAsset(asset); } } public void AddStyleSheetsToAllRootElements(string newUssPath = null, int newUssIndex = 0) { var rootVEA = visualTreeAsset.GetRootUxmlElement(); AddStyleSheetsToRootAsset(rootVEA, newUssPath, newUssIndex); } void RemoveStyleSheetFromLists(int ussIndex) { var openUSSFile = m_OpenUSSFiles[ussIndex]; m_OpenUSSFiles.RemoveAt(ussIndex); openUSSFile.Clear(); } public void UpdateActiveStyleSheet(BuilderSelection selection, StyleSheet styleSheet, IBuilderSelectionNotifier source) { if (m_ActiveStyleSheet == styleSheet) return; m_ActiveStyleSheet = styleSheet; selection.ForceReselection(source); } public bool SaveUnsavedChanges(string manualUxmlPath = null, bool isSaveAs = false) { return SaveNewDocument(null, isSaveAs, out var needsFullRefresh, manualUxmlPath); } public bool SaveNewDocument( VisualElement documentRootElement, bool isSaveAs, out bool needsFullRefresh, string manualUxmlPath = null) { needsFullRefresh = false; // Re-use or ask the user for the UXML path. var newUxmlPath = uxmlPath; if (string.IsNullOrEmpty(newUxmlPath) || isSaveAs) { if (!string.IsNullOrEmpty(manualUxmlPath)) { newUxmlPath = manualUxmlPath; } else { newUxmlPath = BuilderDialogsUtility.DisplaySaveFileDialog("Save UXML", null, null, "uxml"); if (newUxmlPath == null) // User cancelled the save dialog. return false; } } ClearUndo(); var startTime = DateTime.UtcNow; var savedUSSFiles = new List<BuilderDocumentOpenUSS>(); // Save USS files. foreach (var openUSSFile in m_OpenUSSFiles) { if (openUSSFile.SaveToDisk(visualTreeAsset)) { savedUSSFiles.Add(openUSSFile); } } var oldUxmlTest = m_VisualTreeAssetBackup?.GenerateUXML(m_OpenendVisualTreeAssetOldPath, true); // Save UXML files // Saving all open UXML files to ensure references correct upon changes in child documents. foreach (var openUXMLFile in openUXMLFiles) openUXMLFile.PreSaveSyncBackup(); bool shouldSave = m_OpenendVisualTreeAssetOldPath != newUxmlPath; var uxmlText = visualTreeAsset.GenerateUXML(newUxmlPath, true); if (uxmlText != null) { if (!shouldSave && m_VisualTreeAssetBackup) { shouldSave = oldUxmlTest != uxmlText; } if (shouldSave) { WriteUXMLToFile(newUxmlPath, uxmlText); } } // Once we wrote all the files to disk, we refresh the DB and reload // the files from the AssetDatabase. m_DocumentBeingSavedExplicitly = true; try { AssetDatabase.Refresh(); } finally { m_DocumentBeingSavedExplicitly = false; } // Reorder document after reimporting VisualTreeAssetUtilities.ReOrderDocument(m_VisualTreeAsset); // Check if any USS assets have changed reload them. foreach (var openUSSFile in savedUSSFiles) needsFullRefresh |= openUSSFile.PostSaveToDiskChecksAndFixes(); // Check if any UXML assets have changed and reload them. // Saving all open UXML files to ensure references correct upon changes in child subdocuments. foreach (var openUXMLFile in openUXMLFiles) needsFullRefresh |= openUXMLFile.PostSaveToDiskChecksAndFixes(this == openUXMLFile ? newUxmlPath : null, needsFullRefresh); if (needsFullRefresh) { // Copy previous document settings. if (m_Settings != null) { m_Settings.UxmlGuid = AssetDatabase.AssetPathToGUID(newUxmlPath); m_Settings.UxmlPath = newUxmlPath; m_Settings.SaveSettingsToDisk(); } // Reset asset name. m_VisualTreeAsset.name = Path.GetFileNameWithoutExtension(newUxmlPath); m_OpenendVisualTreeAssetOldPath = newUxmlPath; } if (documentRootElement != null) ReloadDocumentToCanvas(documentRootElement); hasUnsavedChanges = false; var assetSize = uxmlText?.Length ?? 0; BuilderAnalyticsUtility.SendSaveEvent(startTime, this, newUxmlPath, assetSize); return true; } private void SetInlineStyleRecursively(VisualElement ve) { if (ve == null) { return; } var inlineSheet = m_VisualTreeAsset.inlineSheet; var vea = ve.GetVisualElementAsset(); if (vea != null && vea.ruleIndex != -1) { var rule = inlineSheet.rules[vea.ruleIndex]; ve.UpdateInlineRule(inlineSheet, rule); } var children = ve.Children(); foreach (var child in children) { SetInlineStyleRecursively(child); } } internal bool SaveNewTemplateFileFromHierarchy(string newTemplatePath, string uxml) { var isReplacingFile = File.Exists(newTemplatePath); bool isReplacingFileInHierarchy = false; if (isReplacingFile) { var replacedVTA = EditorGUIUtility.Load(newTemplatePath) as VisualTreeAsset; isReplacingFileInHierarchy = replacedVTA.TemplateExists(m_VisualTreeAsset); if (isReplacingFileInHierarchy && hasUnsavedChanges) { // If we are replacing an element in the hierarchy and there is unsaved changes, // we need to save to make sure we don't lose any elements var saveUnsavedChanges = BuilderDialogsUtility.DisplayDialog( BuilderConstants.SaveDialogSaveChangesPromptTitle, BuilderConstants.SaveDialogReplaceWithNewTemplateMessage, BuilderConstants.DialogSaveActionOption, BuilderConstants.DialogCancelOption); if (saveUnsavedChanges) { var wasDocumentSaved = SaveUnsavedChanges(); if (!wasDocumentSaved) { // Save failed Debug.LogError("Saving the current template failed. New template will not be created."); return false; } } else { // Save cancelled return false; } } } if (isReplacingFileInHierarchy) { // This is necessary to make sure we don't show the external changes popup // since we are creating a new template m_DocumentBeingSavedExplicitly = true; } File.WriteAllText(newTemplatePath, uxml); AssetDatabase.Refresh(); if (isReplacingFileInHierarchy) { m_DocumentBeingSavedExplicitly = false; } return true; } public bool CheckForUnsavedChanges(bool assetModifiedExternally = false) { if (!hasUnsavedChanges) return true; if (assetModifiedExternally) { // TODO: Nothing can be done here yet, other than telling the user // what just happened. Adding the ability to save unsaved changes // after a file has been modified externally will require some // major changes to the document flow. var promptTitle = string.Format(BuilderConstants.SaveDialogExternalChangesPromptTitle, uxmlPath); BuilderDialogsUtility.DisplayDialog( promptTitle, BuilderConstants.SaveDialogExternalChangesPromptMessage); return true; } else { var option = BuilderDialogsUtility.DisplayDialogComplex( BuilderConstants.SaveDialogSaveChangesPromptTitle, BuilderConstants.SaveDialogSaveChangesPromptMessage, BuilderConstants.DialogSaveActionOption, BuilderConstants.DialogCancelOption, BuilderConstants.DialogDontSaveActionOption); switch (option) { // Save case 0: return SaveUnsavedChanges(); // Cancel case 1: return false; // Don't Save case 2: RestoreAssetsFromBackup(); return true; } } return true; } public void NewDocument(VisualElement documentRootElement) { Clear(); ClearCanvasDocumentRootElement(documentRootElement); hasUnsavedChanges = false; } public void LoadDocument(VisualTreeAsset visualTreeAsset, VisualElement documentElement) { NewDocument(documentElement); if (visualTreeAsset == null) return; m_VisualTreeAssetBackup = visualTreeAsset.DeepCopy(); m_VisualTreeAsset = visualTreeAsset; // Re-stamp orderInDocument values using BuilderConstants.VisualTreeAssetOrderIncrement VisualTreeAssetUtilities.ReOrderDocument(m_VisualTreeAsset); PostLoadDocumentStyleSheetCleanup(); hasUnsavedChanges = false; m_OpenendVisualTreeAssetOldPath = AssetDatabase.GetAssetPath(m_VisualTreeAsset); m_Settings = BuilderDocumentSettings.CreateOrLoadSettingsObject(m_Settings, uxmlPath); ReloadDocumentToCanvas(documentElement); } public void PostLoadDocumentStyleSheetCleanup() { m_VisualTreeAsset.UpdateUsingEntries(); m_OpenUSSFiles.Clear(); // Load styles. var styleSheetsUsed = m_VisualTreeAsset.GetAllReferencedStyleSheets(); for (int i = 0; i < styleSheetsUsed.Count; ++i) AddStyleSheetToDocument(styleSheetsUsed[i], null); // For the near to mid term, we have this code that cleans up any // existing root element stylesheets. RemoveLegacyStyleSheetsFromRootAssets(); hasUnsavedChanges = false; } private void LoadVisualTreeAsset(VisualTreeAsset newVisualTreeAsset) { var builderWindow = Builder.ActiveWindow; if (builderWindow == null) builderWindow = Builder.ShowWindow(); if (string.IsNullOrEmpty(uxmlPath)) builderWindow.toolbar.ReloadDocument(); else builderWindow.toolbar.LoadDocument(newVisualTreeAsset, false, true); } // // Asset Change Detection // public void OnPostProcessAsset(string assetPath) { if (m_DocumentBeingSavedExplicitly) return; var newVisualTreeAsset = m_VisualTreeAsset; var isCurrentDocumentBeingProcessed = assetPath == uxmlOldPath; var wasCurrentDocumentRenamed = uxmlPath == assetPath && assetPath != uxmlOldPath; if (isCurrentDocumentBeingProcessed || wasCurrentDocumentRenamed) { newVisualTreeAsset = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(assetPath); } else { bool found = false; foreach (var openUSSFile in m_OpenUSSFiles) if (found = openUSSFile.CheckPostProcessAssetIfFileChanged(assetPath)) break; if (!found) return; } // LoadDocument() will call Clear() which will try to restore from Backup(). // If we don't clear the Backups here, they will overwrite the newly post-processed // and re-imported asset we detected here. ClearBackups(); if (EditorWindow.HasOpenInstances<Builder>()) { // LoadVisualTreeAsset needs to be delayed to ensure that this is called later, while in a correct state. EditorApplication.delayCall += () => LoadVisualTreeAsset(newVisualTreeAsset); } } // // Selection // public void HierarchyChanged(VisualElement element) { hasUnsavedChanges = true; } public void StylingChanged() { hasUnsavedChanges = true; // Make sure active stylesheet is still in the document. ValidateActiveStyleSheet(); } // // Serialization // void ValidateActiveStyleSheet() { bool found = false; foreach (var openUSSFile in m_OpenUSSFiles) { if (m_ActiveStyleSheet != openUSSFile.styleSheet) continue; found = true; break; } if (!found) m_ActiveStyleSheet = firstStyleSheet; } // // Serialization // public void OnAfterBuilderDeserialize(VisualElement documentRootElement) { // Refresh StyleSheets. var styleSheetsUsed = m_VisualTreeAsset.GetAllReferencedStyleSheets(); while (m_OpenUSSFiles.Count < styleSheetsUsed.Count) m_OpenUSSFiles.Add(new BuilderDocumentOpenUSS()); // Make sure active stylesheet is still in the document. ValidateActiveStyleSheet(); for (int i = 0; i < styleSheetsUsed.Count; ++i) { if (m_OpenUSSFiles[i].styleSheet == styleSheetsUsed[i] && m_OpenUSSFiles[i].backupStyleSheet != null) { continue; } m_OpenUSSFiles[i].Set(styleSheetsUsed[i], null); } while (m_OpenUSSFiles.Count > styleSheetsUsed.Count) { var lastIndex = m_OpenUSSFiles.Count - 1; RemoveStyleSheetFromLists(lastIndex); } // Fix unserialized rule references in Selectors in StyleSheets. // VTA.inlineSheet only has Rules so it does not need this fix. foreach (var openUSSFile in m_OpenUSSFiles) openUSSFile.FixRuleReferences(); ReloadDocumentToCanvas(documentRootElement); } public void OnAfterDeserialize() { // Fix unserialized rule references in Selectors in StyleSheets. // VTA.inlineSheet only has Rules so it does not need this fix. foreach (var openUSSFile in m_OpenUSSFiles) openUSSFile.FixRuleReferences(); } public void OnAfterLoadFromDisk() { if (m_VisualTreeAsset != null) { // Very important we convert asset references to paths here after a restore. m_VisualTreeAsset.UpdateUsingEntries(); // Make sure we have a backup after loading from disk m_VisualTreeAssetBackup = m_VisualTreeAsset.DeepCopy(); } } // // Private Utilities // public void RestoreAssetsFromBackup() { foreach (var openUSSFile in m_OpenUSSFiles) openUSSFile.RestoreFromBackup(); if (m_VisualTreeAsset != null && m_VisualTreeAssetBackup != null) { m_VisualTreeAssetBackup.DeepOverwrite(m_VisualTreeAsset); EditorUtility.SetDirty(m_VisualTreeAsset); if (hasUnsavedChanges && !isAnonymousDocument) { BuilderAssetUtilities.LiveReload(BuilderAssetUtilities.LiveReloadChanges.Hierarchy | BuilderAssetUtilities.LiveReloadChanges.Styles); } } hasUnsavedChanges = false; } // internal because it's used in tests internal void ClearBackups() { m_VisualTreeAssetBackup.Destroy(); m_VisualTreeAssetBackup = null; foreach (var openUSSFile in m_OpenUSSFiles) openUSSFile.ClearBackup(); } void ClearUndo() { // Destroy temp serialized data needed for undo/redo if (m_CurrentDocumentRootElement != null) { var elements = m_CurrentDocumentRootElement.Query<VisualElement>(); elements.ForEach(x => { var tempSerializedData = x.GetProperty(BuilderConstants.InspectorTempSerializedDataPropertyName) as Object; if (tempSerializedData == null) { return; } Object.DestroyImmediate(tempSerializedData); }); } m_VisualTreeAsset.ClearUndo(); foreach (var openUSSFile in m_OpenUSSFiles) openUSSFile.ClearUndo(); } bool WriteUXMLToFile(string uxmlPath) { var uxmlText = visualTreeAsset.GenerateUXML(uxmlPath, true); // This will only be null (not empty) if the UXML is invalid in some way. if (uxmlText == null) return false; return WriteUXMLToFile(uxmlPath, uxmlText); } bool WriteUXMLToFile(string uxmlPath, string uxmlText) { // Make sure the folders exist. var uxmlFolder = Path.GetDirectoryName(uxmlPath); if (!Directory.Exists(uxmlFolder)) Directory.CreateDirectory(uxmlFolder); return BuilderAssetUtilities.WriteTextFileToDisk(uxmlPath, uxmlText); } VisualElement ReloadChildToCanvas(BuilderDocumentOpenUXML childOpenUXML, VisualElement rootElement) { var childRootElement = rootElement; if (childOpenUXML.openSubDocumentParentSourceTemplateAssetIndex > -1) { var parentOpenUXML = openUXMLFiles[childOpenUXML.openSubDocumentParentIndex]; rootElement = ReloadChildToCanvas(parentOpenUXML, rootElement); var targetTemplateAsset = parentOpenUXML.visualTreeAsset.templateAssets[childOpenUXML.openSubDocumentParentSourceTemplateAssetIndex]; var templateContainerQuery = rootElement.Query<TemplateContainer>().Where(container => container.GetProperty(BuilderConstants.ElementLinkedVisualElementAssetVEPropertyName) as TemplateAsset == targetTemplateAsset); var foundTemplateContainer = templateContainerQuery.First(); childRootElement = foundTemplateContainer; } ReloadDocumentHierarchyToCanvas(childOpenUXML.visualTreeAsset, childRootElement); childOpenUXML.ReloadStyleSheetsToCanvas(childRootElement); return childRootElement; } void ClearCanvasDocumentRootElement(VisualElement documentRootElement) { if (documentRootElement == null) return; documentRootElement.Clear(); ResetCanvasDocumentRootElementStyleSheets(documentRootElement); BuilderSharedStyles.ClearContainer(documentRootElement); documentRootElement.SetProperty( BuilderConstants.ElementLinkedVisualTreeAssetVEPropertyName, visualTreeAsset); } internal void ResetCanvasDocumentRootElementStyleSheets(VisualElement documentRootElement) { documentRootElement.styleSheets.Clear(); // Restore the active theme stylesheet if (documentRootElement.HasProperty(BuilderConstants.ElementLinkedActiveThemeStyleSheetVEPropertyName)) { var activeThemeStyleSheet = documentRootElement.GetProperty(BuilderConstants.ElementLinkedActiveThemeStyleSheetVEPropertyName) as StyleSheet; if (activeThemeStyleSheet != null) { documentRootElement.styleSheets.Add(activeThemeStyleSheet); } } } void ReloadDocumentToCanvas(VisualElement documentRootElement) { if (documentRootElement == null) return; ClearCanvasDocumentRootElement(documentRootElement); if (visualTreeAsset == null) return; var childRootElement = ReloadChildToCanvas(this, documentRootElement); ReloadStyleSheetElements(documentRootElement); // Lighten opacity of all sibling documents throughout hierarchy var currentRoot = childRootElement; while (currentRoot != documentRootElement) { var currentParent = currentRoot.parent; foreach (var sibling in currentParent.Children()) { if (sibling == currentRoot) continue; sibling.style.opacity = BuilderConstants.OpacityFadeOutFactor; } currentRoot = currentParent; } } void ReloadDocumentHierarchyToCanvas(VisualTreeAsset vta, VisualElement parentElement) { if (parentElement == null) return; parentElement.Clear(); // Load the asset. try { vta.LinkedCloneTree(parentElement); } catch (Exception e) { Debug.LogError("Invalid UXML or USS: " + e.ToString()); Clear(); } parentElement.SetProperty( BuilderConstants.ElementLinkedVisualTreeAssetVEPropertyName, vta); } void ReloadStyleSheetsToCanvas(VisualElement documentRootElement) { m_CurrentDocumentRootElement = documentRootElement; // Refresh styles. RefreshStyle(documentRootElement); } void ReloadStyleSheetElements(VisualElement documentRootElement) { // Add shared styles. BuilderSharedStyles.ClearContainer(documentRootElement); BuilderSharedStyles.AddSelectorElementsFromStyleSheet(documentRootElement, m_OpenUSSFiles); var parentIndex = openSubDocumentParentIndex; while (parentIndex > -1) { var parentUXML = openUXMLFiles[parentIndex]; var parentUSSFiles = parentUXML.openUSSFiles; BuilderSharedStyles.AddSelectorElementsFromStyleSheet(documentRootElement, parentUSSFiles, m_OpenUSSFiles.Count, true, parentUXML.uxmlFileName); parentIndex = parentUXML.openSubDocumentParentIndex; } } void PreSaveSyncBackup() { if (m_VisualTreeAssetBackup == null) m_VisualTreeAssetBackup = m_VisualTreeAsset.DeepCopy(); else m_VisualTreeAsset.DeepOverwrite(m_VisualTreeAssetBackup); } bool PostSaveToDiskChecksAndFixes(string newUxmlPath, bool needsFullRefresh) { var oldVTAReference = m_VisualTreeAsset; var oldUxmlPath = uxmlPath; var hasNewUxmlPath = !string.IsNullOrEmpty(newUxmlPath) && newUxmlPath != oldUxmlPath; var localUxmlPath = !string.IsNullOrEmpty(newUxmlPath) ? newUxmlPath : oldUxmlPath; m_VisualTreeAsset = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(localUxmlPath); var newIsDifferentFromOld = m_VisualTreeAsset != oldVTAReference; // If we have a new uxmlPath, it means we're saving as and we need to reset the // original document to stock. if (hasNewUxmlPath && newIsDifferentFromOld && !string.IsNullOrEmpty(oldUxmlPath)) { m_DocumentBeingSavedExplicitly = true; AssetDatabase.ImportAsset(oldUxmlPath, ImportAssetOptions.ForceUpdate); m_DocumentBeingSavedExplicitly = false; } needsFullRefresh |= newIsDifferentFromOld; // Check if the UXML asset has changed and reload it. if (needsFullRefresh) { // To get all the selection markers into the new assets. m_VisualTreeAssetBackup.DeepOverwrite(m_VisualTreeAsset); m_VisualTreeAsset.UpdateUsingEntries(); // Update hash. Otherwise we end up with the old overwritten contentHash var hash = UXMLImporterImpl.GenerateHash(localUxmlPath); m_VisualTreeAsset.contentHash = hash.GetHashCode(); } return needsFullRefresh; } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Document/BuilderDocumentOpenUXML.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Document/BuilderDocumentOpenUXML.cs", "repo_id": "UnityCsReference", "token_count": 17911 }
445
// 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; using System.Linq; using System.Collections.Generic; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; namespace Unity.UI.Builder { internal class BuilderStyleSheets : BuilderExplorer { static readonly string kToolbarPath = BuilderConstants.UIBuilderPackagePath + "/Explorer/BuilderStyleSheetsNewSelectorControls.uxml"; static readonly string kHelpTooltipPath = BuilderConstants.UIBuilderPackagePath + "/Explorer/BuilderStyleSheetsNewSelectorHelpTips.uxml"; private static readonly string kMessageLinkClassName = "unity-builder-message-link"; ToolbarMenu m_AddUSSMenu; BuilderNewSelectorField m_NewSelectorField; TextField m_NewSelectorTextField; VisualElement m_NewSelectorTextInputField; ToolbarMenu m_PseudoStatesMenu; BuilderTooltipPreview m_TooltipPreview; Label m_MessageLink; BuilderStyleSheetsDragger m_StyleSheetsDragger; Label m_EmptyStyleSheetsPaneLabel; enum FieldFocusStep { Idle, FocusedFromStandby, NeedsSelectionOverride } FieldFocusStep m_FieldFocusStep; bool m_ShouldRefocusSelectorFieldOnBlur; BuilderDocument document => m_PaneWindow?.document; public BuilderNewSelectorField newSelectorField => m_NewSelectorField; public BuilderStyleSheets( BuilderPaneWindow paneWindow, BuilderViewport viewport, BuilderSelection selection, BuilderClassDragger classDragger, BuilderStyleSheetsDragger styleSheetsDragger, HighlightOverlayPainter highlightOverlayPainter, BuilderTooltipPreview tooltipPreview) : base( paneWindow, viewport, selection, classDragger, styleSheetsDragger, new BuilderStyleSheetsContextMenu(paneWindow, selection), viewport.styleSelectorElementContainer, false, highlightOverlayPainter, kToolbarPath, "StyleSheets") { m_TooltipPreview = tooltipPreview; if (m_TooltipPreview != null) { var helpTooltipTemplate = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>(kHelpTooltipPath); var helpTooltipContainer = helpTooltipTemplate.CloneTree(); m_TooltipPreview.Add(helpTooltipContainer); // We are the only ones using it so just add the contents and be done. m_MessageLink = m_TooltipPreview.Q<Label>(null, kMessageLinkClassName); m_MessageLink.focusable = true; } viewDataKey = "builder-style-sheets"; AddToClassList(BuilderConstants.ExplorerStyleSheetsPaneClassName); var parent = this.Q("new-selector-item"); // Init text field. m_NewSelectorField = parent.Q<BuilderNewSelectorField>("new-selector-field"); m_NewSelectorTextField = m_NewSelectorField.textField; m_NewSelectorTextField.SetValueWithoutNotify(BuilderConstants.ExplorerInExplorerNewClassSelectorInfoMessage); m_NewSelectorTextInputField = m_NewSelectorTextField.Q("unity-text-input"); m_NewSelectorTextInputField.RegisterCallback<KeyDownEvent>(OnEnter, TrickleDown.TrickleDown); UpdateNewSelectorFieldEnabledStateFromDocument(); m_NewSelectorTextInputField.RegisterCallback<FocusEvent>((evt) => { var input = evt.elementTarget; var field = GetTextFieldParent(input); m_FieldFocusStep = FieldFocusStep.FocusedFromStandby; if (field.text == BuilderConstants.ExplorerInExplorerNewClassSelectorInfoMessage || m_ShouldRefocusSelectorFieldOnBlur) { m_ShouldRefocusSelectorFieldOnBlur = false; field.value = BuilderConstants.UssSelectorClassNameSymbol; field.textSelection.selectAllOnMouseUp = false; } ShowTooltip(); }, TrickleDown.TrickleDown); m_NewSelectorTextField.RegisterCallback<ChangeEvent<string>>((evt) => { if (m_FieldFocusStep != FieldFocusStep.FocusedFromStandby) return; m_FieldFocusStep = m_NewSelectorTextField.value == BuilderConstants.UssSelectorClassNameSymbol ? FieldFocusStep.NeedsSelectionOverride : FieldFocusStep.Idle; // We don't want the '.' we just inserted in the FocusEvent to be highlighted, // which is the default behavior. Same goes for when we add pseudo states with options menu. m_NewSelectorTextField.textSelection.SelectRange(m_NewSelectorTextField.value.Length, m_NewSelectorTextField.value.Length); }); // Since MouseDown captures the mouse, we need to RegisterCallback directly on the target in order to intercept the event. // This could be replaced by setting selectAllOnMouseUp to false. m_NewSelectorTextInputField.Q<TextElement>().RegisterCallback<MouseUpEvent>((evt) => { // We want to prevent the default action on mouse up in KeyboardTextEditor, but only when // the field selection behaviour was changed by us. if (m_FieldFocusStep != FieldFocusStep.NeedsSelectionOverride) return; m_FieldFocusStep = FieldFocusStep.Idle; // Reselect on the next execution, after the KeyboardTextEditor selects all. m_NewSelectorTextInputField.schedule.Execute(() => { m_NewSelectorTextField.textSelection.SelectRange(m_NewSelectorTextField.value.Length, m_NewSelectorTextField.value.Length); }); }, TrickleDown.TrickleDown); m_NewSelectorTextInputField.RegisterCallback<BlurEvent>((evt) => { var input = evt.elementTarget; var field = GetTextFieldParent(input); // Delay tooltip to allow users to click on link in preview if needed schedule.Execute(() => { field.textSelection.selectAllOnMouseUp = true; if (m_NewSelectorTextInputField.focusController.focusedElement == m_MessageLink) return; HideTooltip(); if (m_ShouldRefocusSelectorFieldOnBlur) { PostEnterRefocus(); } else if (string.IsNullOrEmpty(field.text) || field.text == BuilderConstants.UssSelectorClassNameSymbol) { field.SetValueWithoutNotify(BuilderConstants.ExplorerInExplorerNewClassSelectorInfoMessage); m_PseudoStatesMenu.SetEnabled(false); } }); }, TrickleDown.TrickleDown); m_MessageLink?.RegisterCallback<BlurEvent>(evt => { HideTooltip(); if (m_ShouldRefocusSelectorFieldOnBlur) { m_NewSelectorTextInputField.schedule.Execute(PostEnterRefocus); } }); m_MessageLink?.RegisterCallback<ClickEvent>(evt => { HideTooltip(); if (m_ShouldRefocusSelectorFieldOnBlur) { m_NewSelectorTextInputField.schedule.Execute(PostEnterRefocus); } }); // Setup New USS Menu. m_AddUSSMenu = parent.Q<ToolbarMenu>("add-uss-menu"); SetUpAddUSSMenu(); // Setup pseudo states menu. m_PseudoStatesMenu = m_NewSelectorField.pseudoStatesMenu; // Update sub title. UpdateSubtitleFromActiveUSS(); // Init drag stylesheet root classDragger.builderStylesheetRoot = container; styleSheetsDragger.builderStylesheetRoot = container; m_StyleSheetsDragger = styleSheetsDragger; RegisterCallback<GeometryChangedEvent>(e => AdjustPosition()); // Create the empty state label here because this file shares a UXML with BuilderHierarchy m_EmptyStyleSheetsPaneLabel = new Label("Click the + icon to create a new StyleSheet."); m_EmptyStyleSheetsPaneLabel.AddToClassList(BuilderConstants.ExplorerDayZeroStateLabelClassName); m_EmptyStyleSheetsPaneLabel.style.display = DisplayStyle.None; } protected override void InitEllipsisMenu() { base.InitEllipsisMenu(); if (pane == null) { return; } pane.AppendActionToEllipsisMenu(L10n.Tr("Full selector text"), a => ChangeVisibilityState(BuilderElementInfoVisibilityState.FullSelectorText), a => m_ElementHierarchyView.elementInfoVisibilityState .HasFlag(BuilderElementInfoVisibilityState.FullSelectorText) ? DropdownMenuAction.Status.Checked : DropdownMenuAction.Status.Normal); } TextField GetTextFieldParent(VisualElement ve) { return ve.GetFirstAncestorOfType<TextField>(); } protected override bool IsSelectedItemValid(VisualElement element) { var isCS = element.GetStyleComplexSelector() != null; var isSS = element.GetStyleSheet() != null; return isCS || isSS; } void PostEnterRefocus() { m_NewSelectorTextInputField.Focus(); } void OnEnter(KeyDownEvent evt) { if (evt.keyCode != KeyCode.Return && evt.keyCode != KeyCode.KeypadEnter) return; CreateNewSelector(document.activeStyleSheet); evt.StopImmediatePropagation(); } void CreateNewSelector(StyleSheet styleSheet) { var newValue = m_NewSelectorTextField.text; if (newValue == BuilderConstants.ExplorerInExplorerNewClassSelectorInfoMessage) return; if (styleSheet == null) { if (BuilderStyleSheetsUtilities.CreateNewUSSAsset(m_PaneWindow)) { styleSheet = m_PaneWindow.document.firstStyleSheet; // The EditorWindow will no longer have Focus after we show the // Save Dialog so even though the New Selector field will appear // focused, typing won't do anything. As such, it's better, in // this one case to remove focus from this field so users know // to re-focus it themselves before they can add more selectors. m_NewSelectorTextField.value = string.Empty; m_NewSelectorTextField.Blur(); } else { return; } } else { m_ShouldRefocusSelectorFieldOnBlur = true; } var newSelectorStr = newValue.Trim(); var selectorTypeSymbol = (newSelectorStr[0]) switch { '.' => BuilderConstants.UssSelectorClassNameSymbol, '#' => BuilderConstants.UssSelectorNameSymbol, ':' => BuilderConstants.UssSelectorPseudoStateSymbol, _ => "" }; if (!string.IsNullOrEmpty(selectorTypeSymbol)) { newSelectorStr = selectorTypeSymbol + newSelectorStr.Trim(selectorTypeSymbol[0]).Trim(); } if (string.IsNullOrEmpty(newSelectorStr)) return; if (newSelectorStr.Length == 1 && ( newSelectorStr.StartsWith(BuilderConstants.UssSelectorClassNameSymbol) || newSelectorStr.StartsWith("-") || newSelectorStr.StartsWith("_"))) return; if (!BuilderNameUtilities.styleSelectorRegex.IsMatch(newSelectorStr)) { Builder.ShowWarning(BuilderConstants.StyleSelectorValidationSpacialCharacters); m_NewSelectorTextField.schedule.Execute(() => { m_NewSelectorTextField.SetValueWithoutNotify(newValue); m_NewSelectorTextField.textSelection.SelectAll(); }); return; } var selectorContainerElement = m_Viewport.styleSelectorElementContainer; var newComplexSelector = BuilderSharedStyles.CreateNewSelector(selectorContainerElement, styleSheet, newSelectorStr); m_Selection.NotifyOfHierarchyChange(); m_Selection.NotifyOfStylingChange(); // Try to selected newly created selector. var newSelectorElement = m_Viewport.styleSelectorElementContainer.FindElement( (e) => e.GetStyleComplexSelector() == newComplexSelector); if (newSelectorElement != null) m_Selection.Select(null, newSelectorElement); schedule.Execute(() => { m_NewSelectorTextField.Blur(); m_NewSelectorTextField.SetValueWithoutNotify(BuilderConstants.ExplorerInExplorerNewClassSelectorInfoMessage); }); } void SetUpAddUSSMenu() { if (m_AddUSSMenu == null) return; m_AddUSSMenu.menu.MenuItems().Clear(); { m_AddUSSMenu.menu.AppendAction( BuilderConstants.ExplorerStyleSheetsPaneCreateNewUSSMenu, action => { BuilderStyleSheetsUtilities.CreateNewUSSAsset(m_PaneWindow); }); m_AddUSSMenu.menu.AppendAction( BuilderConstants.ExplorerStyleSheetsPaneAddExistingUSSMenu, action => { BuilderStyleSheetsUtilities.AddExistingUSSToAsset(m_PaneWindow); }); } } void ShowTooltip() { if (m_TooltipPreview == null) return; if (m_TooltipPreview.isShowing) return; m_TooltipPreview.Show(); AdjustPosition(); } void AdjustPosition() { m_TooltipPreview.style.left = Mathf.Max(0, this.pane.resolvedStyle.width + BuilderConstants.TooltipPreviewYOffset); m_TooltipPreview.style.top = m_Viewport.viewportWrapper.worldBound.y; } void HideTooltip() { if (m_TooltipPreview == null) return; m_TooltipPreview.Hide(); } void UpdateNewSelectorFieldEnabledStateFromDocument() { m_NewSelectorTextField.SetEnabled(true); SetUpAddUSSMenu(); } void UpdateSubtitleFromActiveUSS() { if (pane == null) return; if (document == null || document.activeStyleSheet == null) { pane.subTitle = string.Empty; return; } pane.subTitle = document.activeStyleSheet.name + BuilderConstants.UssExtension; } protected override void ElementSelectionChanged(List<VisualElement> elements) { base.ElementSelectionChanged(elements); UpdateSubtitleFromActiveUSS(); } public override void HierarchyChanged(VisualElement element, BuilderHierarchyChangeType changeType) { base.HierarchyChanged(element, changeType); m_ElementHierarchyView.hasUssChanges = true; UpdateNewSelectorFieldEnabledStateFromDocument(); UpdateSubtitleFromActiveUSS(); // Show empty state if no stylesheet loaded if (document.activeStyleSheet == null) { m_ElementHierarchyView.container.style.justifyContent = Justify.Center; m_ElementHierarchyView.treeView.style.flexGrow = document.activeOpenUXMLFile.isChildSubDocument ? 1 : 0; m_EmptyStyleSheetsPaneLabel.style.display = DisplayStyle.Flex; m_ElementHierarchyView.container.Add(m_EmptyStyleSheetsPaneLabel); m_EmptyStyleSheetsPaneLabel.SendToBack(); } else { if (m_EmptyStyleSheetsPaneLabel.parent != m_ElementHierarchyView.container) return; // Revert inline style changes to default m_ElementHierarchyView.container.style.justifyContent = Justify.FlexStart; elementHierarchyView.treeView.style.flexGrow = 1; m_EmptyStyleSheetsPaneLabel.style.display = DisplayStyle.None; m_EmptyStyleSheetsPaneLabel.RemoveFromHierarchy(); } } // Used by unit tests to reset state after stylesheets drag internal void ResetStyleSheetsDragger() { m_StyleSheetsDragger.Reset(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheets.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Explorer/BuilderStyleSheets.cs", "repo_id": "UnityCsReference", "token_count": 8410 }
446
// 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; using UnityEngine.UIElements; namespace Unity.UI.Builder { class BuilderPropertyPathInfoViewItem : VisualElement { private const string k_UssClassName = "unity-builder-property-path-info-item"; private Label m_NameLabel; private Label m_TypeLabel; public string propertyName { get => m_NameLabel.text; set => m_NameLabel.text = value; } public Type propertyType { set { m_TypeLabel.text = TypeUtility.GetTypeDisplayName(value); m_TypeLabel.tooltip = value.GetDisplayFullName(); } } public BuilderPropertyPathInfoViewItem() { AddToClassList(k_UssClassName); var template = BuilderPackageUtilities.LoadAssetAtPath<VisualTreeAsset>( BuilderConstants.UIBuilderPackagePath + "/Inspector/PropertyPathInfoViewItem.uxml"); template.CloneTree(this); m_NameLabel = this.Q<Label>("nameLabel"); m_TypeLabel = this.Q<Label>("typeLabel"); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BuilderPropertyPathInfoViewItem.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/Binding/BuilderPropertyPathInfoViewItem.cs", "repo_id": "UnityCsReference", "token_count": 573 }
447
// 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 System.Collections.Generic; using UnityEditor; using UnityEditor.UIElements; using UnityEngine; namespace Unity.UI.Builder { internal interface IBuilderInspectorSection { VisualElement root { get; } void Refresh(); void Enable(); void Disable(); } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/IBuilderInspectorSection.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Inspector/IBuilderInspectorSection.cs", "repo_id": "UnityCsReference", "token_count": 165 }
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.Collections.Generic; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { class BuilderTracker : VisualElement, IBuilderSelectionNotifier { [Serializable] public new class UxmlSerializedData : VisualElement.UxmlSerializedData { public override object CreateInstance() => new BuilderTracker(); } static readonly string s_UssClassName = "unity-builder-tracker"; protected static readonly string s_ActiveClassName = "unity-builder-tracker--active"; protected VisualElement m_Target; BuilderCanvas m_Canvas; public BuilderCanvas canvas => m_Canvas; public BuilderTracker() { m_Target = null; AddToClassList(s_UssClassName); } public virtual void Activate(VisualElement target) { if (m_Target == target) return; if (m_Target != null) Deactivate(); if (target == null) return; m_Target = target; AddToClassList(s_ActiveClassName); m_Target.RegisterCallback<GeometryChangedEvent>(OnExternalTargetResize); m_Target.RegisterCallback<DetachFromPanelEvent>(OnTargetDeletion); m_Canvas = m_Target.GetFirstAncestorOfType<BuilderCanvas>(); m_Canvas?.RegisterCallback<GeometryChangedEvent>(OnCanvasResize); if (float.IsNaN(m_Target.layout.width)) { m_Target.RegisterCallback<GeometryChangedEvent>(OnInitialStylesResolved); } else { SetStylesFromTargetStyles(); ResizeSelfFromTarget(); } } public virtual void Deactivate() { if (m_Target == null) return; m_Target.UnregisterCallback<GeometryChangedEvent>(OnExternalTargetResize); m_Target.UnregisterCallback<DetachFromPanelEvent>(OnTargetDeletion); m_Canvas?.UnregisterCallback<GeometryChangedEvent>(OnCanvasResize); m_Target = null; m_Canvas = null; RemoveFromClassList(s_ActiveClassName); } void OnInitialStylesResolved(GeometryChangedEvent evt) { SetStylesFromTargetStyles(); if (m_Target != null) m_Target.UnregisterCallback<GeometryChangedEvent>(OnInitialStylesResolved); } protected virtual void SetStylesFromTargetStyles() {} void OnExternalTargetResize(GeometryChangedEvent evt) { ResizeSelfFromTarget(); } void OnCanvasResize(GeometryChangedEvent evt) { if (m_Target == null) return; ResizeSelfFromTarget(); } void OnTargetDeletion(DetachFromPanelEvent evt) { Deactivate(); } public static Rect GetRelativeRectFromTargetElement(VisualElement target, VisualElement relativeTo) { var targetMarginTop = target.resolvedStyle.marginTop; var targetMarginLeft = target.resolvedStyle.marginLeft; var targetMarginRight = target.resolvedStyle.marginRight; var targetMarginBottom = target.resolvedStyle.marginBottom; Rect targetRect = target.rect; targetRect.y -= targetMarginTop; targetRect.x -= targetMarginLeft; targetRect.width = targetRect.width + (targetMarginLeft + targetMarginRight); targetRect.height = targetRect.height + (targetMarginTop + targetMarginBottom); var relativeRect = target.ChangeCoordinatesTo(relativeTo, targetRect); return relativeRect; } void ResizeSelfFromTarget() { var selfRect = GetRelativeRectFromTargetElement(m_Target, this.hierarchy.parent); var top = selfRect.y; var left = selfRect.x; var width = selfRect.width; var height = selfRect.height; style.top = top - resolvedStyle.borderTopWidth; style.left = left - resolvedStyle.borderLeftWidth; style.width = width + resolvedStyle.borderLeftWidth + resolvedStyle.borderRightWidth; style.height = height + resolvedStyle.borderTopWidth + resolvedStyle.borderBottomWidth; } public void SelectionChanged() { } public void HierarchyChanged(VisualElement element, BuilderHierarchyChangeType changeType) { if (m_Target == null) return; if (!changeType.HasFlag(BuilderHierarchyChangeType.InlineStyle)) return; SetStylesFromTargetStyles(); ResizeSelfFromTarget(); } public virtual void StylingChanged(List<string> styles, BuilderStylingChangeType changeType) { if (m_Target == null) return; SetStylesFromTargetStyles(); ResizeSelfFromTarget(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderTracker.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Manipulators/BuilderTracker.cs", "repo_id": "UnityCsReference", "token_count": 2356 }
449
// 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; namespace Unity.UI.Builder { internal static class BuilderDialogsUtility { public static bool preventDialogsFromOpening { get; set; } private static bool cannotOpenDialogs => Application.isBatchMode || preventDialogsFromOpening; public static bool DisplayDialog(string title, string message) { return DisplayDialog(title, message, BuilderConstants.DialogOkOption); } public static bool DisplayDialog(string title, string message, string ok) { return DisplayDialog(title, message, ok, string.Empty); } public static bool DisplayDialog(string title, string message, string ok, string cancel) { if (cannotOpenDialogs) return true; return EditorUtility.DisplayDialog(title, message, ok, cancel); } public static int DisplayDialogComplex(string title, string message, string ok, string cancel, string alt) { if (cannotOpenDialogs) return 0; return EditorUtility.DisplayDialogComplex(title, message, ok, cancel, alt); } public static string DisplayOpenFileDialog(string title, string directory, string extension) { if (cannotOpenDialogs) return null; if (string.IsNullOrEmpty(directory)) directory = BuilderAssetUtilities.assetsPath; var newPath = EditorUtility.OpenFilePanel( title, directory, extension); if (string.IsNullOrWhiteSpace(newPath)) return null; var projectPath = BuilderAssetUtilities.GetPathRelativeToProject(newPath.Trim()); if (string.IsNullOrWhiteSpace(projectPath)) DisplayDialog("Opening document failed", $"Could not open the document at the requested path ('{newPath}'): the path is outside of the project."); return projectPath; } public static string DisplaySaveFileDialog(string title, string directory, string defaultName, string extension) { if (cannotOpenDialogs) return null; if (string.IsNullOrEmpty(directory)) directory = BuilderAssetUtilities.assetsPath; var newPath = EditorUtility.SaveFilePanel( title, directory, defaultName, extension); if (string.IsNullOrWhiteSpace(newPath)) return null; var projectPath = BuilderAssetUtilities.GetPathRelativeToProject(newPath.Trim()); if (string.IsNullOrWhiteSpace(projectPath)) DisplayDialog("Saving new document failed", $"Could not save the current document at the requested path ('{newPath}'): the path is outside of the project."); return projectPath; } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderDialogsUtility.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/Utilities/BuilderDialogsUtility.cs", "repo_id": "UnityCsReference", "token_count": 1304 }
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; using UnityEditor; using UnityEngine.UIElements; using Object = UnityEngine.Object; namespace Unity.UI.Builder { internal class BuilderUxmlImageAttributeFieldFactory : BuilderTypedUxmlAttributeFieldFactoryBase<Object, BaseField<Object>> { public override bool CanCreateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { return attribute.GetType() == typeof(UxmlImageAttributeDescription); } protected override BaseField<Object> InstantiateField(object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { return new ImageStyleField(); } public override void SetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, object value) { (field as ImageStyleField).SetValueWithoutNotify((value as Background?).Value.GetSelectedImage() ?? value as Object); } public override void ResetFieldValue(VisualElement field, object attributeOwner, VisualTreeAsset uxmlDocument, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute) { (field as ImageStyleField).SetValueWithoutNotify(null); } protected override void NotifyValueChanged(ChangeEvent<Object> evt, BaseField<Object> field, object attributeOwner, UxmlAsset attributeUxmlOwner, UxmlAttributeDescription attribute, string uxmlValue, Action<VisualElement, UxmlAttributeDescription, object, string> onValueChange) { var assetPath = AssetDatabase.GetAssetPath(evt.newValue); if (BuilderAssetUtilities.IsBuiltinPath(assetPath)) { Builder.ShowWarning(BuilderConstants.BuiltInAssetPathsNotSupportedMessageUxml); // Revert the change. field.SetValueWithoutNotify(evt.previousValue); return; } base.NotifyValueChanged(evt, field, attributeOwner, attributeUxmlOwner, attribute, uxmlValue, onValueChange); } } }
UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlImageAttributeField.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Builder/UxmlAttributesView/Fields/BuilderUxmlImageAttributeField.cs", "repo_id": "UnityCsReference", "token_count": 867 }
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.Collections.Generic; namespace Unity.UI.Builder { struct CategoryDropdownContent { public enum ItemType { Category, Separator, Item } public struct Category { public string name; } public struct ValueItem { public string value; public string displayName; public string categoryName; } internal struct Item { public string value; public string displayName; public string categoryName; public ItemType itemType; } List<Item> m_Items; internal List<Item> Items { get { return m_Items ??= new List<Item>(); } } public void AppendCategory(Category category) { Items.Add(new Item { itemType = ItemType.Category, displayName = category.name, categoryName = category.name }); } public void AppendValue(ValueItem value) { Items.Add(new Item { itemType = ItemType.Item, displayName = value.displayName, categoryName = value.categoryName, value = value.value }); } public void AppendSeparator() { Items.Add(new Item { itemType = ItemType.Separator }); } public void AppendContent(CategoryDropdownContent content) { foreach (var item in content.Items) { Items.Add(new Item { value = item.value, categoryName = item.categoryName, itemType = item.itemType, displayName = item.displayName }); } } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/CategoryDropdownField/CategoryDropdownContent.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/CategoryDropdownField/CategoryDropdownContent.cs", "repo_id": "UnityCsReference", "token_count": 1131 }
452
// 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 UnityEditor; using Object = System.Object; namespace Unity.UI.Builder { internal interface IFieldSearchCompleter { public FieldSearchCompleterPopup popup { get; } /// <summary> /// Refreshes the result. /// </summary> public void Refresh(); } class FieldSearchCompleter<TData> : IFieldSearchCompleter { const int k_ItemHeight = 20; const int k_PauseDelay = 250; static readonly List<TData> s_EmptyMatchingDataList = new List<TData>(); // Properties bool m_Enabled = true; IEnumerable<TData> m_DataSource; List<TData> m_Results; // Internal state bool m_DataSourceDirty; IVisualElementScheduledItem m_ScheduledFilterUpdate; // Callbacks Func<IEnumerable<TData>> m_DataSourceCallback; Func<string, TData, bool> m_MatcherCallback; Func<string, string> m_GetFilterFromTextCallback; Func<TData, string> m_GetTextFromDataCallback; private Func<int, string> m_GetResultCountTextCallback; // List view properties int m_ItemHeight; Func<VisualElement> m_MakeItem; Action<VisualElement> m_DestroyItem; Action<VisualElement, int> m_BindItem; // UI parts FieldSearchCompleterPopup m_Popup; VisualElement m_DetailsContent; VisualElement m_Footer; TextField m_TextField; private Rect m_PreviousTextFieldWorldPosition; private bool m_TemporarilyDontShowPopup; private bool m_IsEvaluatingFocus; private bool m_HasPendingValueChanged; private string m_PendingPreviousValue; /// <summary> /// Indicates whether the popup is a native popup window rather than a overlay VisualElement. /// The default value is false. /// </summary> public bool usesNativePopupWindow { get; private set; } public bool enabled { get => m_Enabled; set { if (m_Enabled == value) return; m_Enabled = value; if (!m_Enabled) { results = s_EmptyMatchingDataList; DisconnectFromField(); m_Popup?.Hide(); } else { ConnectToField(); } } } public bool alwaysVisible { get; set; } public List<TData> results { get => m_Results; private set { // Refresh every time set is called even when it has not changed m_Results = value; if (m_Popup != null) { popup.listView.itemsSource = m_Results; popup.resultLabel.text = GetResultCountText(m_Results?.Count ?? 0); popup.Refresh(); } } } public IEnumerable<TData> dataSource { get { if (m_DataSourceDirty) { if (m_DataSourceCallback != null) { m_DataSource = m_DataSourceCallback(); } else { m_DataSource = null; } m_DataSourceDirty = false; } return m_DataSource; } } public Func<IEnumerable<TData>> dataSourceCallback { get => m_DataSourceCallback; set => m_DataSourceCallback = value; } public Func<string, TData, bool> matcherCallback { get { if (m_MatcherCallback == null) { m_MatcherCallback = DefaultMatcher; } return m_MatcherCallback; } set => m_MatcherCallback = value; } public TData selectedData { get { if (m_Popup != null) { var index = m_Popup.listView.selectedIndex; return index != -1 ? results[index] : default(TData); } return default(TData); } } public event Action<TData> hoveredItemChanged; public event Action<TData> selectionChanged; public Action<int> itemChosen; public int itemHeight { get => m_ItemHeight; set { m_ItemHeight = value; if (m_Popup != null) m_Popup.listView.fixedItemHeight = m_ItemHeight; } } public Func<VisualElement> makeItem { get => m_MakeItem; set { m_MakeItem = value; if (m_Popup != null) m_Popup.listView.makeItem = m_MakeItem; } } public Action<VisualElement> destroyItem { get => m_DestroyItem; set { m_DestroyItem = value; if (m_Popup != null) m_Popup.listView.destroyItem = m_DestroyItem; } } public Action<VisualElement, int> bindItem { get => m_BindItem; set { m_BindItem = value; if (m_Popup != null) m_Popup.listView.bindItem = m_BindItem; } } public Func<string, string> getFilterFromTextCallback { get => m_GetFilterFromTextCallback; set => m_GetFilterFromTextCallback = value; } public Func<int, string> getResultCountTextCallback { get => m_GetResultCountTextCallback; set => m_GetResultCountTextCallback = value; } public Func<TData, string> getTextFromDataCallback { get => m_GetTextFromDataCallback; set => m_GetTextFromDataCallback = value; } public FieldSearchCompleterPopup popup => m_Popup; public TextField textField { get => m_TextField; } public void SetupCompleterField(TextField field, bool useNativeWindow) { usesNativePopupWindow = useNativeWindow; if (m_TextField == field) return; DisconnectFromField(); m_TextField = field; ConnectToField(); if (m_Popup != null) m_Popup.anchoredControl = m_TextField.visualInput; } internal void EnsurePopupIsCreated() { if (m_Popup == null) { VisualElement rootElement; var inspector = m_TextField.GetFirstAncestorOfType<BuilderInspector>(); if (inspector != null) { var builder = inspector.paneWindow as Builder; rootElement = builder.rootVisualElement; } else { rootElement = m_TextField.GetRootVisualContainer(); } if (rootElement != null) { m_Popup = CreatePopup(); m_Popup.usesNativeWindow = usesNativePopupWindow; if (m_Footer == null) { CreateFooterContent(); } if (m_Footer != null) { m_Popup.Add(m_Footer); } if (m_DetailsContent == null) { CreateDetailsContent(); } if (m_DetailsContent != null) { m_Popup.Add(m_DetailsContent); } if (!usesNativePopupWindow) { rootElement.Add(m_Popup); } m_Popup.elementChosen += (index) => { CancelEvaluateFocus(); textField.value = GetTextFromData(results[index]); m_TemporarilyDontShowPopup = true; textField.schedule.Execute((e) => { textField.Blur(); m_TemporarilyDontShowPopup = false; }).ExecuteLater(k_PauseDelay); if (usesNativePopupWindow) { m_Popup?.Hide(); } itemChosen?.Invoke(index); }; m_Popup.hoveredItemChanged += (index) => hoveredItemChanged?.Invoke(index != -1 ? results[index] : default(TData)); m_Popup.selectionChanged += (index) => selectionChanged?.Invoke(index != -1 ? results[index] : default(TData)); m_Popup.onHide += OnPopupWindowClose; UpdatePopup(); } } } protected virtual VisualElement MakeDetailsContent() => null; void CreateDetailsContent() { m_DetailsContent?.RemoveFromClassList(FieldSearchCompleterPopup.s_DetailsViewUssClassName); m_DetailsContent = MakeDetailsContent(); m_DetailsContent?.AddToClassList(FieldSearchCompleterPopup.s_DetailsViewUssClassName); } protected virtual VisualElement MakeFooterContent() { return null; } void CreateFooterContent() { m_Footer?.RemoveFromClassList(FieldSearchCompleterPopup.s_DetailsViewUssClassName); m_Footer = MakeFooterContent(); m_Footer?.AddToClassList(FieldSearchCompleterPopup.s_DetailsViewUssClassName); } void ConnectToField() { if (m_TextField != null && enabled) { m_TextField.RegisterCallback<FocusInEvent>(OnFocusIn, TrickleDown.TrickleDown); m_TextField.RegisterCallback<FocusOutEvent>(OnFocusOut, TrickleDown.TrickleDown); m_TextField.RegisterValueChangedCallback(OnTextValueChange); m_TextField.Q(TextField.textInputUssName) .RegisterCallback<KeyDownEvent>(OnKeyDown, TrickleDown.TrickleDown); m_TextField.RegisterCallback<DetachFromPanelEvent>(OnTextFieldDetached); m_TextField.RegisterCallback<FocusOutEvent>(OnTextFieldFocusOut); m_TextField.RegisterCallback<FocusInEvent>(OnTextFieldFocusInPrepareTracking); m_TextField.RegisterCallback<GeometryChangedEvent>(OnTextFieldGeometryChangedEvent); m_PreviousTextFieldWorldPosition = GUIUtility.GUIToScreenRect(textField.visualInput.worldBound); } } void OnTextFieldFocusInPrepareTracking(FocusInEvent _) { PrepareWindowTracking(); } void PrepareWindowTracking() { if (!usesNativePopupWindow) return; var window = GetEditorWindow(); if (window == null) return; UpdateAnchoredControlScreenPosition(); if (window is IBuilderWindowResizeTracker windowWithTracker) { windowWithTracker.onRectChanged += HandlePopupWindowPositionChanged; } } void HandlePopupWindowPositionChanged(object obj, EventArgs args) { HandlePopupWindowPositionChanged(); } // If the window which hosts the textfield is moved/resized, popup must be forcefully hidden. void HandlePopupWindowPositionChanged() { if (m_TextField?.elementPanel?.ownerObject == null) { return; } // Use the element panel to find which window "owns" field var window = GetEditorWindow(); if (window == null || window.rootVisualElement == null) return; UpdateAnchoredControlScreenPosition(); // If the window is moved, we need to hide the popup var textFieldPositionPostUpdate = (Rect) m_TextField.visualInput .GetProperty(BuilderConstants.CompleterAnchoredControlScreenRectVEPropertyName); if (m_PreviousTextFieldWorldPosition.Equals(textFieldPositionPostUpdate)) return; if (window.baseRootVisualElement.focusController.focusedElement == m_TextField) { m_TextField.Blur(); } if (window.baseRootVisualElement.focusController.m_LastPendingFocusedElement == m_TextField) { window.baseRootVisualElement.focusController.BlurLastFocusedElement(); } m_PreviousTextFieldWorldPosition = textFieldPositionPostUpdate; m_Popup?.Hide(); } void DisconnectFromField() { if (m_TextField != null) { m_TextField.UnregisterCallback<DetachFromPanelEvent>(OnTextFieldDetached); m_TextField.UnregisterCallback<FocusInEvent>(OnTextFieldFocusInPrepareTracking); m_TextField.UnregisterCallback<FocusOutEvent>(OnTextFieldFocusOut); m_TextField.UnregisterCallback<GeometryChangedEvent>(OnTextFieldGeometryChangedEvent); m_TextField.UnregisterValueChangedCallback(OnTextValueChange); m_TextField.UnregisterCallback<FocusInEvent>(OnFocusIn, TrickleDown.TrickleDown); m_TextField.UnregisterCallback<FocusOutEvent>(OnFocusOut, TrickleDown.TrickleDown); m_TextField.Q(TextField.textInputUssName) .UnregisterCallback<KeyDownEvent>(OnKeyDown, TrickleDown.TrickleDown); } } void OnTextFieldDetached(DetachFromPanelEvent evt) { if (m_Popup != null && m_Popup.isOpened) { m_Popup.Hide(); } } void OnTextFieldFocusOut(FocusOutEvent evt) { var window = GetEditorWindow(); if (window != null && window is IBuilderWindowResizeTracker windowWithTracker) { windowWithTracker.onRectChanged -= HandlePopupWindowPositionChanged; if (evt.relatedTarget != null && ((VisualElement) evt.relatedTarget).GetFirstAncestorWhere((element => element == m_Popup?.GetRoot())) == null) { m_Popup?.Hide(); } } } void OnTextFieldGeometryChangedEvent(GeometryChangedEvent evt) { if (m_Popup != null && m_Popup.isOpened) { m_Popup.Hide(); } } public FieldSearchCompleter() : this(null) { } public FieldSearchCompleter(TextField field) { itemHeight = k_ItemHeight; makeItem = () => { var item = new Label(); return item; }; bindItem = (e, i) => { if (e is Label label) label.text = GetTextFromData(results[i]); }; } void UpdatePopup() { if (m_Popup != null) { m_Popup.listView.fixedItemHeight = m_ItemHeight; m_Popup.listView.makeItem = m_MakeItem; m_Popup.listView.destroyItem = m_DestroyItem; m_Popup.listView.bindItem = m_BindItem; m_Popup.anchoredControl = textField.visualInput; } } // This has to be called during an event to ensure that GUIUtility.GUIToScreenRect() uses the window containing the attached text field. void UpdateAnchoredControlScreenPosition() { var field = textField.visualInput; if (field != null) { field.SetProperty(BuilderConstants.CompleterAnchoredControlScreenRectVEPropertyName, GUIUtility.GUIToScreenRect(field.worldBound)); } } protected virtual FieldSearchCompleterPopup CreatePopup() => new FieldSearchCompleterPopup(); static bool DefaultMatcher(string filter, TData data) { var text = data.ToString(); return !string.IsNullOrEmpty(text) && text.Contains(filter); } void OnTextChanged() { UpdateFilter(m_TextField.text); } void ScheduleTextChange() { if (m_ScheduledFilterUpdate == null) { m_ScheduledFilterUpdate = m_TextField?.schedule.Execute(a => UpdateFilter(m_TextField.text)); } else { m_ScheduledFilterUpdate.ExecuteLater(0); } } protected virtual bool IsValidText(string text) { return true; } /// <summary> /// Refreshes the result. /// </summary> public void Refresh() { m_DataSourceDirty = true; if (m_Popup != null) { OnTextChanged(); } } void UpdateFilter(string text) { if (!IsValidText(text)) { results = s_EmptyMatchingDataList; popup?.Hide(); return; } SetFilter(GetFilterFromText(text)); } private string GetFilterFromText(string text) { return m_GetFilterFromTextCallback != null ? m_GetFilterFromTextCallback(text) : text; } protected virtual string GetTextFromData(TData data) { return m_GetTextFromDataCallback != null ? m_GetTextFromDataCallback(data) : data.ToString(); } protected virtual string GetResultCountText(int count) { return m_GetResultCountTextCallback?.Invoke(count) ?? $"{count} found"; } protected virtual bool MatchFilter(string filter, in TData data) { return string.IsNullOrEmpty(filter) || (matcherCallback?.Invoke(filter, data) ?? false); } private void SetFilter(string filter) { if (dataSource == null || matcherCallback == null) return; var matchingDataList = new List<TData>(); foreach (var data in dataSource) { if (MatchFilter(filter, in data)) matchingDataList.Add(data); } results = matchingDataList; if (!popup.isOpened && !m_TemporarilyDontShowPopup) { popup.Show(); popup.listView.RefreshItems(); int selectedIndex = -1; int i = 0; // Select the element with the exact match foreach (var data in matchingDataList) { if (!string.IsNullOrEmpty(filter) && filter == GetFilterFromText(GetTextFromData(data))) { selectedIndex = i; break; } i++; } if (selectedIndex != -1) { popup.listView.selectedIndex = selectedIndex; popup.listView.ScrollToItem(selectedIndex); } } else { popup.AdjustGeometry(); } } void OnFocusIn(FocusInEvent e) { if (m_TemporarilyDontShowPopup) return; m_DataSourceDirty = true; EnsurePopupIsCreated(); if (alwaysVisible) { if (textField.isReadOnly) return; UpdateAnchoredControlScreenPosition(); OnTextChanged(); } } void OnFocusOut(FocusOutEvent e) { m_ScheduledFilterUpdate?.Pause(); if (usesNativePopupWindow) { ScheduleEvaluateFocus(); } else { m_Popup?.Hide(); } } void OnPopupWindowClose() { ScheduleEvaluateFocus(); } void OnTextValueChange(ChangeEvent<string> e) { // Do not submit the value change until we evaluate the current focus. See EvaluateFocus. if (m_IsEvaluatingFocus) { PendValueChange(e); } else { ClearPendingValueChange(); } } /* * Schedule the check of the current focus on the next frame */ void ScheduleEvaluateFocus() { if (m_IsEvaluatingFocus) return; m_IsEvaluatingFocus = true; m_TextField.schedule.Execute(EvaluateFocus); } void CancelEvaluateFocus() { ClearPendingValueChange(); m_IsEvaluatingFocus = false; } /* * When the target text field loses focus, we do not submit (by blocking ChangeEvent notification) the new value right away because we want to ensure that * the text field did not lose focus because the user click on the completer popup window (e.g user scrolls the results using the scrollbar). * If this is what happened then we will submit the pending change only when the popup window will also lose focus unless the focus is given back to the text field or if the user choses a result. */ void EvaluateFocus() { if (!m_IsEvaluatingFocus) return; m_IsEvaluatingFocus = false; if (m_TextField.hasFocus || (m_Popup?.nativeWindow != null && m_Popup?.nativeWindow == EditorWindow.focusedWindow)) return; SubmitPendingValueChange(); } void PendValueChange(ChangeEvent<string> e) { m_HasPendingValueChanged = true; m_PendingPreviousValue = e.previousValue; e.StopImmediatePropagation(); } void ClearPendingValueChange() { m_HasPendingValueChanged = false; m_PendingPreviousValue = null; } void SubmitPendingValueChange() { if (!m_HasPendingValueChanged) return; try { using var evt = ChangeEvent<string>.GetPooled(m_PendingPreviousValue, m_TextField.value); evt.elementTarget = m_TextField; m_TextField.SendEvent(evt); } finally { ClearPendingValueChange(); } } bool IsNavigationEvent(KeyDownEvent evt) { switch (evt.keyCode) { case KeyCode.Tab: case KeyCode.LeftArrow: case KeyCode.RightArrow: case KeyCode.UpArrow: case KeyCode.DownArrow: case KeyCode.PageUp: case KeyCode.PageDown: case KeyCode.Home: case KeyCode.End: return true; default: return false; } } void OnKeyDown(KeyDownEvent e) { if (textField.isReadOnly) return; EnsurePopupIsCreated(); UpdateAnchoredControlScreenPosition(); // If the users presses DownArrow key but the popup is not visible then search using the current text if (e.keyCode == KeyCode.KeypadEnter || e.keyCode == KeyCode.Return || e.character == 3 || e.character == '\n') { var selectedIndex = popup.listView.selectedIndex; if (selectedIndex != -1) { m_TextField.value = GetTextFromData(m_Results[selectedIndex]); textField.Blur(); m_TemporarilyDontShowPopup = true; textField.schedule.Execute((e) => m_TemporarilyDontShowPopup = false).ExecuteLater(k_PauseDelay); if (usesNativePopupWindow) { m_Popup?.Hide(); } itemChosen?.Invoke(selectedIndex); } } if (e.keyCode == KeyCode.DownArrow && m_Popup is not {isOpened: true}) { OnTextChanged(); } // Forward the navigation key event to the list view as it does not have focus else if (m_Results != null && m_Results.Count > 0 && (e.keyCode == KeyCode.UpArrow || e.keyCode == KeyCode.DownArrow)) { if (e.keyCode == KeyCode.UpArrow && popup.listView.selectedIndex == 0) { popup.listView.ClearSelection(); } else if (e.keyCode == KeyCode.DownArrow && popup.listView.selectedIndex == -1) { popup.listView.selectedIndex = 0; } else { using (var evt = KeyDownEvent.GetPooled(e.character, e.keyCode, e.modifiers)) { evt.elementTarget = popup.listView.scrollView.contentContainer; popup.listView.SendEvent(evt); } } e.StopImmediatePropagation(); } else if (!IsNavigationEvent(e)) { ScheduleTextChange(); } } EditorWindow GetEditorWindow() { if (m_TextField.elementPanel == null) { return null; } return m_TextField.elementPanel.ownerObject switch { EditorWindow editorWindow => editorWindow, HostView hostView => hostView.actualView, IEditorWindowModel ewm => ewm.window, _ => null }; } } class FieldSearchCompleterPopup : StyleFieldPopup { static readonly string s_UssClassName = "unity-field-search-completer-popup"; public static readonly string s_DetailsViewUssClassName = s_UssClassName + "__details-view"; public static readonly string s_FooterUssClassName = s_UssClassName + "__footer"; public static readonly string s_ResultLabelUssClassName = s_UssClassName + "__result-label"; int m_HoveredIndex = -1; public Action<int> elementChosen; public Action<int> selectionChanged; public event Action<int> hoveredItemChanged; public int hoveredIndex { get => m_HoveredIndex; set { if (m_HoveredIndex == value) return; m_HoveredIndex = value; hoveredItemChanged?.Invoke(value); } } public ListView listView { get; } public Label resultLabel { get; } public FieldSearchCompleterPopup() { AddToClassList(s_UssClassName); listView = new ListView(); var sv = listView.Q<ScrollView>(); sv.style.flexGrow = 0; sv.style.flexShrink = 1; listView.Q<ScrollView>().horizontalScrollerVisibility = ScrollerVisibility.Hidden; listView.itemsChosen += (obj) => { elementChosen?.Invoke(listView.selectedIndex); }; listView.selectionChanged += (obj) => { selectionChanged?.Invoke(listView.selectedIndex); }; listView.allowSingleClickChoice = true; Add(listView); Add(resultLabel = new Label()); resultLabel.AddToClassList(s_ResultLabelUssClassName); // Avoid focus change when clicking on the popup listView.Q<ScrollView>().contentContainer.focusable = true; listView.Query<Scroller>().ForEach(s => { s.focusable = false; }); listView.focusable = false; listView.delegatesFocus = false; RegisterCallback<PointerDownEvent>(e => { e.StopImmediatePropagation(); }); listView.scrollView.contentContainer.RegisterCallback<PointerMoveEvent>(OnPointerMove); listView.scrollView.contentContainer.RegisterCallback<PointerLeaveEvent>(OnPointerLeaveEvent); style.minHeight = 0; } void OnPointerMove(PointerMoveEvent evt) { var index = listView.virtualizationController.GetIndexFromPosition(evt.localPosition); if (index > listView.viewController.itemsSource.Count - 1) { hoveredIndex = -1; } else { hoveredIndex = index; } } void OnPointerLeaveEvent(PointerLeaveEvent evt) { hoveredIndex = -1; } public override void AdjustGeometry() { const int minListViewHeight = 160; base.AdjustGeometry(); listView.style.minHeight = Math.Min(minListViewHeight, listView.fixedItemHeight * (listView.itemsSource != null ? listView.itemsSource.Count : 0)); } public void Refresh() { listView.RefreshItems(); listView.ClearSelection(); } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FieldSearchCompleter.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/FieldSearchCompleter.cs", "repo_id": "UnityCsReference", "token_count": 15999 }
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 UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Unity.UI.Builder { internal class StyleFieldPopup : VisualElement { static readonly string s_UssClassName = "unity-style-field-popup"; static readonly string s_NativeWindowUssClassName = s_UssClassName + "--native-window"; const int k_PopupMaxWidth = 350; private VisualElement m_AnchoredControl; private bool m_UsesNativeWindow; private StyleFieldPopupWindow m_Window; private Rect m_AnchoredControlScreenPos; public event Action onShow; public event Action onHide; public bool isOpened => usesNativeWindow ? m_Window != null : resolvedStyle.display == DisplayStyle.Flex; public VisualElement anchoredControl { get { return m_AnchoredControl; } set { if (m_AnchoredControl == value) return; if (m_AnchoredControl != null) { m_AnchoredControl.UnregisterCallback<GeometryChangedEvent>(OnAnchoredControlGeometryChanged); m_AnchoredControl.UnregisterCallback<DetachFromPanelEvent>(OnAnchoredControlDetachedFromPath); } m_AnchoredControl = value; if (m_AnchoredControl != null) { m_AnchoredControl.RegisterCallback<GeometryChangedEvent>(OnAnchoredControlGeometryChanged); m_AnchoredControl.RegisterCallback<DetachFromPanelEvent>(OnAnchoredControlDetachedFromPath); } } } /// <summary> /// Indicates whether the popup uses a native window. /// </summary> public bool usesNativeWindow { get => m_UsesNativeWindow; set { m_UsesNativeWindow = value; EnableInClassList(s_NativeWindowUssClassName, value); } } public StyleFieldPopupWindow nativeWindow => m_Window; public StyleFieldPopup() { AddToClassList(s_UssClassName); // Popup is hidden by default AddToClassList(BuilderConstants.HiddenStyleClassName); this.RegisterCallback<GeometryChangedEvent>(e => EnsureVisibilityInParent()); // Prevent PointerDownEvent on a child from switching focus. this.RegisterCallback<PointerDownEvent>(e => focusController.IgnoreEvent(e), TrickleDown.TrickleDown); } public virtual void Show() { if (m_AnchoredControl.HasProperty(BuilderConstants.CompleterAnchoredControlScreenRectVEPropertyName)) { m_AnchoredControlScreenPos = (Rect)m_AnchoredControl.GetProperty(BuilderConstants.CompleterAnchoredControlScreenRectVEPropertyName); } else { m_AnchoredControlScreenPos = GUIUtility.GUIToScreenRect(m_AnchoredControl.worldBound); } AdjustGeometry(); onShow?.Invoke(); m_Window?.Close(); RemoveFromClassList(BuilderConstants.HiddenStyleClassName); // Create a new window if (usesNativeWindow) { m_Window = ScriptableObject.CreateInstance<StyleFieldPopupWindow>(); m_Window.ShowAsDropDown(m_AnchoredControlScreenPos, new Vector2(Mathf.Max(200, m_AnchoredControl.worldBound.width), 30), null, ShowMode.PopupMenu, false); // Reset the min and max size of the window m_Window.minSize = Vector2.zero; m_Window.maxSize = new Vector2(1000, 1000); m_Window.content = this; // Load assets. var mainSS = BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UIBuilderPackagePath + "/Builder.uss"); var themeSS = EditorGUIUtility.isProSkin ? BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UIBuilderPackagePath + "/BuilderDark.uss") : BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(BuilderConstants.UIBuilderPackagePath + "/BuilderLight.uss"); // Load styles. m_Window.rootVisualElement.styleSheets.Add(mainSS); m_Window.rootVisualElement.styleSheets.Add(themeSS); m_Window.closed += () => Hide(true); } } public virtual void Hide() { if (!isOpened) return; Hide(false); } void Hide(bool closingWindow) { if (usesNativeWindow) { if (closingWindow) { RemoveFromHierarchy(); onHide?.Invoke(); m_Window = null; } else { m_Window.Close(); } } else { AddToClassList(BuilderConstants.HiddenStyleClassName); onHide?.Invoke(); } } void OnAnchoredControlDetachedFromPath(DetachFromPanelEvent e) { Hide(); } void OnAnchoredControlGeometryChanged(GeometryChangedEvent e) { AdjustGeometry(); } public virtual void AdjustGeometry() { if (m_AnchoredControl != null && m_AnchoredControl.visible && parent != null && !float.IsNaN(layout.width) && !float.IsNaN(layout.height)) { if (usesNativeWindow) { if (m_Window != null) { var pos = m_AnchoredControlScreenPos; pos.y += m_AnchoredControl.layout.height; var h = resolvedStyle.height; var size = m_Window.position.size; size.y = h; m_Window.position = new Rect(pos.position, size); } } else { var pos = m_AnchoredControl.ChangeCoordinatesTo(parent, Vector2.zero); style.left = pos.x; style.top = pos.y + m_AnchoredControl.layout.height; style.width = Math.Max(k_PopupMaxWidth, m_AnchoredControl.resolvedStyle.width); } } } public virtual Vector2 GetAdjustedPosition() { if (m_AnchoredControl == null) { return new Vector2(Mathf.Min(style.left.value.value, parent.layout.width - resolvedStyle.width), Mathf.Min(style.top.value.value, parent.layout.height - resolvedStyle.height)); } else { var currentPos = new Vector2(style.left.value.value, style.top.value.value); var newPos = new Vector2(Mathf.Min(currentPos.x, parent.layout.width - resolvedStyle.width), currentPos.y); var fieldTopLeft = m_AnchoredControl.ChangeCoordinatesTo(parent, Vector2.zero); var fieldBottom = fieldTopLeft.y + m_AnchoredControl.layout.height; const float tolerance = 2f; newPos.y = (fieldBottom < parent.layout.height / 2) ? (currentPos.y) : (fieldTopLeft.y - resolvedStyle.height); if (Math.Abs(newPos.x - currentPos.x) > tolerance || Math.Abs(newPos.y - currentPos.y) > tolerance) return newPos; return currentPos; } } private void EnsureVisibilityInParent() { if (parent != null && !float.IsNaN(layout.width) && !float.IsNaN(layout.height) && !usesNativeWindow) { var pos = GetAdjustedPosition(); style.left = pos.x; style.top = pos.y; } } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/StyleFieldPopup.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleField/StyleFieldPopup.cs", "repo_id": "UnityCsReference", "token_count": 4123 }
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; using System.Linq; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; using UnityEngine.UIElements.StyleSheets; namespace Unity.UI.Builder { /// <summary> /// Transient type detailing which values were actually computed for a given <see cref="StyleProperty"/>. When a /// <see cref="StyleProperty"/> is set on <see cref="StyleSheet"/>, this manipulator can be used to retrieve the /// computed values and their origin as well as modifying the said values. When setting an explicit value, variables /// will be removed automatically. /// </summary> /// <remarks> /// Any external changes to the related <see cref="StyleSheet"/>s' internal structure may invalidate this data. /// </remarks> class StylePropertyManipulator : IDisposable { /// <summary> /// Helper type to help setting a string as a variable in a generic context. /// </summary> readonly struct Variable { public readonly string name; public Variable(string name) { this.name = name; } } /// <summary> /// Helper type to map a linear value index into the internal representation indices. /// </summary> /// <remarks> /// When trying to resolve a variable, it may lead to multiple values instead of a single one, so we treat the /// definition and the resolved states separately. For example: /// 0 1 2 (Parts) /// transition-duration: 100ms, var(--my-value-list), 500ms; /// could be resolved as: /// 0 1 2 3 4 (Values) /// transition-duration, 100ms, 200ms, 300ms, 400ms, 500ms; /// /// In the example above, asking the value at index=3 would return { 1, 2 }, because the value maps to the third /// value of the second part. /// </remarks>> readonly ref struct Index { public readonly int index; public readonly int partIndex; public readonly int valueIndex; public Index(int index, int partIndex, int valueIndex) { this.index = index; this.partIndex = partIndex; this.valueIndex = valueIndex; } } internal struct StyleValueHandleContext { /// <summary> /// The stylesheet in which the <see cref="handle"/> lives. /// </summary> public StyleSheet styleSheet; /// <summary> /// Handle to the actual value inside the <see cref="styleSheet"/> /// </summary> public StyleValueHandle handle; public Dimension AsDimension() { if (handle.valueType == StyleValueType.Dimension) return styleSheet.ReadDimension(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.Dimension}`."); } public StyleValueKeyword AsKeyword() { if (handle.valueType == StyleValueType.Keyword) return styleSheet.ReadKeyword(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.Keyword}`."); } public float AsFloat() { if (handle.valueType == StyleValueType.Float) return styleSheet.ReadFloat(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.Float}`."); } public Color AsColor() { if (handle.valueType == StyleValueType.Color) return styleSheet.ReadColor(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.Color}`."); } public string AsResourcePath() { if (handle.valueType == StyleValueType.ResourcePath) return styleSheet.ReadResourcePath(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.ResourcePath}`."); } public UnityEngine.Object AsAssetReference() { if (handle.valueType == StyleValueType.AssetReference) return styleSheet.ReadAssetReference(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.AssetReference}`."); } public T AsEnum<T>() where T : Enum { if (handle.valueType == StyleValueType.Enum) return (T) Enum.Parse(typeof(T), styleSheet.ReadEnum(handle)); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.Enum}`."); } public string AsEnum() { if (handle.valueType == StyleValueType.Enum) return styleSheet.ReadEnum(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.Enum}`."); } public string AsString() { if (handle.valueType == StyleValueType.String) return styleSheet.ReadString(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.String}`."); } public ScalableImage AsScalableImage() { if (handle.valueType == StyleValueType.ScalableImage) return styleSheet.ReadScalableImage(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.ScalableImage}`."); } public string AsMissingAssetReference() { if (handle.valueType == StyleValueType.MissingAssetReference) return styleSheet.ReadMissingAssetReferenceUrl(handle); throw new InvalidCastException( $"Cannot cast value of type `{handle.valueType}` into a `{StyleValueType.MissingAssetReference}`."); } } internal struct StylePropertyPart : IDisposable { static readonly UnityEngine.Pool.ObjectPool<List<StyleValueHandleContext>> s_Pool = new UnityEngine.Pool.ObjectPool<List<StyleValueHandleContext>>( () => new List<StyleValueHandleContext>(), null, s => { s.Clear(); } ); /// <summary> /// Helper method to create a<see cref="StylePropertyPart"/> with a pre-pooled list of handles. /// </summary> /// <returns></returns> public static StylePropertyPart Create() { return new StylePropertyPart {handles = s_Pool.Get()}; } /// <summary> /// Offset in the originating <see cref="StyleProperty"/> handles array. /// </summary> public int offset; /// <summary> /// Indicates if the handles were resolved as part of a variable. /// </summary> public bool isVariable; /// <summary> /// If <see cref="isVariable"/> is set, contains the name of the main variable. /// </summary> public string variableName; /// <summary> /// Handles that are related to this style property value. For a variable, this can resolve to multiple values. /// </summary> public List<StyleValueHandleContext> handles; public bool isVariableUnresolved => isVariable && handles?.Count == 0; public void Dispose() { if (null != handles) s_Pool.Release(handles); offset = 0; isVariable = false; variableName = string.Empty; } } static readonly UnityEngine.Pool.ObjectPool<StylePropertyManipulator> s_Pool = new UnityEngine.Pool.ObjectPool<StylePropertyManipulator>( () => new StylePropertyManipulator(), null, s => { s.styleSheet = null; s.styleRule = null; s.propertyName = null; s.element = null; s.m_StyleProperty = null; foreach (var value in s.stylePropertyParts) { value.Dispose(); } s.stylePropertyParts.Clear(); } ); public static StylePropertyManipulator GetPooled() { return s_Pool.Get(); } // Intentionally defined to force usage of the pool StylePropertyManipulator() { } StyleProperty m_StyleProperty; public StyleSheet styleSheet; public string propertyName; public StyleProperty styleProperty => m_StyleProperty ??= GetStyleProperty(styleRule, propertyName); public StyleRule styleRule; public VisualElement element; public bool editorExtensionMode; internal List<StylePropertyPart> stylePropertyParts = new List<StylePropertyPart>(); /// <summary> /// Returns all the values as their string representation. /// </summary> /// <returns></returns> /// <exception cref="ArgumentOutOfRangeException"></exception> public IEnumerable<string> GetValuesAsString() { foreach (var part in stylePropertyParts) { foreach (var valueHandle in part.handles) { switch (valueHandle.handle.valueType) { case StyleValueType.Invalid: yield return "<invalid>"; break; case StyleValueType.Keyword: yield return valueHandle.styleSheet.ReadKeyword(valueHandle.handle).ToUssString(); break; case StyleValueType.Float: yield return valueHandle.styleSheet.ReadFloat(valueHandle.handle).ToString(); break; case StyleValueType.Dimension: yield return valueHandle.styleSheet.ReadDimension(valueHandle.handle).ToString(); break; case StyleValueType.Color: yield return valueHandle.styleSheet.ReadColor(valueHandle.handle).ToString(); break; case StyleValueType.ResourcePath: yield return valueHandle.styleSheet.ReadResourcePath(valueHandle.handle); break; case StyleValueType.AssetReference: yield return valueHandle.styleSheet.ReadAssetReference(valueHandle.handle).ToString(); break; case StyleValueType.Enum: yield return valueHandle.styleSheet.ReadEnum(valueHandle.handle); break; case StyleValueType.Variable: yield return valueHandle.styleSheet.ReadVariable(valueHandle.handle); break; case StyleValueType.String: yield return valueHandle.styleSheet.ReadString(valueHandle.handle); break; case StyleValueType.Function: yield return valueHandle.styleSheet.ReadFunction(valueHandle.handle).ToString(); break; case StyleValueType.CommaSeparator: break; case StyleValueType.ScalableImage: yield return valueHandle.styleSheet.ReadScalableImage(valueHandle.handle).ToString(); break; case StyleValueType.MissingAssetReference: yield return valueHandle.styleSheet.ReadMissingAssetReferenceUrl(valueHandle.handle); break; default: throw new ArgumentOutOfRangeException(); } } } } public int GetPartsCount() { return stylePropertyParts.Count; } public int GetValuesCount() { var count = 0; foreach (var part in stylePropertyParts) { if (part.isVariable && part.isVariableUnresolved) count += 1; else count += part.handles.Count; } return count; } public bool IsVariableAtIndex(int index) { var indices = GetInternalIndices(index); return stylePropertyParts[indices.partIndex].isVariable; } public string GetVariableNameAtIndex(int index) { var indices = GetInternalIndices(index); return stylePropertyParts[indices.partIndex].variableName; } public bool IsKeywordAtIndex(int index) { return GetValueContextAtIndex(index).handle.valueType == StyleValueType.Keyword; } public StyleValueHandleContext GetValueContextAtIndex(int index) { var indices = GetInternalIndices(index); // Unresolved variable return indices.valueIndex < 0 ? default : stylePropertyParts[indices.partIndex].handles[indices.valueIndex]; } public void AddValue<T>(T value, StyleValueType valueType) { Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage); EnsureStylePropertyExists(); var offset = styleProperty.values.Length; if (offset > 0) { AddCommaSeparator(); ++offset; } var handle = AddTypedValue(value, valueType); var part = CreatePart(styleSheet, handle, offset); stylePropertyParts.Add(part); UpdateStylesheet(); } public void AddVariable(string variableName) { Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage); EnsureStylePropertyExists(); var offset = styleProperty.values.Length; if (offset > 0) { AddCommaSeparator(); ++offset; } var part = ResolveVariable(AddVariableToStyleSheet(variableName)); part.offset = offset; stylePropertyParts.Add(part); UpdateStylesheet(); } public void SetValueAtIndex<T>(int index, T value, StyleValueType type) { if (null == styleProperty) throw new InvalidOperationException(); var indices = GetInternalIndices(index); // Undo/Redo Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage); SetValue(indices, value, type); UpdateStylesheet(); } public void SetVariableAtIndex(int index, string variableName) { if (null == styleProperty) throw new InvalidOperationException(); var indices = GetInternalIndices(index); // Undo/Redo Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage); if (stylePropertyParts[indices.partIndex].isVariable) OverrideVariableWithValue(indices, new Variable(variableName), StyleValueType.Variable); else SetVariable(indices, variableName); UpdateStylesheet(); } public void RemoveAtIndex(int index) { var indices = GetInternalIndices(index); Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage); RemoveValue(indices); UpdateStylesheet(); } public void RemoveProperty() { if (null != styleProperty) { styleSheet.RemoveProperty(styleRule, styleProperty); m_StyleProperty = null; foreach (var part in stylePropertyParts) { part.Dispose(); } stylePropertyParts.Clear(); UpdateStylesheet(); } } public void ClearValues() { if (null == styleProperty) return; Undo.RegisterCompleteObjectUndo(styleSheet, BuilderConstants.ChangeUIStyleValueUndoMessage); styleProperty.values = Array.Empty<StyleValueHandle>(); foreach (var part in stylePropertyParts) { part.Dispose(); } stylePropertyParts.Clear(); UpdateStylesheet(); } StyleValueHandle TransferTypedValue(StyleValueHandleContext handle) { switch (handle.handle.valueType) { case StyleValueType.Keyword: return AddTypedValue(handle.AsKeyword(), StyleValueType.Keyword); case StyleValueType.Float: return AddTypedValue(handle.AsFloat(), StyleValueType.Float); case StyleValueType.Dimension: return AddTypedValue(handle.AsDimension(), StyleValueType.Dimension); case StyleValueType.Color: return AddTypedValue(handle.AsColor(), StyleValueType.Color); case StyleValueType.ResourcePath: return AddTypedValue(handle.AsResourcePath(), StyleValueType.ResourcePath); case StyleValueType.AssetReference: return AddTypedValue(handle.AsAssetReference(), StyleValueType.AssetReference); case StyleValueType.Enum: return AddTypedValue(handle.AsEnum(), StyleValueType.Enum); case StyleValueType.String: return AddTypedValue(handle.AsString(), StyleValueType.String); case StyleValueType.ScalableImage: return AddTypedValue(handle.AsScalableImage(), StyleValueType.ScalableImage); case StyleValueType.MissingAssetReference: return AddTypedValue(handle.AsString(), StyleValueType.MissingAssetReference); case StyleValueType.Invalid: case StyleValueType.Variable: case StyleValueType.Function: case StyleValueType.CommaSeparator: default: throw new ArgumentOutOfRangeException(); } } void SetTypedValue<T>(StyleValueHandleContext handle, T value) { switch (handle.handle.valueType) { case StyleValueType.Keyword: styleSheet.SetValue(handle.handle, (StyleValueKeyword)(object) value); break; case StyleValueType.Float: styleSheet.SetValue(handle.handle, (float)(object) value); break; case StyleValueType.Dimension: styleSheet.SetValue(handle.handle, (Dimension)(object) value); break; case StyleValueType.Color: styleSheet.SetValue(handle.handle, (Color)(object) value); break; case StyleValueType.ResourcePath: styleSheet.SetValue(handle.handle, (string)(object) value); break; case StyleValueType.AssetReference: styleSheet.SetValue(handle.handle, (UnityEngine.Object)(object) value); break; case StyleValueType.Enum: if (typeof(T).IsEnum || value is Enum) styleSheet.SetValue(handle.handle, (Enum)(object) value); else if (typeof(T) == typeof(string) || value is string) styleSheet.SetValue(handle.handle, (string)(object) value); break; case StyleValueType.String: styleSheet.SetValue(handle.handle, (string)(object) value); break; case StyleValueType.MissingAssetReference: styleSheet.SetValue(handle.handle, (string)(object) value); break; case StyleValueType.ScalableImage: // Not actually supported // styleSheet.SetValue(handle.handle, handle.AsScalableImage()); // break; // These are not "values". case StyleValueType.Invalid: case StyleValueType.Variable: case StyleValueType.Function: case StyleValueType.CommaSeparator: default: throw new ArgumentOutOfRangeException(); } } StyleValueHandle AddTypedValue<T>(T value, StyleValueType type) { switch (type) { case StyleValueType.Keyword: return styleSheet.AddValue(styleProperty, (StyleValueKeyword)(object) value); case StyleValueType.Float: return styleSheet.AddValue(styleProperty, (float)(object) value); case StyleValueType.Dimension: return styleSheet.AddValue(styleProperty, (Dimension)(object) value); case StyleValueType.Color: return styleSheet.AddValue(styleProperty, (Color)(object) value); case StyleValueType.ResourcePath: return styleSheet.AddValue(styleProperty, (string)(object) value); case StyleValueType.AssetReference: return styleSheet.AddValue(styleProperty, (UnityEngine.Object)(object) value); case StyleValueType.Enum: { if (value is string strValue) { // Add value data to data array. var index = styleSheet.AddValueToArray(strValue); // Add value object to property. return styleSheet.AddValueHandle(styleProperty, index, StyleValueType.Enum); } return styleSheet.AddValue(styleProperty, (Enum) (object) value); } case StyleValueType.String: return styleSheet.AddValue(styleProperty, (string)(object) value); case StyleValueType.MissingAssetReference: return styleSheet.AddValue(styleProperty, (string)(object) value); case StyleValueType.ScalableImage: // Not actually supported //return styleSheet.AddValue(styleProperty, (ScalableImage)(object) value); // These are not "values". case StyleValueType.Invalid: case StyleValueType.Variable: case StyleValueType.Function: case StyleValueType.CommaSeparator: default: throw new ArgumentOutOfRangeException(nameof(type), type, null); } } void OverrideVariableWithValue<T>(Index indices, T value, StyleValueType valueType) { if (!stylePropertyParts[indices.partIndex].isVariable) return; var part = stylePropertyParts[indices.partIndex]; var initialOffset = part.offset; var nextOffset = indices.partIndex + 1 >= stylePropertyParts.Count ? -1 : stylePropertyParts[indices.partIndex + 1].offset; // Range of handles to remove in the StyleProperty.values array var range = nextOffset < 0 ? styleProperty.values.Length - initialOffset : nextOffset - initialOffset; var newParts = new List<StylePropertyPart>(); // To set an explicit value on top of a variable, we must first remove the variable. In the case where // the variable points to a list of values, we must remove all values of the list and set them as // explicit values of the same type. var list = styleProperty.values.ToList(); list.RemoveRange(initialOffset, range); var currentOffset = initialOffset; for (var i = 0; i < part.handles.Count; ++i, ++currentOffset) { var propertyValue = StylePropertyPart.Create(); propertyValue.offset = currentOffset; if (i == indices.valueIndex && typeof(Variable).IsAssignableFrom(typeof(T)) && value is Variable variable) { var handles = AddVariableToStyleSheet(variable.name); var property = new StyleProperty { name = styleProperty.name, values = handles }; var ib = 0; var newPart = ResolveValueOrVariable(styleSheet, element, styleRule, property, ref ib, editorExtensionMode); list.InsertRange(currentOffset, handles); currentOffset += 2; if (i < part.handles.Count - 1 || indices.partIndex < stylePropertyParts.Count - 1) list.Insert(++currentOffset, new StyleValueHandle(-1, StyleValueType.CommaSeparator)); newParts.Add(newPart); } else { var handle = i == indices.valueIndex ? AddTypedValue(value, valueType) : TransferTypedValue(part.handles[i]); list.Insert(currentOffset, handle); if (i < part.handles.Count - 1 || indices.partIndex < stylePropertyParts.Count - 1) list.Insert(++currentOffset, new StyleValueHandle(-1, StyleValueType.CommaSeparator)); propertyValue.handles.Add(new StyleValueHandleContext { styleSheet = styleSheet, handle = handle }); newParts.Add(propertyValue); } } if (part.isVariableUnresolved && indices.valueIndex == -1) { if (typeof(Variable).IsAssignableFrom(typeof(T)) && value is Variable variable) { var handles = AddVariableToStyleSheet(variable.name); var newPart = StylePropertyPart.Create(); newPart.offset = currentOffset; newPart.handles.Add( new StyleValueHandleContext { styleSheet = styleSheet, handle = handles[2], }); list.InsertRange(currentOffset, handles); newParts.Add(newPart); } else { var handle = AddTypedValue(value, valueType); var newPart = StylePropertyPart.Create(); newPart.offset = currentOffset; newPart.handles.Add(new StyleValueHandleContext { styleSheet = styleSheet, handle = handle, }); list.Insert(currentOffset, handle); newParts.Add(newPart); } } styleProperty.values = list.ToArray(); stylePropertyParts.RemoveAt(indices.partIndex); // Manually dispose removed part part.Dispose(); stylePropertyParts.InsertRange(indices.partIndex, newParts); var partsCount = indices.partIndex + newParts.Count; var offset = currentOffset - nextOffset; for (var i = partsCount; i < stylePropertyParts.Count; ++i) { var nextPart = stylePropertyParts[i]; nextPart.offset += offset; stylePropertyParts[i] = nextPart; } } void AddCommaSeparator() { styleSheet.AddValueHandle(styleProperty, -1, StyleValueType.CommaSeparator); } StyleValueHandle AddKeywordToStyleSheet(StyleValueKeyword keyword) { return styleSheet.AddValue(styleProperty, keyword); } StyleValueHandle[] AddVariableToStyleSheet(string variableName) { return styleSheet.AddVariable(styleProperty, variableName); } void SetValue<T>(Index indices, T value, StyleValueType valueType) { var part = stylePropertyParts[indices.partIndex]; if (part.isVariable) { OverrideVariableWithValue(indices, value, valueType); } // The assumption here is that an individual value which is not a variable will always have a single // resolved value else { if (part.handles[0].handle.valueType == valueType) { var valueHandle = part.handles[0]; SetTypedValue(valueHandle, value); } else { var initialOffset = part.offset; var list = styleProperty.values.ToList(); list.RemoveAt(initialOffset); var handle = AddTypedValue(value, valueType); list.Insert(initialOffset, handle); styleProperty.values = list.ToArray(); var valueContext = part.handles[0]; valueContext.handle = handle; part.handles[0] = valueContext; } } } void SetVariable(Index indices, string variableName) { var part = stylePropertyParts[indices.partIndex]; var initialOffset = part.offset; var nextOffset = indices.partIndex + 1 >= stylePropertyParts.Count ? -1 : stylePropertyParts[indices.partIndex + 1].offset /* To account for the comma */ - 1; // Range of handles to remove in the StyleProperty.values array var range = nextOffset < 0 ? styleProperty.values.Length - initialOffset : nextOffset - initialOffset; var list = styleProperty.values.ToList(); list.RemoveRange(initialOffset, range); var handles = AddVariableToStyleSheet(variableName); list.InsertRange(initialOffset, handles); styleProperty.values = list.ToArray(); var i = part.offset; var newPart = ResolveValueOrVariable(styleSheet, element, styleRule, styleProperty, ref i, editorExtensionMode); stylePropertyParts.RemoveAt(indices.partIndex); stylePropertyParts.Insert(indices.partIndex, newPart); part.Dispose(); AdjustOffsets(indices.partIndex, i - nextOffset); } void AdjustOffsets(int indicesPartIndex, int partOffset) { for (var i = indicesPartIndex; i < stylePropertyParts.Count; ++i) { var stylePropertyPart = stylePropertyParts[i]; stylePropertyPart.offset += partOffset; stylePropertyParts[i] = stylePropertyPart; } } Index GetInternalIndices(int index) { if (index < 0) throw new ArgumentOutOfRangeException(); var current = index; var partIndex = 0; for (; partIndex < stylePropertyParts.Count; ++partIndex) { var valueIndex = 0; var part = stylePropertyParts[partIndex]; for (; valueIndex < part.handles.Count; ++valueIndex) { if (--current < 0) { return new Index(index, partIndex, valueIndex); } } if (!part.isVariableUnresolved) continue; if (--current < 0) return new Index(index, partIndex, -1); } throw new ArgumentOutOfRangeException(); } void RemoveValue(Index indices) { var part = stylePropertyParts[indices.partIndex]; var initialOffset = part.offset; var nextOffset = indices.partIndex + 1 >= stylePropertyParts.Count ? -1 : stylePropertyParts[indices.partIndex + 1].offset; // Range of handles to remove in the StyleProperty.values array var range = nextOffset < 0 ? styleProperty.values.Length - initialOffset : nextOffset - initialOffset; if (part.isVariable) { if (part.isVariableUnresolved && indices.valueIndex == -1) { // If there's only a single value, simply remove the property. if (stylePropertyParts.Count == 1) { RemoveProperty(); return; } var valueList = styleProperty.values.ToList(); if (indices.partIndex > 0) initialOffset -= 1; if (indices.partIndex == stylePropertyParts.Count - 1) range += 1; valueList.RemoveRange(initialOffset, range); var firstPropertyValue = stylePropertyParts[indices.partIndex]; for(var i = indices.partIndex + 1; i < stylePropertyParts.Count; ++i) { var propertyValue = stylePropertyParts[i]; propertyValue.offset -= 2; } firstPropertyValue.Dispose(); stylePropertyParts.RemoveAt(indices.partIndex); styleProperty.values = valueList.ToArray(); return; } var newParts = new List<StylePropertyPart>(); // To set an explicit value on top of a variable, we must first remove the variable. In the case where // the variable points to a list of values, we must remove all values of the list and set them as // explicit values of the same type. var list = styleProperty.values.ToList(); list.RemoveRange(initialOffset, range); var currentOffset = initialOffset; for (var i = 0; i < part.handles.Count; ++i, ++currentOffset) { var propertyValue = StylePropertyPart.Create(); propertyValue.offset = currentOffset; var handle = TransferTypedValue(part.handles[i]); list.Insert(currentOffset, handle); if (i < part.handles.Count - 1 || indices.partIndex < stylePropertyParts.Count - 1) list.Insert(++currentOffset, new StyleValueHandle(-1, StyleValueType.CommaSeparator)); propertyValue.handles.Add(new StyleValueHandleContext { styleSheet = styleSheet, handle = handle }); newParts.Add(propertyValue); } styleProperty.values = list.ToArray(); stylePropertyParts.RemoveAt(indices.partIndex); // Manually dispose removed part part.Dispose(); stylePropertyParts.InsertRange(indices.partIndex, newParts); var adjustIndex = indices.partIndex + newParts.Count; var offset = currentOffset - nextOffset; for (var i = adjustIndex; i < stylePropertyParts.Count; ++i) { var nextPart = stylePropertyParts[i]; nextPart.offset += offset; stylePropertyParts[i] = nextPart; } // Now that the variable has been transferred as explicit values, we can remove the actual value. if (indices.valueIndex >= 0) RemoveAtIndex(indices.index); } else { // If there's only a single value, simply remove the property. if (stylePropertyParts.Count == 1) { RemoveProperty(); return; } var list = styleProperty.values.ToList(); if (indices.partIndex > 0) initialOffset -= 1; if (indices.partIndex == stylePropertyParts.Count - 1) range += 1; list.RemoveRange(initialOffset, range); var partToRemove = stylePropertyParts[indices.partIndex]; partToRemove.Dispose(); stylePropertyParts.RemoveAt(indices.partIndex); AdjustOffsets(indices.partIndex, -2); styleProperty.values = list.ToArray(); } } public void Dispose() { s_Pool.Release(this); } internal static StylePropertyPart ResolveValueOrVariable( StyleSheet styleSheet, VisualElement element, StyleRule styleRule, StyleProperty property, ref int currentIndex, bool isEditorExtensionMode) { var handle = property.values[currentIndex]; switch (handle.valueType) { case StyleValueType.Invalid: case StyleValueType.Keyword: case StyleValueType.Float: case StyleValueType.Dimension: case StyleValueType.Color: case StyleValueType.ResourcePath: case StyleValueType.AssetReference: case StyleValueType.Enum: case StyleValueType.String: case StyleValueType.ScalableImage: case StyleValueType.MissingAssetReference: { // skip comma ++currentIndex; var part = StylePropertyPart.Create(); part.handles.Add(new StyleValueHandleContext { styleSheet = styleSheet, handle = handle }); return part; } case StyleValueType.Function: { var argCountHandle = property.values[++currentIndex]; var argCount = (int) styleSheet.ReadFloat(argCountHandle); var varHandle = property.values[++currentIndex]; var variable = styleSheet.ReadVariable(varHandle); using (var manipulator = ResolveVariable(element, styleSheet, styleRule, variable, isEditorExtensionMode)) { if (argCount == 1) { // Skip comma ++currentIndex; var part = StylePropertyPart.Create(); if (null == manipulator || manipulator.stylePropertyParts.Count == 0) { part.isVariable = true; part.variableName = variable; return part; } part.handles.AddRange(manipulator.stylePropertyParts.SelectMany(o => o.handles)); part.isVariable = true; part.variableName = variable; return part; } } // Skip comma and point to next function argument. currentIndex += 2; var fallbackPart = ResolveValueOrVariable(styleSheet, element, styleRule, property, ref currentIndex, isEditorExtensionMode); fallbackPart.isVariable = true; fallbackPart.variableName = variable; return fallbackPart; } // These should never be hit as they are being handled by the cases above case StyleValueType.Variable: case StyleValueType.CommaSeparator: throw new InvalidOperationException(); default: throw new ArgumentOutOfRangeException(); } } static StylePropertyManipulator ResolveVariable( VisualElement currentVisualElement, StyleSheet styleSheet, StyleRule styleRule, string variableName, bool editorExtensionMode) { var customStyles = currentVisualElement.computedStyle.customProperties; if (customStyles != null && customStyles.TryGetValue(variableName, out var stylePropertyValue)) { var propValue = stylePropertyValue; if (!editorExtensionMode && propValue.sheet.isDefaultStyleSheet) return null; if (propValue.sheet.isDefaultStyleSheet) { StyleVariableUtilities.editorVariableDescriptions.TryGetValue(variableName, out var variableDescription); } var propStyleSheet = propValue.sheet; for (var propertyIndex = styleRule.properties.Length - 1; propertyIndex >= 0; --propertyIndex) { var property = styleRule.properties[propertyIndex]; if (property.name != variableName) continue; var manipulator = GetPooled(); for (var i = 0; i < property.values.Length; ++i) { var index = i; var offset = ResolveValueOrVariable(propStyleSheet, currentVisualElement, styleRule, property, ref i, editorExtensionMode); offset.offset = index; offset.isVariable = true; offset.variableName = variableName; manipulator.stylePropertyParts.Add(offset); } return manipulator; } } // Look within :root selectors var styleSheets = styleSheet.flattenedRecursiveImports; var rootManipulator = ResolveVariableFromRootSelectorInStyleSheet(currentVisualElement, styleSheet, styleRule, variableName, editorExtensionMode); if (null != rootManipulator) return rootManipulator; for (var i = styleSheets.Count - 1; i >= 0; --i) { var sheet = styleSheets[i]; rootManipulator = ResolveVariableFromRootSelectorInStyleSheet(currentVisualElement, sheet, styleRule, variableName, editorExtensionMode); if (null != rootManipulator) return rootManipulator; } return null; } static StylePropertyManipulator ResolveVariableFromRootSelectorInStyleSheet( VisualElement currentVisualElement, StyleSheet sheet, StyleRule styleRule, string variableName, bool editorExtensionMode) { for (var selectorIndex = sheet.complexSelectors.Length - 1; selectorIndex >= 0; --selectorIndex) { var complexSelector = sheet.complexSelectors[selectorIndex]; if (!complexSelector.isSimple) continue; var simpleSelector = complexSelector.selectors[0]; var selectorPart = simpleSelector.parts[0]; if (selectorPart.type != StyleSelectorType.Wildcard && selectorPart.type != StyleSelectorType.PseudoClass) continue; if (selectorPart.type == StyleSelectorType.PseudoClass && selectorPart.value != "root") continue; var rule = complexSelector.rule; for (var propertyIndex = rule.properties.Length - 1; propertyIndex >= 0; --propertyIndex) { var property = rule.properties[propertyIndex]; if (property.name != variableName) { continue; } var manipulator = GetPooled(); for (var i = 0; i < property.values.Length; ++i) { var index = i; var newPart = ResolveValueOrVariable(sheet, currentVisualElement, styleRule, property, ref i, editorExtensionMode); newPart.offset = index; newPart.isVariable = true; newPart.variableName = variableName; manipulator.stylePropertyParts.Add(newPart); } return manipulator; } } return null; } StylePropertyPart ResolveVariable(StyleValueHandle[] handles) { var property = new StyleProperty { name = propertyName, values = handles }; var index = 0; return ResolveValueOrVariable(styleSheet, element, styleRule, property, ref index, editorExtensionMode); } void UpdateStylesheet() { // Set the contentHash to 0 if the style sheet is empty if (styleSheet.rules == null || styleSheet.rules.Length == 0) styleSheet.contentHash = 0; else // Use a random value instead of computing the real contentHash. // This is faster (for large content) and safe enough to avoid conflicts with other style sheets // since contentHash is used internally as a optimized way to compare style sheets. // However, note that the real contentHash will still be computed on import. styleSheet.contentHash = UnityEngine.Random.Range(1, int.MaxValue); } void EnsureStylePropertyExists() { m_StyleProperty ??= GetStyleProperty(styleRule, propertyName) ?? styleSheet.AddProperty(styleRule, propertyName); } static StyleProperty GetStyleProperty(StyleRule rule, string propertyName) { return rule?.properties.LastOrDefault(property => property.name == propertyName); } static StylePropertyPart CreatePart(StyleSheet styleSheet, StyleValueHandle handle, int offset) { var part = StylePropertyPart.Create(); part.offset = offset; part.handles.Add( new StyleValueHandleContext { styleSheet = styleSheet, handle = handle }); return part; } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StylePropertyManipulator.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/StyleSheetExtensions/StylePropertyManipulator.cs", "repo_id": "UnityCsReference", "token_count": 24548 }
455
// 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.Pool; using UnityEngine.UIElements; namespace Unity.UI.Builder { class BuilderAttributeTypeName : VisualElement { static readonly UnityEngine.Pool.ObjectPool<Label> s_LabelPool = new UnityEngine.Pool.ObjectPool<Label>( () => new Label(), null, l => { l.RemoveFromClassList(s_NamespaceClass); l.RemoveFromClassList(s_TypeNameClass); l.RemoveFromClassList(s_MatchedTokenClass); }); const string s_UssPathNoExt = BuilderConstants.UtilitiesPath + "/TypeField/BuilderAttributeTypeName"; const string s_UssPath = s_UssPathNoExt + ".uss"; const string s_UssDarkPath = s_UssPathNoExt + "Dark.uss"; const string s_UssLightPath = s_UssPathNoExt + "Light.uss"; const string s_BaseClass = "unity-attribute-type-name"; const string s_NamespaceClass = s_BaseClass + "__namespace"; const string s_NamespaceContainerClass = s_NamespaceClass + "-container"; const string s_NamespacePrefixClass = s_NamespaceClass + "-prefix"; const string s_TypeNameClass = s_BaseClass + "__type-name"; const string s_TypeNameContainerClass = s_TypeNameClass + "-container"; const string s_MatchedTokenClass = s_BaseClass + "__matched-token"; readonly VisualElement m_Namespace; readonly VisualElement m_TypeName; readonly Label m_InNamespace; public BuilderAttributeTypeName() { AddToClassList(s_BaseClass); styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(s_UssPath)); if (EditorGUIUtility.isProSkin) styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(s_UssDarkPath)); else styleSheets.Add(BuilderPackageUtilities.LoadAssetAtPath<StyleSheet>(s_UssLightPath)); m_Namespace = new VisualElement(); m_Namespace.AddToClassList(s_NamespaceContainerClass); m_TypeName = new VisualElement(); m_TypeName.AddToClassList(s_TypeNameContainerClass); Add(m_TypeName); Add(m_Namespace); // Trailing spaces are trimmed when measuring the text, so we'll add a class on this particular Label to // force some padding on the right. m_InNamespace = new Label("in"); m_InNamespace.AddToClassList(s_NamespacePrefixClass); } public static IEnumerable<int> AllIndexesOf(string str, string searchString) { var minIndex = str.IndexOf(searchString, StringComparison.InvariantCultureIgnoreCase); while (minIndex != -1) { yield return minIndex; minIndex = str.IndexOf(searchString, minIndex + searchString.Length, StringComparison.InvariantCultureIgnoreCase); } } readonly struct AutoCompleteToken { public AutoCompleteToken(string src, int start, int length, bool matchedToken) { this.source = src; this.startIndex = start; this.length = length; this.isMatchedToken = matchedToken; } public AutoCompleteToken(string src, int start, bool matchedToken) : this(src, start, src.Length - start, matchedToken) { } public readonly string source; public readonly int startIndex; public readonly int length; public readonly bool isMatchedToken; public override string ToString() { return source.Substring(startIndex, length); } } public void ClearType() { this.Query<Label>().ForEach(l => { if (l != m_InNamespace) s_LabelPool.Release(l) ; }); m_TypeName.Clear(); m_Namespace.Clear(); } public void SetType(Type type, string searchString = null) { ClearType(); if (null == type) return; tooltip = type.AssemblyQualifiedName; var fullName = type.FullName; var nsLength = string.IsNullOrEmpty(type.Namespace) ? 0 : type.Namespace.Length + 1; m_Namespace.Add(m_InNamespace); if (nsLength == 0) { var namespaceLabel = s_LabelPool.Get(); namespaceLabel.AddToClassList(s_NamespaceClass); m_Namespace.Add(namespaceLabel); namespaceLabel.text = "global namespace"; } if (string.IsNullOrEmpty(searchString)) { var namespaceLabel = s_LabelPool.Get(); namespaceLabel.AddToClassList(s_NamespaceClass); m_Namespace.Add(namespaceLabel); // Using the source namespace directly here, since we don't want to include the `.` namespaceLabel.text = !string.IsNullOrEmpty(type.Namespace) ? type.Namespace : "global namespace"; var typeNameLabel = s_LabelPool.Get(); m_TypeName.Add(typeNameLabel); typeNameLabel.text = fullName.Substring(nsLength); typeNameLabel.AddToClassList(s_TypeNameClass); return; } var list = ListPool<AutoCompleteToken>.Get(); try { var current = 0; foreach (var index in AllIndexesOf(fullName, searchString)) { if (current != index) list.Add(new AutoCompleteToken(fullName, current, index - current, false)); list.Add(new AutoCompleteToken(fullName, index, searchString.Length, true)); current = index + searchString.Length; } if (current < fullName.Length) list.Add(new AutoCompleteToken(fullName, current, false)); foreach (var part in list) { if (part.startIndex < nsLength) { if (part.startIndex + part.length <= nsLength) { var namespaceLabel = s_LabelPool.Get(); m_Namespace.Add(namespaceLabel); var length = part.length; if (part.startIndex + part.length == nsLength) length -= 1; namespaceLabel.text = part.source.Substring(part.startIndex, length); namespaceLabel.AddToClassList(s_NamespaceClass); namespaceLabel.EnableInClassList(s_MatchedTokenClass, part.isMatchedToken); } else { var namespaceLabel = s_LabelPool.Get(); namespaceLabel.AddToClassList(s_NamespaceClass); m_Namespace.Add(namespaceLabel); namespaceLabel.text = part.source.Substring(part.startIndex, nsLength - part.startIndex - 1); namespaceLabel.EnableInClassList(s_MatchedTokenClass, part.isMatchedToken); var typeNameLabel = s_LabelPool.Get(); m_TypeName.Add(typeNameLabel); typeNameLabel.text = part.source.Substring(nsLength, part.startIndex + part.length - nsLength); typeNameLabel.AddToClassList(s_TypeNameClass); typeNameLabel.EnableInClassList(s_MatchedTokenClass, part.isMatchedToken); } } else { var typeNameLabel = s_LabelPool.Get(); m_TypeName.Add(typeNameLabel); typeNameLabel.text = part.ToString(); typeNameLabel.AddToClassList(s_TypeNameClass); typeNameLabel.EnableInClassList(s_MatchedTokenClass, part.isMatchedToken); } } } finally { ListPool<AutoCompleteToken>.Release(list); } } } }
UnityCsReference/Modules/UIBuilder/Editor/Utilities/TypeField/BuilderAttributeTypeName.cs/0
{ "file_path": "UnityCsReference/Modules/UIBuilder/Editor/Utilities/TypeField/BuilderAttributeTypeName.cs", "repo_id": "UnityCsReference", "token_count": 4487 }
456
// 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; namespace UnityEngine.UIElements { [VisibleToOtherModules("UnityEditor.UIBuilderModule")] internal static class BackgroundPropertyHelper { public static BackgroundPosition ConvertScaleModeToBackgroundPosition(ScaleMode scaleMode = ScaleMode.StretchToFill) { return new BackgroundPosition(BackgroundPositionKeyword.Center); } public static BackgroundRepeat ConvertScaleModeToBackgroundRepeat(ScaleMode scaleMode = ScaleMode.StretchToFill) { return new BackgroundRepeat(Repeat.NoRepeat, Repeat.NoRepeat); } public static BackgroundSize ConvertScaleModeToBackgroundSize(ScaleMode scaleMode = ScaleMode.StretchToFill) { if (scaleMode == ScaleMode.ScaleAndCrop) { return new BackgroundSize(BackgroundSizeType.Cover); } else if (scaleMode == ScaleMode.ScaleToFit) { return new BackgroundSize(BackgroundSizeType.Contain); } else // ScaleMode.StretchToFill { return new BackgroundSize(Length.Percent(100.0f), Length.Percent(100.0f)); } } public static ScaleMode ResolveUnityBackgroundScaleMode(BackgroundPosition backgroundPositionX, BackgroundPosition backgroundPositionY, BackgroundRepeat backgroundRepeat, BackgroundSize backgroundSize, out bool valid) { if (backgroundPositionX == BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleAndCrop) && backgroundPositionY == BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleAndCrop) && backgroundRepeat == BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat(ScaleMode.ScaleAndCrop) && backgroundSize == BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(ScaleMode.ScaleAndCrop)) { valid = true; return ScaleMode.ScaleAndCrop; } else if (backgroundPositionX == BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleToFit) && backgroundPositionY == BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.ScaleToFit) && backgroundRepeat == BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat(ScaleMode.ScaleToFit) && backgroundSize == BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(ScaleMode.ScaleToFit)) { valid = true; return ScaleMode.ScaleToFit; } else if (backgroundPositionX == BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.StretchToFill) && backgroundPositionY == BackgroundPropertyHelper.ConvertScaleModeToBackgroundPosition(ScaleMode.StretchToFill) && backgroundRepeat == BackgroundPropertyHelper.ConvertScaleModeToBackgroundRepeat(ScaleMode.StretchToFill) && backgroundSize == BackgroundPropertyHelper.ConvertScaleModeToBackgroundSize(ScaleMode.StretchToFill)) { valid = true; return ScaleMode.StretchToFill; } else { valid = false; return ScaleMode.StretchToFill; } } } }
UnityCsReference/Modules/UIElements/Core/BackgroundPropertyHelper.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/BackgroundPropertyHelper.cs", "repo_id": "UnityCsReference", "token_count": 1419 }
457
// 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 { /// <summary> /// Base class for general purpose binding extensibility. /// </summary> /// <example> /// The following example creates a custom binding that displays the current time. /// You can bind it to the text field of a Label to create a clock. /// <code source="../../../../Modules/UIElements/Tests/UIElementsExamples/Assets/Examples/CustomBinding_CurrentTime.cs"/> /// </example> [UxmlObject] public abstract partial class CustomBinding : Binding { /// <summary> /// Initializes and returns an instance of <see cref="CustomBinding"/>. /// </summary> protected CustomBinding() { updateTrigger = BindingUpdateTrigger.EveryUpdate; } /// <summary> /// Called when the binding system updates the binding. /// </summary> /// <param name="context">Context object containing the necessary information to resolve a binding.</param> /// <returns>A <see cref="BindingResult"/> indicating if the binding update succeeded or not.</returns> protected internal virtual BindingResult Update(in BindingContext context) { return new BindingResult(BindingStatus.Success); } } }
UnityCsReference/Modules/UIElements/Core/Bindings/CustomBinding.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Bindings/CustomBinding.cs", "repo_id": "UnityCsReference", "token_count": 490 }
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 Unity.Properties; using System.Linq; using UnityEngine.Pool; namespace UnityEngine.UIElements { /// <summary> /// Base collection list view controller. View controllers of this type are meant to take care of data virtualized by any <see cref="BaseListView"/> inheritor. /// </summary> public abstract class BaseListViewController : CollectionViewController { private protected class SerializedObjectListControllerImpl { private ISerializedObjectList serializedObjectList => m_SerializedObjectListGetter?.Invoke(); private Func<ISerializedObjectList> m_SerializedObjectListGetter; private BaseListViewController m_BaseListViewController; internal SerializedObjectListControllerImpl(BaseListViewController baseListViewController, Func<ISerializedObjectList> serializedObjectListGetter) { m_BaseListViewController = baseListViewController; m_SerializedObjectListGetter = serializedObjectListGetter; } public int GetItemsCount() { return serializedObjectList?.Count ?? 0; } internal int GetItemsMinCount() { return serializedObjectList?.minArraySize ?? 0; } public void AddItems(int itemCount) { var previousCount = GetItemsCount(); serializedObjectList.arraySize += itemCount; serializedObjectList.ApplyChanges(); var indices = ListPool<int>.Get(); try { for (var i = 0; i < itemCount; i++) { indices.Add(previousCount + i); } m_BaseListViewController.RaiseItemsAdded(indices); } finally { ListPool<int>.Release(indices); } m_BaseListViewController.RaiseOnSizeChanged(); } internal void RemoveItems(int itemCount) { var previousCount = GetItemsCount(); serializedObjectList.arraySize -= itemCount; var indices = ListPool<int>.Get(); try { for (var i = previousCount - itemCount; i < previousCount; i++) { indices.Add(i); } m_BaseListViewController.RaiseItemsRemoved(indices); } finally { ListPool<int>.Release(indices); } serializedObjectList.ApplyChanges(); m_BaseListViewController.RaiseOnSizeChanged(); } public void RemoveItems(List<int> indices) { indices.Sort(); m_BaseListViewController.RaiseItemsRemoved(indices); var listCount = serializedObjectList.Count; for (var i = indices.Count - 1; i >= 0; i--) { var index = indices[i]; serializedObjectList.RemoveAt(index, listCount); listCount--; } serializedObjectList.ApplyChanges(); m_BaseListViewController.RaiseOnSizeChanged(); } public void RemoveItem(int index) { using (ListPool<int>.Get(out var indices)) { indices.Add(index); m_BaseListViewController.RaiseItemsRemoved(indices); } serializedObjectList.RemoveAt(index); serializedObjectList.ApplyChanges(); m_BaseListViewController.RaiseOnSizeChanged(); } public void ClearItems() { var itemsSourceIndices = Enumerable.Range(0, GetItemsMinCount() - 1); serializedObjectList.arraySize = 0; serializedObjectList.ApplyChanges(); m_BaseListViewController.RaiseItemsRemoved(itemsSourceIndices); m_BaseListViewController.RaiseOnSizeChanged(); } public void Move(int srcIndex, int destIndex) { if (srcIndex == destIndex) return; serializedObjectList.Move(srcIndex, destIndex); serializedObjectList.ApplyChanges(); m_BaseListViewController.RaiseItemIndexChanged(srcIndex, destIndex); } } /// <summary> /// Raised when the <see cref="CollectionViewController.itemsSource"/> size changes. /// </summary> public event Action itemsSourceSizeChanged; /// <summary> /// Raised when an item is added to the <see cref="CollectionViewController.itemsSource"/>. /// </summary> public event Action<IEnumerable<int>> itemsAdded; /// <summary> /// Raised when an item is removed from the <see cref="CollectionViewController.itemsSource"/>. /// </summary> public event Action<IEnumerable<int>> itemsRemoved; /// <summary> /// View for this controller, cast as a <see cref="BaseListView"/>. /// </summary> protected BaseListView baseListView => view as BaseListView; internal override void InvokeMakeItem(ReusableCollectionItem reusableItem) { if (reusableItem is ReusableListViewItem listItem) { listItem.Init(MakeItem(), baseListView.reorderable && baseListView.reorderMode == ListViewReorderMode.Animated); PostInitRegistration(listItem); } } internal void PostInitRegistration(ReusableListViewItem listItem) { listItem.bindableElement.style.position = Position.Relative; listItem.bindableElement.style.flexBasis = StyleKeyword.Initial; listItem.bindableElement.style.marginTop = 0f; listItem.bindableElement.style.marginBottom = 0f; listItem.bindableElement.style.paddingTop = 0f; listItem.bindableElement.style.flexGrow = 0f; listItem.bindableElement.style.flexShrink = 0f; if (baseListView.autoAssignSource) { listItem.rootElement.dataSource = itemsSource; } } internal override void InvokeBindItem(ReusableCollectionItem reusableItem, int index) { if (baseListView.autoAssignSource) { reusableItem.rootElement.dataSourcePath = PropertyPath.FromIndex(index); } if (reusableItem is ReusableListViewItem listItem) { var usesAnimatedDragger = baseListView.reorderable && baseListView.reorderMode == ListViewReorderMode.Animated; listItem.UpdateDragHandle(usesAnimatedDragger && NeedsDragHandle(index)); } base.InvokeBindItem(reusableItem, index); } /// <summary> /// Returns whether this item needs a drag handle or not with the Animated drag mode. /// </summary> /// <param name="index">Item index.</param> /// <returns>Whether or not the drag handle is needed.</returns> public virtual bool NeedsDragHandle(int index) { return true; } /// <summary> /// Adds a certain amount of items at the end of the collection. /// </summary> /// <param name="itemCount">The number of items to add.</param> public virtual void AddItems(int itemCount) { if (itemCount <= 0) return; EnsureItemSourceCanBeResized(); var previousCount = GetItemsCount(); var indices = ListPool<int>.Get(); try { if (itemsSource.IsFixedSize) { itemsSource = AddToArray((Array)itemsSource, itemCount); for (var i = 0; i < itemCount; i++) { indices.Add(previousCount + i); } } else { var sourceType = itemsSource.GetType(); bool IsGenericList(Type t) => t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IList<>); var listType = sourceType.GetInterfaces().FirstOrDefault(IsGenericList); if (listType != null && listType.GetGenericArguments()[0].IsValueType) { var elementValueType = listType.GetGenericArguments()[0]; for (var i = 0; i < itemCount; i++) { indices.Add(previousCount + i); itemsSource.Add(Activator.CreateInstance(elementValueType)); } } else { for (var i = 0; i < itemCount; i++) { indices.Add(previousCount + i); itemsSource.Add(default); } } } RaiseItemsAdded(indices); } finally { ListPool<int>.Release(indices); } RaiseOnSizeChanged(); } /// <summary> /// Moves an item in the source. /// </summary> /// <param name="index">The source index.</param> /// <param name="newIndex">The destination index.</param> public virtual void Move(int index, int newIndex) { if (itemsSource == null) return; if (index == newIndex) return; var minIndex = Mathf.Min(index, newIndex); var maxIndex = Mathf.Max(index, newIndex); if (minIndex < 0 || maxIndex >= itemsSource.Count) return; var destinationIndex = newIndex; var direction = newIndex < index ? 1 : -1; while (Mathf.Min(index, newIndex) < Mathf.Max(index, newIndex)) { Swap(index, newIndex); newIndex += direction; } RaiseItemIndexChanged(index, destinationIndex); } /// <summary> /// Removes an item from the source, by index. /// </summary> /// <param name="index">The item index.</param> public virtual void RemoveItem(int index) { using (ListPool<int>.Get(out var indices)) { indices.Add(index); RemoveItems(indices); } } /// <summary> /// Removes items from the source, by indices. /// </summary> /// <param name="indices">A list of indices to remove.</param> public virtual void RemoveItems(List<int> indices) { EnsureItemSourceCanBeResized(); if (indices == null) return; indices.Sort(); RaiseItemsRemoved(indices); if (itemsSource.IsFixedSize) { itemsSource = RemoveFromArray((Array)itemsSource, indices); } else { for (var i = indices.Count - 1; i >= 0; i--) { itemsSource.RemoveAt(indices[i]); } } RaiseOnSizeChanged(); } internal virtual void RemoveItems(int itemCount) { if (itemCount <= 0) return; var previousCount = GetItemsCount(); var indices = ListPool<int>.Get(); try { var newItemCount = previousCount - itemCount; for (var i = newItemCount; i < previousCount; i++) { indices.Add(i); } RemoveItems(indices); } finally { ListPool<int>.Release(indices); } } /// <summary> /// Removes all items from the source. /// </summary> public virtual void ClearItems() { if (itemsSource == null) return; EnsureItemSourceCanBeResized(); var itemsSourceIndices = Enumerable.Range(0, itemsSource.Count - 1); itemsSource.Clear(); RaiseItemsRemoved(itemsSourceIndices); RaiseOnSizeChanged(); } /// <summary> /// Invokes the <see cref="itemsSourceSizeChanged"/> event. /// </summary> protected void RaiseOnSizeChanged() { itemsSourceSizeChanged?.Invoke(); } /// <summary> /// Invokes the <see cref="itemsAdded"/> event. /// </summary> protected void RaiseItemsAdded(IEnumerable<int> indices) { itemsAdded?.Invoke(indices); } /// <summary> /// Invokes the <see cref="itemsRemoved"/> event. /// </summary> protected void RaiseItemsRemoved(IEnumerable<int> indices) { itemsRemoved?.Invoke(indices); } static Array AddToArray(Array source, int itemCount) { var elementType = source.GetType().GetElementType(); if (elementType == null) throw new InvalidOperationException("Cannot resize source, because its size is fixed."); var newItemsSource = Array.CreateInstance(elementType, source.Length + itemCount); Array.Copy(source, newItemsSource, source.Length); return newItemsSource; } // Requires the list to be sorted without duplicates. static Array RemoveFromArray(Array source, List<int> indicesToRemove) { var count = source.Length; var newCount = count - indicesToRemove.Count; if (newCount < 0) throw new InvalidOperationException("Cannot remove more items than the current count from source."); var elementType = source.GetType().GetElementType(); if (newCount == 0) return Array.CreateInstance(elementType, 0); var newSource = Array.CreateInstance(elementType, newCount); var newSourceIndex = 0; var toRemove = 0; for (var index = 0; index < source.Length; ++index) { if (toRemove < indicesToRemove.Count && indicesToRemove[toRemove] == index) { ++toRemove; continue; } newSource.SetValue(source.GetValue(index), newSourceIndex); ++newSourceIndex; } return newSource; } void Swap(int lhs, int rhs) { (itemsSource[lhs], itemsSource[rhs]) = (itemsSource[rhs], itemsSource[lhs]); } void EnsureItemSourceCanBeResized() { var itemsSourceType = itemsSource?.GetType(); var itemsSourceIsArray = itemsSourceType?.IsArray ?? false; if (itemsSource == null || itemsSource.IsFixedSize && !itemsSourceIsArray) throw new InvalidOperationException("Cannot add or remove items from source, because it is null or its size is fixed."); } } }
UnityCsReference/Modules/UIElements/Core/Collections/Controllers/BaseListViewController.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Controllers/BaseListViewController.cs", "repo_id": "UnityCsReference", "token_count": 7833 }
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 UnityEngine.UIElements.Experimental; namespace UnityEngine.UIElements { class ReusableCollectionItem { public const int UndefinedIndex = -1; public virtual VisualElement rootElement => bindableElement; public VisualElement bindableElement { get; protected set; } public ValueAnimation<StyleValues> animator { get; set; } public int index { get; set; } public int id { get; set; } // Identifies an item as an invisible duplicate of the dragged item. internal bool isDragGhost { get; private set; } public event Action<ReusableCollectionItem> onGeometryChanged; protected EventCallback<GeometryChangedEvent> m_GeometryChangedEventCallback; internal event Action<ReusableCollectionItem> onDestroy; public ReusableCollectionItem() { index = id = UndefinedIndex; m_GeometryChangedEventCallback = OnGeometryChanged; } public virtual void Init(VisualElement item) { bindableElement = item; } public virtual void PreAttachElement() { rootElement.AddToClassList(BaseVerticalCollectionView.itemUssClassName); rootElement.RegisterCallback(m_GeometryChangedEventCallback); } public virtual void DetachElement() { rootElement.RemoveFromClassList(BaseVerticalCollectionView.itemUssClassName); rootElement.UnregisterCallback(m_GeometryChangedEventCallback); rootElement?.RemoveFromHierarchy(); SetSelected(false); SetDragGhost(false); index = id = UndefinedIndex; } public virtual void DestroyElement() { onDestroy?.Invoke(this); } public virtual void SetSelected(bool selected) { if (selected) { rootElement.AddToClassList(BaseVerticalCollectionView.itemSelectedVariantUssClassName); rootElement.pseudoStates |= PseudoStates.Checked; } else { rootElement.RemoveFromClassList(BaseVerticalCollectionView.itemSelectedVariantUssClassName); rootElement.pseudoStates &= ~PseudoStates.Checked; } } public virtual void SetDragGhost(bool dragGhost) { isDragGhost = dragGhost; rootElement.style.maxHeight = isDragGhost ? 0 : StyleKeyword.Initial; bindableElement.style.display = isDragGhost ? DisplayStyle.None : DisplayStyle.Flex; } protected void OnGeometryChanged(GeometryChangedEvent evt) { onGeometryChanged?.Invoke(this); } } }
UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableCollectionItem.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Collections/Virtualization/ReusableCollectionItem.cs", "repo_id": "UnityCsReference", "token_count": 1209 }
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 System.Collections.Generic; using UnityEngine.Scripting.APIUpdating; namespace UnityEngine.UIElements { /// <summary> /// A <see cref="Bounds"/> editor field. For more information, refer to [[wiki:UIE-uxml-element-BoundsField|UXML element BoundsField]]. /// </summary> [MovedFrom(true, UpgradeConstants.EditorNamespace, UpgradeConstants.EditorAssembly)] public class BoundsField : BaseField<Bounds> { [UnityEngine.Internal.ExcludeFromDocs, Serializable] public new class UxmlSerializedData : BaseField<Bounds>.UxmlSerializedData, IUxmlSerializedDataCustomAttributeHandler { public override object CreateInstance() => new BoundsField(); void IUxmlSerializedDataCustomAttributeHandler.SerializeCustomAttributes(IUxmlAttributes bag, HashSet<string> handledAttributes) { // Its possible to only specify 1 attribute so we need to check them all and if we get at least 1 match then we can proceed. int foundAttributeCounter = 0; var cx = UxmlUtility.TryParseFloatAttribute("cx", bag, ref foundAttributeCounter); var cy = UxmlUtility.TryParseFloatAttribute("cy", bag, ref foundAttributeCounter); var cz = UxmlUtility.TryParseFloatAttribute("cz", bag, ref foundAttributeCounter); var ex = UxmlUtility.TryParseFloatAttribute("ex", bag, ref foundAttributeCounter); var ey = UxmlUtility.TryParseFloatAttribute("ey", bag, ref foundAttributeCounter); var ez = UxmlUtility.TryParseFloatAttribute("ez", bag, ref foundAttributeCounter); if (foundAttributeCounter > 0) { Value = new Bounds(new Vector3(cx, cy, cz), new Vector3(ex, ey, ez)); handledAttributes.Add("value"); if (bag is UxmlAsset uxmlAsset) { uxmlAsset.RemoveAttribute("cx"); uxmlAsset.RemoveAttribute("cy"); uxmlAsset.RemoveAttribute("cz"); uxmlAsset.RemoveAttribute("ex"); uxmlAsset.RemoveAttribute("ey"); uxmlAsset.RemoveAttribute("ez"); uxmlAsset.SetAttribute("value", UxmlUtility.ValueToString(Value)); } } } } /// <summary> /// Instantiates a <see cref="BoundsField"/> 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<BoundsField, UxmlTraits> {} /// <summary> /// Defines <see cref="UxmlTraits"/> for the <see cref="BoundsField"/>. /// </summary> [Obsolete("UxmlTraits is deprecated and will be removed. Use UxmlElementAttribute instead.", false)] public new class UxmlTraits : BaseField<Bounds>.UxmlTraits { UxmlFloatAttributeDescription m_CenterXValue = new UxmlFloatAttributeDescription { name = "cx" }; UxmlFloatAttributeDescription m_CenterYValue = new UxmlFloatAttributeDescription { name = "cy" }; UxmlFloatAttributeDescription m_CenterZValue = new UxmlFloatAttributeDescription { name = "cz" }; UxmlFloatAttributeDescription m_ExtentsXValue = new UxmlFloatAttributeDescription { name = "ex" }; UxmlFloatAttributeDescription m_ExtentsYValue = new UxmlFloatAttributeDescription { name = "ey" }; UxmlFloatAttributeDescription m_ExtentsZValue = new UxmlFloatAttributeDescription { name = "ez" }; /// <summary> /// Initialize <see cref="BoundsField"/> properties using values from the attribute bag. /// </summary> /// <param name="ve">The object to initialize.</param> /// <param name="bag">The attribute bag.</param> /// <param name="cc">The creation context; unused.</param> public override void Init(VisualElement ve, IUxmlAttributes bag, CreationContext cc) { base.Init(ve, bag, cc); BoundsField f = (BoundsField)ve; f.SetValueWithoutNotify(new Bounds( new Vector3(m_CenterXValue.GetValueFromBag(bag, cc), m_CenterYValue.GetValueFromBag(bag, cc), m_CenterZValue.GetValueFromBag(bag, cc)), new Vector3(m_ExtentsXValue.GetValueFromBag(bag, cc), m_ExtentsYValue.GetValueFromBag(bag, cc), m_ExtentsZValue.GetValueFromBag(bag, cc)))); } } /// <summary> /// USS class name of elements of this type. /// </summary> public new static readonly string ussClassName = "unity-bounds-field"; /// <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> /// USS class name of center fields in elements of this type. /// </summary> public static readonly string centerFieldUssClassName = ussClassName + "__center-field"; /// <summary> /// USS class name of extents fields in elements of this type. /// </summary> public static readonly string extentsFieldUssClassName = ussClassName + "__extents-field"; private Vector3Field m_CenterField; private Vector3Field m_ExtentsField; /// <summary> /// Initializes and returns an instance of BoundsField. /// </summary> public BoundsField() : this(null) {} /// <summary> /// Initializes and returns an instance of BoundsField. /// </summary> /// <param name="label">The text to use as a label.</param> public BoundsField(string label) : base(label, null) { delegatesFocus = false; visualInput.focusable = false; AddToClassList(ussClassName); visualInput.AddToClassList(inputUssClassName); labelElement.AddToClassList(labelUssClassName); m_CenterField = new Vector3Field("Center"); m_CenterField.name = "unity-m_Center-input"; m_CenterField.delegatesFocus = true; m_CenterField.AddToClassList(centerFieldUssClassName); m_CenterField.RegisterValueChangedCallback(e => { Bounds current = value; current.center = e.newValue; value = current; }); visualInput.hierarchy.Add(m_CenterField); m_ExtentsField = new Vector3Field("Extents"); m_ExtentsField.name = "unity-m_Extent-input"; m_ExtentsField.delegatesFocus = true; m_ExtentsField.AddToClassList(extentsFieldUssClassName); m_ExtentsField.RegisterValueChangedCallback(e => { Bounds current = value; current.extents = e.newValue; value = current; }); visualInput.hierarchy.Add(m_ExtentsField); } public override void SetValueWithoutNotify(Bounds newValue) { base.SetValueWithoutNotify(newValue); m_CenterField.SetValueWithoutNotify(rawValue.center); m_ExtentsField.SetValueWithoutNotify(rawValue.extents); } protected override void UpdateMixedValueContent() { m_CenterField.showMixedValue = showMixedValue; m_ExtentsField.showMixedValue = showMixedValue; } } }
UnityCsReference/Modules/UIElements/Core/Controls/BoundsField.cs/0
{ "file_path": "UnityCsReference/Modules/UIElements/Core/Controls/BoundsField.cs", "repo_id": "UnityCsReference", "token_count": 3443 }
461